From efeee03b0017020c90119269aaafaf62c9e5c39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 20:42:36 +0100 Subject: [PATCH 1/5] refactor(harmonyos): move HarmonyOS into the managed platform plugin The packed core no longer answers for the HarmonyOS family. `@agent-device/harmonyos` is a managed optional platform plugin like the web and Vega plugins: the composition resolves it through the same one-shot module selection, and a request that names `--platform harmonyos` without it answers `plugin-not-installed` with its install command, while unfiltered discovery and doctor skip the family. The family's mechanics move with it. HDC device discovery, the ArkUI interactor, interaction handlers, app lifecycle and logs, the toolchain probe, the plugin-owned HDC screen recorder and the RSS memory sampler all live in the package now; the plugin reads the documented toolchain roots from the host environment the composition hands it and never touches `process.env`. Core keeps only the canonical platform vocabulary. --- package.json | 3 +- packages/build-config/src/index.ts | 47 ++++++ packages/contracts/src/perf-runtime-host.ts | 5 - packages/contracts/src/platform-plugin.ts | 38 ++++- .../src/screen-recording-runtime-host.ts | 28 ---- packages/platform-harmonyos/build.mjs | 14 ++ packages/platform-harmonyos/package.json | 58 +++++-- packages/platform-harmonyos/src/index.test.ts | 141 ++++++++++++++++ packages/platform-harmonyos/src/index.ts | 157 +++++++----------- .../src/interactor-facade.ts | 10 -- .../platform-harmonyos/src/interactor.test.ts | 24 +-- packages/platform-harmonyos/src/interactor.ts | 12 +- .../src/inventory-config.ts | 8 - packages/platform-harmonyos/src/inventory.ts | 8 +- .../src/perf/runtime.test.ts | 6 +- .../platform-harmonyos/src/perf/runtime.ts | 14 +- .../src/recording/recorder.ts | 55 ++++-- .../src/recording/runtime.fixtures.ts | 43 +++-- .../src/recording/runtime.ts | 95 ++++++----- packages/platform-harmonyos/src/runtime.ts | 4 +- .../platform-harmonyos/test/package-smoke.mjs | 122 ++++++++++++++ packages/platform-harmonyos/tsconfig.json | 4 +- packages/platform-vega/build.mjs | 34 +--- packages/platform-web/build.mjs | 34 +--- packages/plugins/src/platform.ts | 20 ++- packages/plugins/src/validate.ts | 17 ++ pnpm-lock.yaml | 12 +- scripts/capability-matrix/collect.ts | 3 +- scripts/check-package.ts | 9 + .../layering/daemon-platform-boundary.test.ts | 4 +- .../layering/platform-package-policy.test.ts | 34 +++- scripts/layering/platform-package-policy.ts | 5 +- scripts/layering/root-module-zones.ts | 1 - .../contracts/platform-plugin-parity.test.ts | 14 +- src/core/interactors/register-builtins.ts | 10 -- src/daemon-composition.ts | 4 +- ...orm-runtime-harmonyos-provider.fixtures.ts | 35 ++++ src/platform-runtime-host-diagnostics.test.ts | 69 ++++++++ src/platform-runtime-host-diagnostics.ts | 30 ++-- src/platform-runtime-host.ts | 8 +- src/platform-runtime-operation-host.ts | 4 +- src/platform-runtime-perf-host.test.ts | 3 +- src/platform-runtime-perf-host.ts | 7 +- ...time-screen-recording-harmony-host.test.ts | 44 ----- src/platform-runtime-screen-recording-host.ts | 24 --- src/platform-runtime-toolchain-host.test.ts | 54 +++--- src/platform-runtime-toolchain-host.ts | 13 +- src/platform-runtime.test.ts | 7 +- src/platform-runtime.ts | 20 +-- src/platform-runtime/platform-plugins.ts | 19 +++ test/repo-guards/npm-package-scripts.test.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/installation.md | 15 +- website/docs/docs/quick-start.md | 2 +- 54 files changed, 938 insertions(+), 517 deletions(-) create mode 100644 packages/platform-harmonyos/build.mjs create mode 100644 packages/platform-harmonyos/src/index.test.ts delete mode 100644 packages/platform-harmonyos/src/interactor-facade.ts delete mode 100644 packages/platform-harmonyos/src/inventory-config.ts rename src/platform-runtime-screen-recording-harmony-host.ts => packages/platform-harmonyos/src/recording/recorder.ts (52%) create mode 100644 packages/platform-harmonyos/test/package-smoke.mjs create mode 100644 src/platform-runtime-harmonyos-provider.fixtures.ts delete mode 100644 src/platform-runtime-screen-recording-harmony-host.test.ts diff --git a/package.json b/package.json index 75cbf7b545..fb209ff90f 100644 --- a/package.json +++ b/package.json @@ -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 && 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 && 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", "generate:command-docs": "node --experimental-strip-types scripts/command-docs/generate.ts --write", @@ -328,7 +328,6 @@ "@agent-device/kernel": "workspace:*", "@agent-device/platform-android": "workspace:*", "@agent-device/platform-apple": "workspace:*", - "@agent-device/platform-harmonyos": "workspace:*", "@agent-device/platform-linux": "workspace:*", "@agent-device/plugins": "workspace:*", "@agent-device/provider-limrun": "workspace:*", diff --git a/packages/build-config/src/index.ts b/packages/build-config/src/index.ts index 38ca7c8926..e9ba70e3fa 100644 --- a/packages/build-config/src/index.ts +++ b/packages/build-config/src/index.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs'; import type { InputOptions } from 'rolldown'; export const strictBundlerInputOptions: InputOptions = { @@ -19,3 +20,49 @@ export const providerPluginBuildConfig = { deps: { alwaysBundle: [/^@agent-device\//] }, inputOptions: strictBundlerInputOptions, }; + +/** + * The bundler options every managed platform plugin package builds with: its own `agent-device` + * entry, emitted types, and `agent-device/plugins` kept external because the running core owns + * that contract. Each package's `build.mjs` spreads this and calls `build`. + */ +export const managedPlatformPluginBuildConfig = { + ...providerPluginBuildConfig, + config: false, + dts: true, + tsconfig: '../../tsconfig.lib.json', + deps: { + ...providerPluginBuildConfig.deps, + neverBundle: ['agent-device/plugins'], + }, +}; + +/** + * Checks a managed platform plugin's default-exported factory against the `agent-device` claim in + * its own package.json — the same pair the loader reads at install time, so a package that + * contributes another family, or a stale contract version, fails its build rather than its users. + * The caller passes its `package.json` URL and the factory it imported. + */ +export function assertManagedPlatformPluginFactory( + packageJsonUrl: URL, + factory: () => { + apiVersion: unknown; + contributes: readonly { kind: unknown; family: unknown }[]; + }, + label: string, +): void { + const manifest = JSON.parse(readFileSync(packageJsonUrl, 'utf8'))['agent-device'] as { + apiVersion: unknown; + platform: unknown; + }; + const { apiVersion, contributes } = factory(); + const [platform] = contributes; + if ( + apiVersion !== manifest.apiVersion || + contributes.length !== 1 || + platform?.kind !== 'platform' || + platform.family !== manifest.platform + ) { + throw new Error(`The managed ${label} factory must match its package claim`); + } +} diff --git a/packages/contracts/src/perf-runtime-host.ts b/packages/contracts/src/perf-runtime-host.ts index 68dea58315..c23febbb45 100644 --- a/packages/contracts/src/perf-runtime-host.ts +++ b/packages/contracts/src/perf-runtime-host.ts @@ -44,13 +44,8 @@ export type AndroidPerfHost = NativeCaptureHost & writeProfileReport(device: DeviceInfo, input: PerfProfileReportInput): Promise; }>; -export type HarmonyPerfHost = Readonly<{ - sampleMemory(device: DeviceInfo, appId: string): Promise; -}>; - /** Family-specific native mechanics; platform packages own policy and operation construction. */ export type PerfRuntimeHost = Readonly<{ apple: ApplePerfHost; android: AndroidPerfHost; - harmony: HarmonyPerfHost; }>; diff --git a/packages/contracts/src/platform-plugin.ts b/packages/contracts/src/platform-plugin.ts index 995a7ccf07..e6f0aaa55f 100644 --- a/packages/contracts/src/platform-plugin.ts +++ b/packages/contracts/src/platform-plugin.ts @@ -7,7 +7,7 @@ import type { WebProvider } from './web-provider.ts'; import type { VegaToolProvider } from './vega-tool-provider.ts'; import type { AppError } from '@agent-device/kernel/errors'; import type { DeviceInfo, Platform, PlatformSelector } from '@agent-device/kernel/device'; -import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { PlatformGatedProviderResolverKey } from './platform-providers.ts'; import type { Interactor, RunnerContext } from './interactor-types.ts'; @@ -113,6 +113,41 @@ export type VegaPlatformSelection = Readonly<{ get(): VegaPlatformRegistration; }>; +/** + * What the core asks of the HarmonyOS plugin. The toolchain probe answers `doctor --platform + * harmonyos`; the toolchain preparation runs the plugin's own device discovery and log streaming, + * which need the host's documented SDK roots. Every other HarmonyOS operation — HDC discovery, + * probing, interaction, capture, recording, performance — the package owns. + */ +export type HarmonyPlatformOperations = Readonly<{ + toolchainCheck(): Promise; + /** + * Prepends the HarmonyOS toolchain roots that hold an `hdc` binary to `env`'s PATH, so a spawn + * sees the same HDC an interactive shell does. The core hands over the host environment it + * captured: the plugin must not read `process.env` itself (ADR 0019). + */ + prepareToolchain(env: EnvMap): Promise; +}>; + +export type HarmonyPlatformRegistration = Readonly<{ + family: 'harmonyos'; + inventoryModule: InventoryPlatformModule<'harmonyos'>; + runtimeModule: PlatformRuntimeModule & { readonly family: 'harmonyos' }; + createInteractor: PlatformPlugin['createInteractor']; + operations: HarmonyPlatformOperations; +}>; + +/** + * How the running process answers for the HarmonyOS family, installed or not. `get()` raises the + * selection's own typed outcome when the plugin is absent or failed to load, and `toolchainCheck` + * of the toolchain row comes from it either way: `doctor --platform harmonyos` names the install + * command rather than reporting nothing. + */ +export type HarmonyPlatformSelection = Readonly<{ + active?: HarmonyPlatformRegistration; + get(): HarmonyPlatformRegistration; +}>; + export type PlatformPluginSet = PlatformModuleRegistry<{ family: Platform; plugin: Plugin }>; @@ -120,6 +155,7 @@ export type PlatformModuleSelection = Readonly<{ interactors: PlatformPluginSet; web: WebPlatformSelection; vega: VegaPlatformSelection; + harmony: HarmonyPlatformSelection; inventoryModules: readonly InventoryPlatformModule[]; runtimeModules: readonly PlatformRuntimeModule[]; reportAbsent(family: Platform): AppError; diff --git a/packages/contracts/src/screen-recording-runtime-host.ts b/packages/contracts/src/screen-recording-runtime-host.ts index 0ef6b91402..8a44abdd19 100644 --- a/packages/contracts/src/screen-recording-runtime-host.ts +++ b/packages/contracts/src/screen-recording-runtime-host.ts @@ -203,33 +203,6 @@ export type AndroidScreenRecordingHost = Readonly<{ resolve(device: DeviceInfo): Promise; }>; -export type HarmonyScreenRecordingHost = Readonly<{ - start(device: DeviceInfo, fileName: string, signal?: AbortSignal): Promise; - stop(device: DeviceInfo, signal?: AbortSignal): Promise; - findMedia( - device: DeviceInfo, - fileName: string, - signal?: AbortSignal, - ): Promise; - stageMedia( - device: DeviceInfo, - input: Readonly<{ mediaUri: string; remotePath: string }>, - signal?: AbortSignal, - ): Promise; - stagedFileSize( - device: DeviceInfo, - remotePath: string, - signal?: AbortSignal, - ): Promise; - pull( - device: DeviceInfo, - input: Readonly<{ remotePath: string; outputPath: string }>, - signal?: AbortSignal, - ): Promise; - remove(device: DeviceInfo, remotePath: string, signal?: AbortSignal): Promise; - removeMedia(device: DeviceInfo, mediaUri: string, signal?: AbortSignal): Promise; -}>; - export type WebScreenRecordingTransport = Readonly<{ start(outputPath: string, signal?: AbortSignal): Promise; stop(signal?: AbortSignal): Promise; @@ -283,7 +256,6 @@ export type ScreenRecordingOutputHost = Readonly<{ export type ScreenRecordingRuntimeHost = Readonly<{ apple: AppleScreenRecordingHost; android: AndroidScreenRecordingHost; - harmony: HarmonyScreenRecordingHost; web: WebScreenRecordingHost; outputs: ScreenRecordingOutputHost; finalize: ScreenRecordingFinalizer; diff --git a/packages/platform-harmonyos/build.mjs b/packages/platform-harmonyos/build.mjs new file mode 100644 index 0000000000..e4a277d603 --- /dev/null +++ b/packages/platform-harmonyos/build.mjs @@ -0,0 +1,14 @@ +import { build } from 'tsdown'; +import { + assertManagedPlatformPluginFactory, + managedPlatformPluginBuildConfig, +} from '@agent-device/build-config'; +import harmonyPlatformPlugin from './src/index.ts'; + +assertManagedPlatformPluginFactory( + new URL('./package.json', import.meta.url), + harmonyPlatformPlugin, + 'HarmonyOS', +); + +await build(managedPlatformPluginBuildConfig); diff --git a/packages/platform-harmonyos/package.json b/packages/platform-harmonyos/package.json index 8c8a69d019..3f8fda37bc 100644 --- a/packages/platform-harmonyos/package.json +++ b/packages/platform-harmonyos/package.json @@ -1,27 +1,53 @@ { - "name": "@agent-device/platform-harmonyos", - "version": "0.0.0", + "name": "@agent-device/harmonyos", + "version": "0.22.0-dev", "private": true, "type": "module", - "description": "HarmonyOS-family platform runtime metadata and implementations for agent-device.", - "dependencies": { + "description": "Managed HarmonyOS 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/provision-kit": "workspace:*", + "@agent-device/test-kit": "workspace:*", + "agent-device": "workspace:*" }, - "devDependencies": { - "@agent-device/test-kit": "workspace:*" + "engines": { + "node": ">=22.12" }, - "exports": { - ".": { - "types": "./src/index.ts", - "default": "./src/index.ts" + "files": [ + "dist" + ], + "license": "MIT", + "agent-device": { + "apiVersion": 3, + "platform": "harmonyos" + }, + "scripts": { + "build": "node --experimental-strip-types build.mjs", + "prepack": "pnpm build" + }, + "publishConfig": { + "exports": { + "./agent-device": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + } }, - "./interactor": { - "types": "./src/interactor-facade.ts", - "default": "./src/interactor-facade.ts" - } - } + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/callstack/agent-device.git", + "directory": "packages/platform-harmonyos" + }, + "homepage": "https://agent-device.dev/docs/commands#harmonyos-command-boundary" } diff --git a/packages/platform-harmonyos/src/index.test.ts b/packages/platform-harmonyos/src/index.test.ts new file mode 100644 index 0000000000..f7877a9f3e --- /dev/null +++ b/packages/platform-harmonyos/src/index.test.ts @@ -0,0 +1,141 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { HarmonyPlatformRegistration } from '@agent-device/contracts/platform-plugin'; +import type { DeviceInventoryHostFor } from '@agent-device/contracts/platform-runtime-host'; +import type { PlatformHost } from 'agent-device/plugins'; +import harmonyPlatformPlugin from './index.ts'; + +const HARMONY_DEVICE = { + platform: 'harmonyos', + id: 'harmony-device', + name: 'HarmonyOS', + kind: 'device', + target: 'mobile', + booted: true, +} satisfies DeviceInfo; + +/** The host the composition hands the plugin: one captured environment, no device authority. */ +function createPluginHost(env: Record = {}): PlatformHost { + return { + env, + cwd: '/host-cwd', + stateDir: '/host-state', + runCommand: async () => ({ stdout: '', stderr: '', exitCode: 0 }), + emitDiagnostic: () => undefined, + withDiagnosticTimer: async (_label, run) => await run(), + } as unknown as PlatformHost; +} + +function setupHarmonyPlatform(host?: PlatformHost): HarmonyPlatformRegistration { + return harmonyPlatformPlugin().contributes[0].setup( + host ?? createPluginHost(), + ) as HarmonyPlatformRegistration; +} + +const scope = { + signal: new AbortController().signal, + diagnostics: { emit: () => undefined }, + progress: { report: () => undefined }, +}; + +test('the HarmonyOS package contributes the HarmonyOS platform family', () => { + const plugin = harmonyPlatformPlugin(); + const [contribution] = plugin.contributes; + + assert.equal(plugin.apiVersion, 3); + assert.equal(plugin.contributes.length, 1); + assert.equal(contribution.kind, 'platform'); + assert.equal(contribution.family, 'harmonyos'); +}); + +test('setup registers the HarmonyOS modules and operations', () => { + const registration = setupHarmonyPlatform(); + + assert.equal(registration.family, 'harmonyos'); + assert.equal(registration.inventoryModule.family, 'harmonyos'); + assert.equal(registration.runtimeModule.family, 'harmonyos'); + assert.equal(typeof registration.inventoryModule.loadInventory, 'function'); + assert.equal(typeof registration.runtimeModule.loadRuntime, 'function'); + assert.equal(typeof registration.operations.toolchainCheck, 'function'); + assert.equal(typeof registration.operations.prepareToolchain, 'function'); +}); + +test('setup hands the host it was set up with to the inventory module it registers', async () => { + // The plugin never reads `process.env`: the documented HarmonyOS roots reach discovery through + // the setup host only. Discovery asks the host to prepare its toolchain first, then resolves HDC + // through the roots and PATH that preparation owns, so a host without either answers its own + // missing-toolchain reason. The process environment names a different root on purpose, so an + // implementation that read it instead of the host fails here on any machine. + const originalRoots = { + HDC_SDK_PATH: process.env.HDC_SDK_PATH, + DEVECO_SDK_HOME: process.env.DEVECO_SDK_HOME, + HARMONYOS_COMMAND_LINE_TOOLS: process.env.HARMONYOS_COMMAND_LINE_TOOLS, + }; + process.env.HDC_SDK_PATH = '/process-tools/hdc'; + process.env.DEVECO_SDK_HOME = '/process-tools/deveco'; + delete process.env.HARMONYOS_COMMAND_LINE_TOOLS; + try { + const registration = setupHarmonyPlatform( + createPluginHost({ + HDC_SDK_PATH: ' /host-tools/hdc ', + DEVECO_SDK_HOME: '/host-tools/deveco', + HARMONYOS_COMMAND_LINE_TOOLS: '', + PATH: '/bin', + }), + ); + const lookedUp: string[] = []; + let prepares = 0; + const inventoryHost = { + toolchains: { + prepare: async () => { + prepares += 1; + }, + }, + commands: { + which: async (command: string) => { + lookedUp.push(command); + return undefined; + }, + run: async () => ({ stdout: '', stderr: '', exitCode: 0 }), + }, + files: { + isExecutable: async (candidate: string) => { + lookedUp.push(candidate); + return false; + }, + }, + hostOs: 'darwin', + hostName: 'test-host', + } as unknown as DeviceInventoryHostFor<'harmonyos'>; + + const source = await registration.inventoryModule.loadInventory(inventoryHost); + await assert.rejects( + async () => await source.discover({}, scope), + (error: Error) => error.message === 'hdc not found in PATH', + ); + assert.equal(prepares, 1); + // Each root the setup host named is probed, trimmed, and derived; the empty root and the + // process environment's roots are not. + assert.deepEqual(lookedUp, [ + '/host-tools/hdc/hdc', + '/host-tools/deveco/default/openharmony/toolchains/hdc', + 'hdc', + ]); + } finally { + Object.assign(process.env, originalRoots); + if (originalRoots.HARMONYOS_COMMAND_LINE_TOOLS === undefined) + delete process.env.HARMONYOS_COMMAND_LINE_TOOLS; + } +}); + +test('setup creates the HarmonyOS interactor lazily', async () => { + const registration = setupHarmonyPlatform(); + const interactor = await registration.createInteractor(HARMONY_DEVICE, {}, { + env: {}, + cwd: '/host-cwd', + }); + + assert.equal(typeof interactor.snapshot, 'function'); + assert.equal(typeof interactor.tap, 'function'); +}); diff --git a/packages/platform-harmonyos/src/index.ts b/packages/platform-harmonyos/src/index.ts index 588d7659c9..aa03ea7cf8 100644 --- a/packages/platform-harmonyos/src/index.ts +++ b/packages/platform-harmonyos/src/index.ts @@ -1,28 +1,18 @@ +import type { PlatformContribution, PlatformHost, PlatformSetup } from 'agent-device/plugins'; import type { InventoryPlatformModule, PlatformModuleMetadata, } from '@agent-device/contracts/platform-module'; import type { PlatformRuntimeModule } from '@agent-device/contracts/platform-runtime-operations'; -import type { HarmonyInventoryConfig } from './inventory-config.ts'; - -// fallow-ignore-next-line code-duplication -type DeferredFunction = (...args: never[]) => unknown; -type Deferred = ( - ...args: Parameters -) => Promise>>; - -function deferred(load: () => Promise): Deferred { - return (async (...args: Parameters) => - await ( - await load() - )(...args)) as unknown as Deferred; -} +import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; const metadata = Object.freeze({ family: 'harmonyos', } satisfies PlatformModuleMetadata); -export const runtimeModule = Object.freeze({ +const runtimeModule = Object.freeze({ ...metadata, loadRuntime: async (host) => { const { createHarmonyPlatformRuntime } = await import('./runtime.ts'); @@ -30,94 +20,22 @@ export const runtimeModule = Object.freeze({ }, } satisfies PlatformRuntimeModule); -export type { HarmonyInventoryConfig } from './inventory-config.ts'; - -export const openHarmonyApp = deferred<(typeof import('./app-lifecycle.ts'))['openHarmonyApp']>( - async () => (await import('./app-lifecycle.ts')).openHarmonyApp, -); -export const closeHarmonyApp = deferred<(typeof import('./app-lifecycle.ts'))['closeHarmonyApp']>( - async () => (await import('./app-lifecycle.ts')).closeHarmonyApp, -); - -export const runHarmonyHdc = deferred<(typeof import('./hdc.ts'))['runHarmonyHdc']>( - async () => (await import('./hdc.ts')).runHarmonyHdc, -); -export const runHarmonyShell = deferred<(typeof import('./hdc.ts'))['runHarmonyShell']>( - async () => (await import('./hdc.ts')).runHarmonyShell, -); -export const ensureHarmonyToolchainPathConfigured = deferred< - (typeof import('./hdc.ts'))['ensureHarmonyToolchainPathConfigured'] ->(async () => (await import('./hdc.ts')).ensureHarmonyToolchainPathConfigured); - -export const pressHarmony = deferred<(typeof import('./input-actions.ts'))['pressHarmony']>( - async () => (await import('./input-actions.ts')).pressHarmony, -); -export const doubleClickHarmony = deferred< - (typeof import('./input-actions.ts'))['doubleClickHarmony'] ->(async () => (await import('./input-actions.ts')).doubleClickHarmony); -export const longPressHarmony = deferred<(typeof import('./input-actions.ts'))['longPressHarmony']>( - async () => (await import('./input-actions.ts')).longPressHarmony, -); -export const typeHarmony = deferred<(typeof import('./input-actions.ts'))['typeHarmony']>( - async () => (await import('./input-actions.ts')).typeHarmony, -); -export const fillHarmony = deferred<(typeof import('./input-actions.ts'))['fillHarmony']>( - async () => (await import('./input-actions.ts')).fillHarmony, -); -export const scrollHarmony = deferred<(typeof import('./input-actions.ts'))['scrollHarmony']>( - async () => (await import('./input-actions.ts')).scrollHarmony, -); -export const performHarmonyGesture = deferred< - (typeof import('./input-actions.ts'))['performHarmonyGesture'] ->(async () => (await import('./input-actions.ts')).performHarmonyGesture); -export const backHarmony = deferred<(typeof import('./input-actions.ts'))['backHarmony']>( - async () => (await import('./input-actions.ts')).backHarmony, -); -export const homeHarmony = deferred<(typeof import('./input-actions.ts'))['homeHarmony']>( - async () => (await import('./input-actions.ts')).homeHarmony, -); -export const appSwitcherHarmony = deferred< - (typeof import('./input-actions.ts'))['appSwitcherHarmony'] ->(async () => (await import('./input-actions.ts')).appSwitcherHarmony); -export const pressHarmonyKeyboardKey = deferred< - (typeof import('./input-actions.ts'))['pressHarmonyKeyboardKey'] ->(async () => (await import('./input-actions.ts')).pressHarmonyKeyboardKey); -export const setHarmonyOrientation = deferred< - (typeof import('./input-actions.ts'))['setHarmonyOrientation'] ->(async () => (await import('./input-actions.ts')).setHarmonyOrientation); - -export const screenshotHarmony = deferred<(typeof import('./screenshot.ts'))['screenshotHarmony']>( - async () => (await import('./screenshot.ts')).screenshotHarmony, -); -export const setHarmonySetting = deferred<(typeof import('./settings.ts'))['setHarmonySetting']>( - async () => (await import('./settings.ts')).setHarmonySetting, -); -export const snapshotHarmony = deferred<(typeof import('./snapshot.ts'))['snapshotHarmony']>( - async () => (await import('./snapshot.ts')).snapshotHarmony, -); -export const readHarmonyGestureViewport = deferred< - (typeof import('./snapshot.ts'))['readHarmonyGestureViewport'] ->(async () => (await import('./snapshot.ts')).readHarmonyGestureViewport); -export const sampleHarmonyMemoryPerf = deferred< - (typeof import('./perf.ts'))['sampleHarmonyMemoryPerf'] ->(async () => (await import('./perf.ts')).sampleHarmonyMemoryPerf); -export const harmonyToolchainCheck = deferred< - (typeof import('./doctor.ts'))['harmonyToolchainCheck'] ->(async () => (await import('./doctor.ts')).harmonyToolchainCheck); - -export function createHarmonyInventoryModule( - config: HarmonyInventoryConfig, -): InventoryPlatformModule<'harmonyos'> { - const capturedConfig = Object.freeze({ - hdcSdkPath: normalizedRoot(config.hdcSdkPath), - devecoSdkHome: normalizedRoot(config.devecoSdkHome), - commandLineToolsHome: normalizedRoot(config.commandLineToolsHome), +/** + * Builds the inventory module from the host the plugin was set up with. The documented HarmonyOS + * toolchain roots are read there, so a daemon started with them picks them up without the core + * naming HarmonyOS configuration, and the plugin never reads `process.env` itself (ADR 0019). + */ +function createHarmonyInventoryModule(host: HostEnvironment): InventoryPlatformModule<'harmonyos'> { + const config = Object.freeze({ + hdcSdkPath: normalizedRoot(host.env.HDC_SDK_PATH), + devecoSdkHome: normalizedRoot(host.env.DEVECO_SDK_HOME), + commandLineToolsHome: normalizedRoot(host.env.HARMONYOS_COMMAND_LINE_TOOLS), }); return Object.freeze({ ...metadata, - loadInventory: async (host) => { + loadInventory: async (inventoryHost) => { const { createHarmonyInventory } = await import('./inventory.ts'); - return createHarmonyInventory(host, capturedConfig); + return createHarmonyInventory(inventoryHost, config); }, }); } @@ -126,3 +44,44 @@ function normalizedRoot(root: string | undefined): string | undefined { const trimmed = root?.trim(); return trimmed ? trimmed : undefined; } + +function harmonyPlatformPlugin() { + return { + apiVersion: 3, + contributes: [ + { + kind: 'platform', + family: 'harmonyos', + setup(host: PlatformHost): PlatformSetup<'harmonyos'> { + return { + family: 'harmonyos', + inventoryModule: createHarmonyInventoryModule(host), + runtimeModule, + createInteractor: async ( + device: DeviceInfo, + runnerContext: RunnerContext, + ): Promise => { + const { createHarmonyInteractor } = await import('./interactor.ts'); + return createHarmonyInteractor(device, runnerContext); + }, + operations: { + toolchainCheck: async () => { + const { harmonyToolchainCheck } = await import('./doctor.ts'); + return await harmonyToolchainCheck(); + }, + prepareToolchain: async (env: EnvMap) => { + const { ensureHarmonyToolchainPathConfigured } = await import('./hdc.ts'); + await ensureHarmonyToolchainPathConfigured(env); + }, + }, + }; + }, + }, + ], + } satisfies { + apiVersion: 3; + contributes: [Extract]; + }; +} + +export { harmonyPlatformPlugin as default }; diff --git a/packages/platform-harmonyos/src/interactor-facade.ts b/packages/platform-harmonyos/src/interactor-facade.ts deleted file mode 100644 index 4aeee9f729..0000000000 --- a/packages/platform-harmonyos/src/interactor-facade.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; - -export async function createHarmonyInteractor( - device: DeviceInfo, - runner?: RunnerContext, -): Promise { - const { createHarmonyInteractor: create } = await import('./interactor.ts'); - return create(device, runner); -} diff --git a/packages/platform-harmonyos/src/interactor.test.ts b/packages/platform-harmonyos/src/interactor.test.ts index 09a21e84ec..3d94a308c6 100644 --- a/packages/platform-harmonyos/src/interactor.test.ts +++ b/packages/platform-harmonyos/src/interactor.test.ts @@ -9,25 +9,15 @@ const { pressHarmonyKeyboardKey, snapshotHarmony } = vi.hoisted(() => ({ })), })); -vi.mock('./index.ts', () => ({ - appSwitcherHarmony: vi.fn(), - backHarmony: vi.fn(), - closeHarmonyApp: vi.fn(), - doubleClickHarmony: vi.fn(), - fillHarmony: vi.fn(), - homeHarmony: vi.fn(), - longPressHarmony: vi.fn(), - openHarmonyApp: vi.fn(), - performHarmonyGesture: vi.fn(), - pressHarmony: vi.fn(), +// The interactor imports the owning modules directly, so the test stubs them where they live. +vi.mock('./input-actions.ts', async (importOriginal) => ({ + ...(await importOriginal()), pressHarmonyKeyboardKey, - readHarmonyGestureViewport: vi.fn(), - screenshotHarmony: vi.fn(), - scrollHarmony: vi.fn(), - setHarmonyOrientation: vi.fn(), - setHarmonySetting: vi.fn(), +})); + +vi.mock('./snapshot.ts', async (importOriginal) => ({ + ...(await importOriginal()), snapshotHarmony, - typeHarmony: vi.fn(), })); import { createHarmonyInteractor } from './interactor.ts'; diff --git a/packages/platform-harmonyos/src/interactor.ts b/packages/platform-harmonyos/src/interactor.ts index bc545a3a1f..b6626e93d2 100644 --- a/packages/platform-harmonyos/src/interactor.ts +++ b/packages/platform-harmonyos/src/interactor.ts @@ -3,26 +3,24 @@ import { AppError } from '@agent-device/kernel/errors'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; import { withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; +import { closeHarmonyApp, openHarmonyApp } from './app-lifecycle.ts'; import { appSwitcherHarmony, backHarmony, - closeHarmonyApp, doubleClickHarmony, fillHarmony, homeHarmony, longPressHarmony, - openHarmonyApp, performHarmonyGesture, pressHarmony, pressHarmonyKeyboardKey, - readHarmonyGestureViewport, - screenshotHarmony, scrollHarmony, setHarmonyOrientation, - setHarmonySetting, - snapshotHarmony, typeHarmony, -} from './index.ts'; +} from './input-actions.ts'; +import { screenshotHarmony } from './screenshot.ts'; +import { setHarmonySetting } from './settings.ts'; +import { readHarmonyGestureViewport, snapshotHarmony } from './snapshot.ts'; export function createHarmonyInteractor(device: DeviceInfo, _runner?: RunnerContext): Interactor { const unsupported = (name: string) => async (): Promise => { diff --git a/packages/platform-harmonyos/src/inventory-config.ts b/packages/platform-harmonyos/src/inventory-config.ts deleted file mode 100644 index facc5060fe..0000000000 --- a/packages/platform-harmonyos/src/inventory-config.ts +++ /dev/null @@ -1,8 +0,0 @@ -export type HarmonyInventoryConfig = Readonly<{ - /** Raw HDC_SDK_PATH captured inertly by the composition root. */ - hdcSdkPath?: string; - /** Raw DEVECO_SDK_HOME captured inertly by the composition root. */ - devecoSdkHome?: string; - /** Raw HARMONYOS_COMMAND_LINE_TOOLS captured inertly by the composition root. */ - commandLineToolsHome?: string; -}>; diff --git a/packages/platform-harmonyos/src/inventory.ts b/packages/platform-harmonyos/src/inventory.ts index 9dbac26ab9..ea6130b934 100644 --- a/packages/platform-harmonyos/src/inventory.ts +++ b/packages/platform-harmonyos/src/inventory.ts @@ -9,7 +9,13 @@ import type { } from '@agent-device/contracts/platform-runtime-host'; import type { DeviceInventorySource } from '@agent-device/contracts/platform-module'; import type { DeviceInventoryRequest } from '@agent-device/contracts/device'; -import type { HarmonyInventoryConfig } from './inventory-config.ts'; + +/** The raw HarmonyOS toolchain roots the plugin was configured with, captured inertly by its host. */ +export type HarmonyInventoryConfig = Readonly<{ + hdcSdkPath?: string; + devecoSdkHome?: string; + commandLineToolsHome?: string; +}>; const PROBE_TIMEOUT_MS = 10_000; diff --git a/packages/platform-harmonyos/src/perf/runtime.test.ts b/packages/platform-harmonyos/src/perf/runtime.test.ts index 1ce790827c..dedc2e864f 100644 --- a/packages/platform-harmonyos/src/perf/runtime.test.ts +++ b/packages/platform-harmonyos/src/perf/runtime.test.ts @@ -1,5 +1,4 @@ import { expect, test, vi } from 'vitest'; -import type { HarmonyPerfHost } from '@agent-device/contracts/perf-runtime-host'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { createHarmonyPerfOperations } from './runtime.ts'; @@ -14,10 +13,7 @@ const device: DeviceInfo = { test('keeps HarmonyOS perf limited to its existing memory sample', async () => { const sampleMemory = vi.fn(async () => ({ residentKb: 256 })); - const operations = createHarmonyPerfOperations({ - resolveHost: () => ({ sampleMemory }) satisfies HarmonyPerfHost, - device, - }); + const operations = createHarmonyPerfOperations({ device, sampleMemory }); await expect(operations.perfMemorySample({ appId: 'com.example.app' })).resolves.toMatchObject({ metric: { available: true, residentKb: 256 }, diff --git a/packages/platform-harmonyos/src/perf/runtime.ts b/packages/platform-harmonyos/src/perf/runtime.ts index 834f7cd16d..139d123b8b 100644 --- a/packages/platform-harmonyos/src/perf/runtime.ts +++ b/packages/platform-harmonyos/src/perf/runtime.ts @@ -1,18 +1,24 @@ -import type { HarmonyPerfHost } from '@agent-device/contracts/perf-runtime-host'; import { missingPerfAppMetric, settlePerfMetric, } from '@agent-device/contracts/perf-runtime-operation-builder'; import type { PerfRuntimeOperations } from '@agent-device/contracts/perf-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { sampleHarmonyMemoryPerf } from '../perf.ts'; +/** + * The HarmonyOS performance cells. Memory sampling reads `/proc//status` over HDC, which the + * family owns; no shared host facet carries it. + */ export function createHarmonyPerfOperations( params: Readonly<{ - resolveHost(): HarmonyPerfHost; device: DeviceInfo; + /** The HDC memory read; the binding supplies the package's own sampler so a test can stub it. */ + sampleMemory?: (device: DeviceInfo, appId: string) => Promise; }>, ): Pick { - const { resolveHost, device } = params; + const { device } = params; + const sampleMemory = params.sampleMemory ?? sampleHarmonyMemoryPerf; const frameUnavailable = { available: false, reason: @@ -22,7 +28,7 @@ export function createHarmonyPerfOperations( perfFrames: async () => ({ metric: frameUnavailable, sampling: frameUnavailable }), perfMemorySample: async ({ appId }) => ({ metric: appId - ? await settlePerfMetric(resolveHost().sampleMemory(device, appId)) + ? await settlePerfMetric(sampleMemory(device, appId)) : missingPerfAppMetric('HarmonyOS', 'bundle'), sampling: { method: 'hdc-shell-proc-status', diff --git a/src/platform-runtime-screen-recording-harmony-host.ts b/packages/platform-harmonyos/src/recording/recorder.ts similarity index 52% rename from src/platform-runtime-screen-recording-harmony-host.ts rename to packages/platform-harmonyos/src/recording/recorder.ts index c334883630..455ebc1e82 100644 --- a/src/platform-runtime-screen-recording-harmony-host.ts +++ b/packages/platform-harmonyos/src/recording/recorder.ts @@ -1,8 +1,44 @@ -import type { ScreenRecordingRuntimeHost } from '@agent-device/contracts/screen-recording-runtime-host'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { HostCommandResult } from '@agent-device/contracts/platform-runtime-host'; import type { ShellWord } from '@agent-device/kernel/device-shell'; +import { runHarmonyHdc, runHarmonyShell } from '../hdc.ts'; -export function createHarmonyScreenRecordingHost(): ScreenRecordingRuntimeHost['harmony'] { +/** + * The device-side HarmonyOS screen recorder, driven entirely through HDC. It is the family's own + * transport: the shared screen-recording host keeps output preparation and video finalization, and + * nothing else needs to know the recorder's ability ids or media-tool commands. + */ +export type HarmonyScreenRecorder = Readonly<{ + start(device: DeviceInfo, fileName: string, signal?: AbortSignal): Promise; + stop(device: DeviceInfo, signal?: AbortSignal): Promise; + findMedia( + device: DeviceInfo, + fileName: string, + signal?: AbortSignal, + ): Promise; + stageMedia( + device: DeviceInfo, + input: Readonly<{ mediaUri: string; remotePath: string }>, + signal?: AbortSignal, + ): Promise; + stagedFileSize( + device: DeviceInfo, + remotePath: string, + signal?: AbortSignal, + ): Promise; + pull( + device: DeviceInfo, + input: Readonly<{ remotePath: string; outputPath: string }>, + signal?: AbortSignal, + ): Promise; + remove(device: DeviceInfo, remotePath: string, signal?: AbortSignal): Promise; + removeMedia(device: DeviceInfo, mediaUri: string, signal?: AbortSignal): Promise; +}>; + +const SCREEN_RECORDER_ABILITY = 'com.huawei.hmos.screenrecorder'; +const SCREEN_RECORDER_SERVICE_ABILITY = 'com.huawei.hmos.screenrecorder.ServiceExtAbility'; + +export function createHarmonyScreenRecorder(): HarmonyScreenRecorder { return Object.freeze({ start: async (device, fileName, signal) => await hdcShell( @@ -11,9 +47,9 @@ export function createHarmonyScreenRecordingHost(): ScreenRecordingRuntimeHost[' 'aa', 'start', '-b', - 'com.huawei.hmos.screenrecorder', + SCREEN_RECORDER_ABILITY, '-a', - 'com.huawei.hmos.screenrecorder.ServiceExtAbility', + SCREEN_RECORDER_SERVICE_ABILITY, '--ps', 'CustomizedFileName', fileName, @@ -23,14 +59,7 @@ export function createHarmonyScreenRecordingHost(): ScreenRecordingRuntimeHost[' stop: async (device, signal) => await hdcShell( device, - [ - 'aa', - 'start', - '-b', - 'com.huawei.hmos.screenrecorder', - '-a', - 'com.huawei.hmos.screenrecorder.ServiceExtAbility', - ], + ['aa', 'start', '-b', SCREEN_RECORDER_ABILITY, '-a', SCREEN_RECORDER_SERVICE_ABILITY], signal, ), findMedia: async (device, fileName, signal) => @@ -56,11 +85,9 @@ export function createHarmonyScreenRecordingHost(): ScreenRecordingRuntimeHost[' } async function hdc(device: DeviceInfo, args: string[], signal?: AbortSignal) { - const { runHarmonyHdc } = await import('@agent-device/platform-harmonyos'); return await runHarmonyHdc(device, args, { allowFailure: true, signal }); } async function hdcShell(device: DeviceInfo, words: readonly ShellWord[], signal?: AbortSignal) { - const { runHarmonyShell } = await import('@agent-device/platform-harmonyos'); return await runHarmonyShell(device, words, { allowFailure: true, signal }); } diff --git a/packages/platform-harmonyos/src/recording/runtime.fixtures.ts b/packages/platform-harmonyos/src/recording/runtime.fixtures.ts index 7f3e9aaef3..b8ea9b3aca 100644 --- a/packages/platform-harmonyos/src/recording/runtime.fixtures.ts +++ b/packages/platform-harmonyos/src/recording/runtime.fixtures.ts @@ -1,7 +1,7 @@ import { recordingFileStore } from '@agent-device/capture-kit/recording-artifact-fixtures'; import type { ScreenRecordingRuntimeHost } from '@agent-device/contracts/screen-recording-runtime-host'; import type { ScreenRecordingStartInput } from '@agent-device/contracts/screen-recording-runtime'; -import type { createHarmonyScreenRecordingOperations } from './runtime.ts'; +import type { HarmonyScreenRecorder } from './recorder.ts'; export const harmonyDevice = Object.freeze({ platform: 'harmonyos' as const, @@ -31,27 +31,22 @@ export function harmonyCommandSuccess() { return { stdout: 'start ability successfully', stderr: '', exitCode: 0 }; } -type HarmonyHost = Parameters[0]['host']; - +/** + * The host and recorder pair the recording operations consume. Every recorder port is a stub the + * test overrides, so no HDC process is spawned from these tests. + */ export function harmonyRecordingHost( - overrides: Partial & { + overrides: Partial & { complete?: ScreenRecordingRuntimeHost['finalize']['complete']; prepare?: ScreenRecordingRuntimeHost['outputs']['prepare']; } = {}, -): HarmonyHost { - const harmony: ScreenRecordingRuntimeHost['harmony'] = { - start: overrides.start ?? (async () => harmonyCommandSuccess()), - stop: overrides.stop ?? (async () => harmonyCommandSuccess()), - findMedia: overrides.findMedia ?? (async () => 'file://media/video'), - stageMedia: overrides.stageMedia ?? (async () => true), - stagedFileSize: overrides.stagedFileSize ?? (async () => 12), - pull: overrides.pull ?? (async () => ({ stdout: '', stderr: '', exitCode: 0 })), - remove: overrides.remove ?? (async () => true), - removeMedia: overrides.removeMedia ?? (async () => true), - }; +): Readonly<{ + screenRecording: Pick; + clock: Readonly<{ now: () => number; sleep: (ms?: number) => Promise }>; + recorder: HarmonyScreenRecorder; +}> { return { screenRecording: { - harmony, outputs: { ...recordingFileStore().outputs, prepare: overrides.prepare ?? (async () => {}), @@ -59,5 +54,21 @@ export function harmonyRecordingHost( finalize: { sniff: async () => {}, complete: overrides.complete ?? (async () => ({})) }, }, clock: { now: () => 0, sleep: async () => {} }, + recorder: harmonyRecordingRecorder(overrides), + }; +} + +function harmonyRecordingRecorder( + overrides: Partial = {}, +): HarmonyScreenRecorder { + return { + start: overrides.start ?? (async () => harmonyCommandSuccess()), + stop: overrides.stop ?? (async () => harmonyCommandSuccess()), + findMedia: overrides.findMedia ?? (async () => 'file://media/video'), + stageMedia: overrides.stageMedia ?? (async () => true), + stagedFileSize: overrides.stagedFileSize ?? (async () => 12), + pull: overrides.pull ?? (async () => ({ stdout: '', stderr: '', exitCode: 0 })), + remove: overrides.remove ?? (async () => true), + removeMedia: overrides.removeMedia ?? (async () => true), }; } diff --git a/packages/platform-harmonyos/src/recording/runtime.ts b/packages/platform-harmonyos/src/recording/runtime.ts index 6e5ebcfc2d..002251b5bf 100644 --- a/packages/platform-harmonyos/src/recording/runtime.ts +++ b/packages/platform-harmonyos/src/recording/runtime.ts @@ -4,7 +4,6 @@ import { AppError } from '@agent-device/kernel/errors'; import type { CleanupOutcome } from '@agent-device/contracts/durable-resource'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import type { RuntimeOwnerRef } from '@agent-device/contracts/platform-runtime'; -import type { ScreenRecordingRuntimeHost } from '@agent-device/contracts/screen-recording-runtime-host'; import type { ScreenRecordingLiveSnapshot, ScreenRecordingRuntimeOperations, @@ -21,12 +20,30 @@ import { createHarmonyRecordingEnvelope, type HarmonyRecordingDescriptor, } from './recovery.ts'; +import { createHarmonyScreenRecorder, type HarmonyScreenRecorder } from './recorder.ts'; -type HarmonyScreenRecordingOperationHost = Readonly<{ - screenRecording: Pick; +/** + * The host the HarmonyOS recording operations consume: output preparation and video finalization + * from the shared runtime host, plus the HDC recorder this family drives. The recorder is part of + * the seam rather than a shared host facet, because no other family uses it. + */ +export type HarmonyScreenRecordingOperationHost = Readonly<{ + screenRecording: Pick; clock: PlatformRuntimeHost['clock']; + recorder: HarmonyScreenRecorder; }>; +/** Binds the shared runtime host's recording authorities to the HDC recorder this family drives. */ +export function createHarmonyRecordingHost( + host: PlatformRuntimeHost, +): HarmonyScreenRecordingOperationHost { + return Object.freeze({ + screenRecording: host.screenRecording, + clock: host.clock, + recorder: createHarmonyScreenRecorder(), + }); +} + export function harmonyScreenRecordingFacts(device: DeviceInfo) { return device.kind === 'device' ? Object.freeze({ available: true } as const) @@ -44,9 +61,10 @@ export function createHarmonyScreenRecordingOperations(params: { signal: AbortSignal; }): ScreenRecordingRuntimeOperations { const { host, device, owner, signal } = params; + const { recorder } = host; return Object.freeze({ screenRecordingStart: async (input) => - await startHarmonyRecording({ host, device, owner, input, signal }), + await startHarmonyRecording({ host, recorder, device, owner, input, signal }), screenRecordingReattach: async () => ({ status: 'unreattachable' as const, reason: 'transport-not-reattachable' as const, @@ -59,12 +77,13 @@ export function createHarmonyScreenRecordingOperations(params: { async function startHarmonyRecording(params: { host: HarmonyScreenRecordingOperationHost; + recorder: HarmonyScreenRecorder; device: DeviceInfo; owner: RuntimeOwnerRef; input: ScreenRecordingStartInput; signal: AbortSignal; }) { - const { host, device, owner, input, signal } = params; + const { host, recorder, device, owner, input, signal } = params; if (input.scope === 'app') { throw new AppError( 'INVALID_ARGS', @@ -87,11 +106,11 @@ async function startHarmonyRecording(params: { }; let start; try { - start = await host.screenRecording.harmony.start(device, fileName, signal); + start = await recorder.start(device, fileName, signal); signal.throwIfAborted(); } catch (error) { if (signal.aborted) { - await cleanupLiveHarmonyDescriptor(host, device, descriptor).catch(() => {}); + await cleanupLiveHarmonyDescriptor(recorder, device, descriptor).catch(() => {}); throw signal.reason; } throw error; @@ -100,22 +119,22 @@ async function startHarmonyRecording(params: { try { signal.throwIfAborted(); } catch (error) { - await cleanupLiveHarmonyDescriptor(host, device, descriptor).catch(() => {}); + await cleanupLiveHarmonyDescriptor(recorder, device, descriptor).catch(() => {}); throw error; } const initial = snapshot(input); let recorderStopped = false; const stopRecorder = async () => { if (recorderStopped) return; - const stop = await host.screenRecording.harmony.stop(device); + const stop = await recorder.stop(device); assertHarmonyRecorderCommandSucceeded(stop, 'stop'); recorderStopped = true; }; const handle = createScreenRecordingLiveHandle(initial, { finish: async (current) => - await finishHarmonyRecording(host, device, current, descriptor, stopRecorder), + await finishHarmonyRecording(host, recorder, device, current, descriptor, stopRecorder), forceCleanup: async () => - await cleanupLiveHarmonyDescriptor(host, device, descriptor, stopRecorder), + await cleanupLiveHarmonyDescriptor(recorder, device, descriptor, stopRecorder), }); return Object.freeze({ pendingHandle: new PendingTransferGuard(handle), @@ -139,23 +158,24 @@ function snapshot(input: ScreenRecordingStartInput): ScreenRecordingLiveSnapshot async function finishHarmonyRecording( host: HarmonyScreenRecordingOperationHost, + recorder: HarmonyScreenRecorder, device: DeviceInfo, snapshot: ScreenRecordingLiveSnapshot, descriptor: HarmonyRecordingDescriptor, stopRecorder: () => Promise, ) { await stopRecorder(); - const mediaUri = await host.screenRecording.harmony.findMedia(device, descriptor.fileName); + const mediaUri = await recorder.findMedia(device, descriptor.fileName); if (!mediaUri) throw new Error(`failed to find finalized HarmonyOS recording '${descriptor.fileName}'`); - const staged = await stageHarmonyMedia(host, device, descriptor, mediaUri); + const staged = await stageHarmonyMedia(host, recorder, device, descriptor, mediaUri); if (!staged) { throw new Error( `failed to finalize HarmonyOS recording: ${descriptor.fileName} did not produce a non-empty media file`, ); } try { - const pulled = await host.screenRecording.harmony.pull(device, { + const pulled = await recorder.pull(device, { remotePath: descriptor.remotePath, outputPath: snapshot.outPath, }); @@ -167,7 +187,7 @@ async function finishHarmonyRecording( targetLabel: 'HarmonyOS recording', }); const cleanupWarning = await cleanupCompletedHarmonyArtifacts( - host, + recorder, device, descriptor, mediaUri, @@ -187,25 +207,21 @@ async function finishHarmonyRecording( }, ); } catch (error) { - await host.screenRecording.harmony.remove(device, descriptor.remotePath).catch(() => {}); + await recorder.remove(device, descriptor.remotePath).catch(() => {}); throw error; } } async function cleanupCompletedHarmonyArtifacts( - host: HarmonyScreenRecordingOperationHost, + recorder: HarmonyScreenRecorder, device: DeviceInfo, descriptor: HarmonyRecordingDescriptor, mediaUri: string, ): Promise { const unconfirmed: string[] = []; - if ( - !(await confirmedRemoval(() => - host.screenRecording.harmony.remove(device, descriptor.remotePath), - )) - ) + if (!(await confirmedRemoval(() => recorder.remove(device, descriptor.remotePath)))) unconfirmed.push('staging artifact'); - if (!(await confirmedRemoval(() => host.screenRecording.harmony.removeMedia(device, mediaUri)))) + if (!(await confirmedRemoval(() => recorder.removeMedia(device, mediaUri)))) unconfirmed.push('media-library artifact'); return unconfirmed.length === 0 ? undefined @@ -232,19 +248,20 @@ function appendCompletionWarning( async function stageHarmonyMedia( host: HarmonyScreenRecordingOperationHost, + recorder: HarmonyScreenRecorder, device: DeviceInfo, descriptor: HarmonyRecordingDescriptor, mediaUri: string, ): Promise { let previousNonzeroSize: number | undefined; for (let attempt = 0; attempt < 40; attempt += 1) { - await host.screenRecording.harmony.remove(device, descriptor.remotePath).catch(() => {}); - const staged = await host.screenRecording.harmony.stageMedia(device, { + await recorder.remove(device, descriptor.remotePath).catch(() => {}); + const staged = await recorder.stageMedia(device, { mediaUri, remotePath: descriptor.remotePath, }); if (staged) { - const size = await host.screenRecording.harmony.stagedFileSize(device, descriptor.remotePath); + const size = await recorder.stagedFileSize(device, descriptor.remotePath); if (size !== undefined && size > 0 && size === previousNonzeroSize) return true; previousNonzeroSize = size !== undefined && size > 0 ? size : undefined; } else { @@ -256,22 +273,26 @@ async function stageHarmonyMedia( } async function cleanupLiveHarmonyDescriptor( - host: HarmonyScreenRecordingOperationHost, + recorder: HarmonyScreenRecorder, device: DeviceInfo, descriptor: HarmonyRecordingDescriptor, - stopRecorder: () => Promise = async () => { - const stop = await host.screenRecording.harmony.stop(device); - assertHarmonyRecorderCommandSucceeded(stop, 'stop'); - }, + stopRecorder?: () => Promise, ): Promise { const failures = [ - await cleanupFailure(stopRecorder), + await cleanupFailure( + stopRecorder ?? + (async () => { + assertHarmonyRecorderCommandSucceeded(await recorder.stop(device), 'stop'); + }), + ), await cleanupFailure(async () => { - if (!(await host.screenRecording.harmony.remove(device, descriptor.remotePath))) { + if (!(await recorder.remove(device, descriptor.remotePath))) { throw new Error('HarmonyOS recording staging artifact removal was not confirmed'); } }), - await cleanupFailure(async () => await removeHarmonyMedia(host, device, descriptor.fileName)), + await cleanupFailure( + async () => await removeHarmonyMedia(recorder, device, descriptor.fileName), + ), ]; const failure = failures.find((candidate) => candidate !== undefined); if (failure !== undefined) { @@ -285,12 +306,12 @@ async function cleanupLiveHarmonyDescriptor( } async function removeHarmonyMedia( - host: HarmonyScreenRecordingOperationHost, + recorder: HarmonyScreenRecorder, device: DeviceInfo, fileName: string, ): Promise { - const mediaUri = await host.screenRecording.harmony.findMedia(device, fileName); - if (mediaUri && !(await host.screenRecording.harmony.removeMedia(device, mediaUri))) { + const mediaUri = await recorder.findMedia(device, fileName); + if (mediaUri && !(await recorder.removeMedia(device, mediaUri))) { throw new Error('HarmonyOS recording media removal was not confirmed'); } } diff --git a/packages/platform-harmonyos/src/runtime.ts b/packages/platform-harmonyos/src/runtime.ts index 4b87a01737..92dfc3d9b2 100644 --- a/packages/platform-harmonyos/src/runtime.ts +++ b/packages/platform-harmonyos/src/runtime.ts @@ -46,6 +46,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import { createHarmonyAppLogRuntime } from './logs/runtime.ts'; import { createHarmonyPerfOperations } from './perf/runtime.ts'; import { + createHarmonyRecordingHost, createHarmonyScreenRecordingOperations, harmonyScreenRecordingFacts, } from './recording/runtime.ts'; @@ -327,7 +328,7 @@ export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): Platfor ensureReady: async () => ({ ...request.device, booted: true }), ...(recordingFacts.available ? createHarmonyScreenRecordingOperations({ - host, + host: createHarmonyRecordingHost(host), device: request.device, owner, signal: request.scope.signal, @@ -351,7 +352,6 @@ export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): Platfor }), ...whenAdmitted(facts.operations.perfFrames, () => createHarmonyPerfOperations({ - resolveHost: () => host.perf.harmony, device: request.device, }), ), diff --git a/packages/platform-harmonyos/test/package-smoke.mjs b/packages/platform-harmonyos/test/package-smoke.mjs new file mode 100644 index 0000000000..ea887125a2 --- /dev/null +++ b/packages/platform-harmonyos/test/package-smoke.mjs @@ -0,0 +1,122 @@ +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'; + +const repo = path.resolve(import.meta.dirname, '../../..'); + +test('packed core discovers harmonyos only after the managed platform is installed', () => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-harmonyos-pack-')); + // HDC is a host tool the plugin reads through PATH and through the three documented SDK roots. + // A machine that has it installed would answer with its own device list, so every CLI run names a + // host that carries neither: the installed plugin then always answers its own missing-toolchain + // report, on any machine. + const strippedHost = (source) => + Object.fromEntries( + Object.entries(source).filter( + ([name]) => + !name.startsWith('AGENT_DEVICE_') && + !['HDC_SDK_PATH', 'DEVECO_SDK_HOME', 'HARMONYOS_COMMAND_LINE_TOOLS'].includes(name), + ), + ); + 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 cliEnv = { + ...env, + PATH: [path.dirname(process.execPath), '/usr/bin', '/bin'].join(path.delimiter), + HOME: scratch, + }; + const exec = (command, args, cwd = scratch) => + execFileSync(command, args, { cwd, env, encoding: 'utf8', timeout: 120_000 }); + // Help is the CLI's local fast path: it renders text and never takes `--json`. + const cliText = (...args) => + exec(process.execPath, ['node_modules/agent-device/bin/agent-device.mjs', ...args], scratch); + const runCli = (expectedExit, ...args) => { + const invoke = () => + execFileSync( + process.execPath, + ['node_modules/agent-device/bin/agent-device.mjs', ...args, '--json'], + { cwd: scratch, env: cliEnv, encoding: 'utf8', timeout: 120_000 }, + ); + 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; + } + }; + try { + const [packed] = JSON.parse( + exec('npm', ['pack', '--ignore-scripts', '--json', '--pack-destination', scratch], repo), + ); + assert.ok(!packed.files.some(({ path }) => path.includes('/platform-harmonyos/'))); + exec( + 'pnpm', + ['pack', '--out', path.join(scratch, 'harmonyos.tgz')], + path.join(repo, 'packages/platform-harmonyos'), + ); + fs.writeFileSync(path.join(scratch, 'package.json'), '{"private":true}'); + exec('npm', [ + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + path.join(scratch, packed.filename), + ]); + + // Without the plugin: a request that names the family answers the typed outcome with the + // install command, an unfiltered request skips the family silently, and help still renders. + const { error } = runCli(1, 'devices', '--platform', 'harmonyos'); + assert.equal(error.details.reason, 'plugin-not-installed'); + assert.match(error.hint, /agent-device plugins add @agent-device\/harmonyos/); + + const open = runCli(1, 'open', 'com.example.app', '--platform', 'harmonyos'); + assert.equal(open.error.details.reason, 'plugin-not-installed'); + + // Doctor names the family's own blocker through a failing toolchain row, built from the same + // absence outcome the discovery request raises. An unfiltered doctor stays silent about it. + const scoped = runCli(0, 'doctor', '--platform', 'harmonyos'); + const toolchain = scoped.data.checks.find((check) => check.id === 'toolchain'); + assert.equal(toolchain.status, 'fail'); + assert.equal(toolchain.evidence.reason, 'plugin-not-installed'); + assert.equal(toolchain.evidence.package, '@agent-device/harmonyos'); + assert.match(toolchain.command, /agent-device plugins add @agent-device\/harmonyos/); + const unscoped = runCli(0, 'doctor'); + assert.ok( + !unscoped.data.checks.some((check) => + JSON.stringify(check).includes('@agent-device/harmonyos'), + ), + 'an unfiltered doctor names no plugin the core lacks', + ); + runCli(0, 'devices'); + // The family's help renders with no plugin installed: nothing about HarmonyOS depends on it. + assert.match(cliText('help', 'devices'), /devices/); + runCli(0, 'daemon', 'stop'); + + runCli(0, 'plugins', 'add', './harmonyos.tgz'); + // HDC is not installed on this host, so the plugin is active and reports its own toolchain + // rather than an absent plugin. + const installed = runCli(1, 'devices', '--platform', 'harmonyos'); + assert.equal(installed.error.code, 'TOOL_MISSING'); + const plugins = runCli(0, 'daemon', 'status').data.plugins; + assert.ok( + plugins.some((plugin) => plugin.platform === 'harmonyos' && plugin.state === 'active'), + ); + } 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/platform-harmonyos/tsconfig.json b/packages/platform-harmonyos/tsconfig.json index 45051401b5..5acae24d04 100644 --- a/packages/platform-harmonyos/tsconfig.json +++ b/packages/platform-harmonyos/tsconfig.json @@ -6,11 +6,13 @@ "emitDeclarationOnly": true, "declaration": true, "declarationDir": "./dist-types", - "rootDir": "./src", + "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" }, diff --git a/packages/platform-vega/build.mjs b/packages/platform-vega/build.mjs index ec7f1a2d5a..bd06b2acf1 100644 --- a/packages/platform-vega/build.mjs +++ b/packages/platform-vega/build.mjs @@ -1,30 +1,14 @@ -import { readFileSync } from 'node:fs'; import { build } from 'tsdown'; -import { providerPluginBuildConfig } from '@agent-device/build-config'; +import { + assertManagedPlatformPluginFactory, + managedPlatformPluginBuildConfig, +} from '@agent-device/build-config'; import vegaPlatformPlugin from './src/index.ts'; -const { 'agent-device': manifest } = JSON.parse( - readFileSync(new URL('./package.json', import.meta.url), 'utf8'), +assertManagedPlatformPluginFactory( + new URL('./package.json', import.meta.url), + vegaPlatformPlugin, + 'Vega', ); -const { apiVersion, contributes } = vegaPlatformPlugin(); -const [platform] = contributes; -if ( - apiVersion !== manifest.apiVersion || - contributes.length !== 1 || - platform.kind !== 'platform' || - platform.family !== manifest.platform -) { - throw new Error('The managed Vega factory must match its package claim'); -} -await build({ - ...providerPluginBuildConfig, - config: false, - dts: true, - tsconfig: '../../tsconfig.lib.json', - entry: { 'agent-device': 'src/index.ts' }, - deps: { - ...providerPluginBuildConfig.deps, - neverBundle: ['agent-device/plugins'], - }, -}); +await build(managedPlatformPluginBuildConfig); diff --git a/packages/platform-web/build.mjs b/packages/platform-web/build.mjs index e81d5a6bde..84e8e7d2e0 100644 --- a/packages/platform-web/build.mjs +++ b/packages/platform-web/build.mjs @@ -1,30 +1,14 @@ -import { readFileSync } from 'node:fs'; import { build } from 'tsdown'; -import { providerPluginBuildConfig } from '@agent-device/build-config'; +import { + assertManagedPlatformPluginFactory, + managedPlatformPluginBuildConfig, +} from '@agent-device/build-config'; import webPlatformPlugin from './src/index.ts'; -const { 'agent-device': manifest } = JSON.parse( - readFileSync(new URL('./package.json', import.meta.url), 'utf8'), +assertManagedPlatformPluginFactory( + new URL('./package.json', import.meta.url), + webPlatformPlugin, + 'web', ); -const { apiVersion, contributes } = webPlatformPlugin(); -const [platform] = contributes; -if ( - apiVersion !== manifest.apiVersion || - contributes.length !== 1 || - platform.kind !== 'platform' || - platform.family !== manifest.platform -) { - throw new Error('The managed web factory must match its package claim'); -} -await build({ - ...providerPluginBuildConfig, - config: false, - dts: true, - tsconfig: '../../tsconfig.lib.json', - entry: { 'agent-device': 'src/index.ts' }, - deps: { - ...providerPluginBuildConfig.deps, - neverBundle: ['agent-device/plugins'], - }, -}); +await build(managedPlatformPluginBuildConfig); diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index 17445f3bec..f379f79f46 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -1,6 +1,8 @@ import type { InventoryPlatformModule } from '@agent-device/contracts/platform-module'; import type { Platform } from '@agent-device/kernel/device'; import type { + HarmonyPlatformOperations, + HarmonyPlatformRegistration, PlatformPlugin, VegaPlatformOperations, VegaPlatformRegistration, @@ -61,7 +63,9 @@ export type PlatformSetup = Family extends P ): Promise; operations: VegaPlatformOperations; }> - : unknown) + : Family extends 'harmonyos' + ? Readonly<{ operations: HarmonyPlatformOperations }> + : unknown) : never; export type RegisteredPlatformSetup = Family extends Platform @@ -69,12 +73,14 @@ export type RegisteredPlatformSetup = Family ? WebPlatformRegistration : Family extends 'vega' ? VegaPlatformRegistration - : Readonly<{ - family: Family; - createInteractor: PlatformPlugin['createInteractor']; - inventoryModule: InventoryPlatformModule; - runtimeModule: PlatformRuntimeModule & { readonly family: Family }; - }> + : Family extends 'harmonyos' + ? HarmonyPlatformRegistration + : Readonly<{ + family: Family; + createInteractor: PlatformPlugin['createInteractor']; + inventoryModule: InventoryPlatformModule; + runtimeModule: PlatformRuntimeModule & { readonly family: Family }; + }> : never; export type PlatformContribution = { diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index db3460d96f..5c7a8f31d8 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -2,6 +2,7 @@ import type { RegisteredPlatformSetup } from './platform.ts'; import { isPlatform, type Platform } from '@agent-device/kernel/device-identity'; import { NATIVE_REPLAY_BACKEND } from '@agent-device/contracts/replay-execution'; import type { + HarmonyPlatformOperations, VegaPlatformOperations, WebPlatformOperations, } from '@agent-device/contracts/platform-plugin'; @@ -347,6 +348,11 @@ const VEGA_OPERATIONS: Record = { toolchainCheck: true, }; +const HARMONY_OPERATIONS: Record = { + toolchainCheck: true, + prepareToolchain: true, +}; + const PLATFORM_SETUP_CHECKS: Partial) => void>> = { web(value) { const operations = value.operations; @@ -368,6 +374,17 @@ const PLATFORM_SETUP_CHECKS: Partial typeof operations[operation] !== 'function', + ) + ) { + throw invalidPlugin('HarmonyOS platform setup must supply HarmonyOS operations'); + } + }, }; function isClaimId(value: unknown): value is string { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ad10e3b5e6..c416c54eaa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -86,9 +86,6 @@ importers: '@agent-device/platform-apple': specifier: workspace:* version: link:packages/platform-apple - '@agent-device/platform-harmonyos': - specifier: workspace:* - version: link:packages/platform-harmonyos '@agent-device/platform-linux': specifier: workspace:* version: link:packages/platform-linux @@ -812,7 +809,10 @@ importers: version: 5.0.0 packages/platform-harmonyos: - dependencies: + devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config '@agent-device/capture-kit': specifier: workspace:* version: link:../capture-kit @@ -828,10 +828,12 @@ importers: '@agent-device/provision-kit': specifier: workspace:* version: link:../provision-kit - devDependencies: '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit + agent-device: + specifier: workspace:* + version: link:../.. packages/platform-linux: dependencies: diff --git a/scripts/capability-matrix/collect.ts b/scripts/capability-matrix/collect.ts index 50142dab06..ba1e8d9f26 100644 --- a/scripts/capability-matrix/collect.ts +++ b/scripts/capability-matrix/collect.ts @@ -14,7 +14,7 @@ import { runtimeModule as appleRuntimeModule } from '@agent-device/platform-appl import { createAndroidRuntimeModule } from '@agent-device/platform-android'; import { webSelectionFixture } from '../../src/platform-runtime-web-provider.fixtures.ts'; import { vegaSelectionFixture } from '../../src/platform-runtime-vega-provider.fixtures.ts'; -import { runtimeModule as harmonyosRuntimeModule } from '@agent-device/platform-harmonyos'; +import { harmonySelectionFixture } from '../../src/platform-runtime-harmonyos-provider.fixtures.ts'; import { runtimeModule as linuxRuntimeModule } from '@agent-device/platform-linux'; import { createCloudWebDriverRuntime } from '@agent-device/provider-webdriver/plugin'; import { createPluginHost, type RunHostCommand } from '@agent-device/plugins/host'; @@ -33,6 +33,7 @@ import { TARGETS, type Target } from './targets.ts'; const webRuntimeModule = webSelectionFixture().get().runtimeModule; const vegaRuntimeModule = vegaSelectionFixture().get().runtimeModule; +const harmonyosRuntimeModule = harmonySelectionFixture().get().runtimeModule; export type CommandSupport = Readonly<{ /** Public commands the registry derives from runtime facts, in registry order. */ diff --git a/scripts/check-package.ts b/scripts/check-package.ts index 7ea0320949..3a8b18080c 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -59,6 +59,15 @@ const EXCLUDED_IMPLEMENTATIONS = [ paths: [/(?:^|\/)platform-vega\//, /^dist\/src\/vega-.*\.js$/], markers: ['vega-adapter-host-unbound', 'Install Vega Developer Tools'], }, + { + owner: 'harmonyos platform', + paths: [/(?:^|\/)platform-harmonyos\//], + markers: [ + 'Install HarmonyOS Command Line Tools', + 'hdc not found in PATH', + 'harmony-screen-recorder', + ], + }, ] as const; const repoRoot = path.resolve(import.meta.dirname, '..'); diff --git a/scripts/layering/daemon-platform-boundary.test.ts b/scripts/layering/daemon-platform-boundary.test.ts index 921607498f..0f5631af0b 100644 --- a/scripts/layering/daemon-platform-boundary.test.ts +++ b/scripts/layering/daemon-platform-boundary.test.ts @@ -211,7 +211,7 @@ test('R65 follows common createRequire and require aliases', () => { "loadAlias('@agent-device/platform-linux');", "module.require('@agent-device/platform-vega');", "const { createRequire: fromCjs } = require('node:module');", - "fromCjs(import.meta.url)('@agent-device/platform-harmonyos');", + "fromCjs(import.meta.url)('@agent-device/platform-apple');", ].join('\n'); assert.deepEqual( @@ -223,7 +223,7 @@ test('R65 follows common createRequire and require aliases', () => { { spec: '@agent-device/platform-web', line: 9 }, { spec: '@agent-device/platform-linux', line: 11 }, { spec: '@agent-device/platform-vega', line: 12 }, - { spec: '@agent-device/platform-harmonyos', line: 14 }, + { spec: '@agent-device/platform-apple', line: 14 }, ], ); }); diff --git a/scripts/layering/platform-package-policy.test.ts b/scripts/layering/platform-package-policy.test.ts index 79d92b91f7..b42dd1a7df 100644 --- a/scripts/layering/platform-package-policy.test.ts +++ b/scripts/layering/platform-package-policy.test.ts @@ -18,7 +18,7 @@ const inventoryModuleNames = { web: 'webInventoryModule', } as const; -const MANAGED_FAMILIES = ['web', 'vega'] as const; +const MANAGED_FAMILIES = ['web', 'vega', 'harmonyos'] as const; function isManagedFamily(family: string): boolean { return (MANAGED_FAMILIES as readonly string[]).includes(family); @@ -72,7 +72,7 @@ function declarations(): PlatformPackageDeclaration[] { ] : isManagedFamily(family) ? [`${managedPackageName(family)}/agent-device`] - : family === 'harmonyos' || family === 'linux' + : family === 'linux' ? [`@agent-device/platform-${family}`, `@agent-device/platform-${family}/interactor`] : [`@agent-device/platform-${family}`], })); @@ -163,16 +163,21 @@ test('family packages are exact, private, and expose only their root facade', () const packages = declarations(); packages[0] = { ...packages[0]!, private: false }; packages[1] = { ...packages[1]!, name: '@agent-device/not-android' }; - packages[2] = { - ...packages[2]!, - exportedSubpaths: [packages[2]!.name, `${packages[2]!.name}/internal`], + packages[2] = { ...packages[2]!, managedClaim: { platform: 'linux', apiVersion: 3 } }; + packages[4] = { + ...packages[4]!, + exportedSubpaths: [packages[4]!.name, `${packages[4]!.name}/internal`], }; packages.pop(); const found = messages(validSources(), packages).join('\n'); assert.match(found, /platform-apple must be private/); assert.match(found, /platform-android must be named '@agent-device\/platform-android'/); - assert.match(found, /platform-harmonyos must export exactly its root façade/); + assert.match( + found, + /Managed platform must declare its family and export only @agent-device\/harmonyos\/agent-device/, + ); + assert.match(found, /platform-linux must export exactly its root façade/); assert.match(found, /missing canonical platform package.*platform-web/); }); @@ -609,7 +614,7 @@ test('platform-web production source may use only the canonical positional-ref s }); test('interactor subpaths are loaded only by the builtin registry, dynamically', () => { - for (const family of ['harmonyos', 'linux', 'web']) { + for (const family of ['linux', 'web']) { const allowed = validSources(); allowed.set( 'src/core/interactors/register-builtins.ts', @@ -809,6 +814,21 @@ test('only the plugin scope resolves the managed Vega entry', () => { assert.throws(() => resolveVega.resolve('@agent-device/vega'), /No "exports" main/); }); +test('only the plugin scope resolves the managed HarmonyOS entry', () => { + assert.throws( + () => import.meta.resolve('@agent-device/harmonyos/agent-device'), + /Cannot find package/, + ); + const resolveHarmony = createRequire( + new URL('../../packages/platform-harmonyos/package.json', import.meta.url), + ); + assert.match( + resolveHarmony.resolve('@agent-device/harmonyos/agent-device'), + /platform-harmonyos[/\\]src[/\\]index\.ts$/, + ); + assert.throws(() => resolveHarmony.resolve('@agent-device/harmonyos'), /No "exports" main/); +}); + test('the retired src/platforms zone rejects every production, test, and fixture file', () => { const planted = [ 'src/platforms/__tests__/install-source.test.ts', diff --git a/scripts/layering/platform-package-policy.ts b/scripts/layering/platform-package-policy.ts index efaaf2bea8..b9f500bb27 100644 --- a/scripts/layering/platform-package-policy.ts +++ b/scripts/layering/platform-package-policy.ts @@ -53,7 +53,6 @@ const PLATFORM_RUNTIME_HOST_FILES = new Set([ 'src/platform-runtime-operation-host.ts', 'src/platform-runtime-perf-host.ts', 'src/platform-runtime-resource-cleanup.ts', - 'src/platform-runtime-screen-recording-harmony-host.ts', 'src/platform-runtime-screen-recording-web-host.ts', 'src/platform-runtime-toolchain-host.ts', ]); @@ -107,13 +106,13 @@ const MECHANICS_FACET_SUBPATHS: Readonly>> = { web: '@agent-device/web', vega: '@agent-device/vega', + harmonyos: '@agent-device/harmonyos', }; const INTERACTOR_COMPOSITION_FILE = 'src/core/interactors/register-builtins.ts'; @@ -498,5 +497,5 @@ export function checkPlatformPackagePolicy( } export function platformPackagePolicySummary(): string { - return `R13 holds built-in and managed implementation-lazy platform packages above capture-kit behind one canonical composition root and its single private provider-composition submodule, with the android mechanics facet and the Apple runner package behind their enumerated seams; deferred or type-only edges are limited to the approved platform-runtime host watchlist and the dynamic-only HarmonyOS, Linux and Web interactor subpaths imported by ${INTERACTOR_COMPOSITION_FILE}`; + return `R13 holds built-in and managed implementation-lazy platform packages above capture-kit behind one canonical composition root and its single private provider-composition submodule, with the android mechanics facet and the Apple runner package behind their enumerated seams; deferred or type-only edges are limited to the approved platform-runtime host watchlist and the dynamic-only Linux and Web interactor subpaths imported by ${INTERACTOR_COMPOSITION_FILE}`; } diff --git a/scripts/layering/root-module-zones.ts b/scripts/layering/root-module-zones.ts index 7cb22a26f7..43e230b50c 100644 --- a/scripts/layering/root-module-zones.ts +++ b/scripts/layering/root-module-zones.ts @@ -89,7 +89,6 @@ export const ROOT_MODULE_ZONES: Readonly> = { 'src/platform-runtime-screen-recording-apple-simulator-host.ts', 'src/platform-runtime-screen-recording-apple-transport.ts', 'src/platform-runtime-screen-recording-finalizer-host.ts', - 'src/platform-runtime-screen-recording-harmony-host.ts', 'src/platform-runtime-screen-recording-host.ts', 'src/platform-runtime-screen-recording-output-host.ts', 'src/platform-runtime-screen-recording-process-host.ts', diff --git a/src/__tests__/contracts/platform-plugin-parity.test.ts b/src/__tests__/contracts/platform-plugin-parity.test.ts index 1f2c86669b..5bb90e0da7 100644 --- a/src/__tests__/contracts/platform-plugin-parity.test.ts +++ b/src/__tests__/contracts/platform-plugin-parity.test.ts @@ -11,7 +11,9 @@ import { } from '../../core/interactors/register-builtins.ts'; import { missingPlatformPlugin } from '../../core/platform-plugin-absence.ts'; -// Idempotently populate the root-owned registry for this test module. +// The optional families that ship as platform plugins: parsing a selector for them resolves a +// registration only through the plugin registry, never through a builtin row. +const PLATFORM_PLUGIN_FAMILIES = ['harmonyos', 'vega', 'web'] as const; // Independent copy of the internal platform accept-set. The CLI `--platform` // enum derives separately from `PLATFORM_SELECTORS`; this oracle keeps registry @@ -30,7 +32,7 @@ function parsePlatformByHand(value: unknown): Platform | undefined { test('built-in platforms follow the canonical family order', () => { // The builtin set holds exactly the families the packed core still owns, in canonical // `PLATFORMS` order. The optional families that ship as platform plugins have no row here. - assert.deepEqual(builtinPlatformPlugins.families, ['apple', 'android', 'harmonyos', 'linux']); + assert.deepEqual(builtinPlatformPlugins.families, ['apple', 'android', 'linux']); }); test('every required family is covered by a builtin plugin; optional families may be absent', () => { @@ -70,8 +72,10 @@ test('registry coverage is byte-for-byte equal to the parsePlatform hand allow-l ]; for (const candidate of candidates) { const registered = builtinPlatformPlugins.tryGet(candidate as Platform) !== undefined; + // The families that ship as platform plugins parse as platforms but hold no builtin row. const parses = - parsePlatformByHand(candidate) !== undefined && candidate !== 'web' && candidate !== 'vega'; + parsePlatformByHand(candidate) !== undefined && + !(PLATFORM_PLUGIN_FAMILIES as readonly unknown[]).includes(candidate); assert.equal(registered, parses, `coverage parity for ${JSON.stringify(candidate)}`); } }); @@ -89,10 +93,6 @@ test('a family plugin resolves to the SAME instance for every leaf it owns', () builtinPlatformPlugins.get('android').plugin, builtinPlatformPlugins.get('linux').plugin, ); - assert.notEqual( - builtinPlatformPlugins.get('harmonyos').plugin, - builtinPlatformPlugins.get('android').plugin, - ); }); test('each registered platform resolves to a plugin that owns it', () => { diff --git a/src/core/interactors/register-builtins.ts b/src/core/interactors/register-builtins.ts index 9de08bbd10..f6c1be82f9 100644 --- a/src/core/interactors/register-builtins.ts +++ b/src/core/interactors/register-builtins.ts @@ -16,15 +16,6 @@ const androidPlugin = { }, } as const satisfies PlatformPlugin; -const harmonyosPlugin = { - id: 'harmonyos', - platforms: ['harmonyos'], - createInteractor: async (device: DeviceInfo, runner: RunnerContext) => { - const { createHarmonyInteractor } = await import('@agent-device/platform-harmonyos/interactor'); - return createHarmonyInteractor(device, runner); - }, -} as const satisfies PlatformPlugin; - const linuxPlugin = { id: 'linux', platforms: ['linux'], @@ -44,7 +35,6 @@ const linuxPlugin = { export const BUILTIN_PLATFORM_PLUGINS = [ applePlugin, androidPlugin, - harmonyosPlugin, linuxPlugin, ] as const satisfies readonly PlatformPlugin[]; diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index c99075ae94..488a3ff8e4 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -136,8 +136,8 @@ export async function composeDaemonRuntimeDeps( providerComposition.inventory, providerComposition.assertSelectionCurrent, ); - const { web, vega } = platforms; - const hostDiagnostics = createHostDiagnostics(host, web, vega); + const { web, vega, harmony } = platforms; + const hostDiagnostics = createHostDiagnostics(host, web, vega, harmony); const deviceRuntimeGateway = createPlatformRuntimeGateway({ host, platforms, diff --git a/src/platform-runtime-harmonyos-provider.fixtures.ts b/src/platform-runtime-harmonyos-provider.fixtures.ts new file mode 100644 index 0000000000..643efe93bc --- /dev/null +++ b/src/platform-runtime-harmonyos-provider.fixtures.ts @@ -0,0 +1,35 @@ +import { createRequire } from 'node:module'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { createLiveTestHostEnvironment } from '@agent-device/test-kit'; +import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; +import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; +import type { + HarmonyPlatformRegistration, + HarmonyPlatformSelection, +} from '@agent-device/contracts/platform-plugin'; +import type { PlatformHost } from '@agent-device/plugins/contract'; + +const pluginRequire = createRequire( + new URL('../packages/platform-harmonyos/package.json', import.meta.url), +); +const { default: harmonyPlatformPlugin } = (await import( + pluginRequire.resolve('@agent-device/harmonyos/agent-device') +)) as { + default(): { contributes: [{ setup(host: PlatformHost): HarmonyPlatformRegistration }] }; +}; + +export function harmonySelectionFixture( + host: HostEnvironment = createLiveTestHostEnvironment(), + stateDir = '/test-harmony-state', +): HarmonyPlatformSelection { + const active = harmonyPlatformPlugin().contributes[0].setup( + createPlatformPluginHost(host, stateDir), + ); + return { active, get: () => active }; +} + +export function harmonyPlatformCompositionFixture( + ...args: Parameters +) { + return composePlatformPlugins([harmonySelectionFixture(...args).get()], []); +} diff --git a/src/platform-runtime-host-diagnostics.test.ts b/src/platform-runtime-host-diagnostics.test.ts index 0f8a5945d8..8966ac44f2 100644 --- a/src/platform-runtime-host-diagnostics.test.ts +++ b/src/platform-runtime-host-diagnostics.test.ts @@ -165,3 +165,72 @@ test('doctor without a Vega selector reports no Vega row when the plugin is abse ), ).toBeUndefined(); }); + +test('doctor targeted at HarmonyOS reports the absent plugin with its install command', async () => { + // Same contract as Vega: the row is the composition's own absence report, so it names the same + // package and command a HarmonyOS discovery request answers with. + const { harmony } = composePlatformPlugins([], []); + const check = await createHostDiagnostics( + createLiveTestHostEnvironment(), + undefined, + undefined, + harmony, + ).toolchainCheck('harmonyos', context); + + expect(check?.id).toBe('toolchain'); + expect(check?.status).toBe('fail'); + expect(check?.summary).toContain('@agent-device/harmonyos'); + expect(check?.hint).toContain('agent-device plugins add @agent-device/harmonyos'); + expect(check?.command).toMatch(/^agent-device plugins add @agent-device\/harmonyos/); + expect(check?.evidence).toMatchObject({ + code: 'UNSUPPORTED_PLATFORM', + reason: 'plugin-not-installed', + family: 'harmonyos', + package: '@agent-device/harmonyos', + }); +}); + +test('doctor targeted at a HarmonyOS plugin that failed to load reports what the plugin said', async () => { + const { harmony } = composePlatformPlugins([], [ + { + platform: 'harmonyos', + source: 'store', + package: '@agent-device/harmonyos', + version: '0.22.0-dev', + state: 'failed', + credentials: { variables: [], byBackend: {} }, + error: { + code: 'COMMAND_FAILED', + message: 'Plugin exited during setup', + reason: 'setup-threw', + }, + }, + ] satisfies readonly PluginInventoryEntry[]); + const check = await createHostDiagnostics( + createLiveTestHostEnvironment(), + undefined, + undefined, + harmony, + ).toolchainCheck('harmonyos', context); + + expect(check?.status).toBe('fail'); + expect(check?.summary).toContain('Plugin exited during setup'); + expect(check?.evidence).toMatchObject({ + code: 'COMMAND_FAILED', + reason: 'setup-threw', + family: 'harmonyos', + package: '@agent-device/harmonyos', + }); +}); + +test('doctor without a HarmonyOS selector reports no HarmonyOS row when the plugin is absent', async () => { + const { harmony } = composePlatformPlugins([], []); + expect( + await createHostDiagnostics( + createLiveTestHostEnvironment(), + undefined, + undefined, + harmony, + ).toolchainCheck(undefined, context), + ).toBeUndefined(); +}); diff --git a/src/platform-runtime-host-diagnostics.ts b/src/platform-runtime-host-diagnostics.ts index 2e5169805d..f1950fc8c4 100644 --- a/src/platform-runtime-host-diagnostics.ts +++ b/src/platform-runtime-host-diagnostics.ts @@ -1,4 +1,5 @@ import type { + HarmonyPlatformSelection, VegaPlatformSelection, WebPlatformSelection, } from '@agent-device/contracts/platform-plugin'; @@ -21,6 +22,7 @@ export function createHostDiagnostics( host: HostEnvironment, web?: WebPlatformSelection, vega?: VegaPlatformSelection, + harmony?: HarmonyPlatformSelection, ): HostDiagnostics { const { env } = host; return Object.freeze({ @@ -35,11 +37,12 @@ export function createHostDiagnostics( if (platform === 'vega') { const { active } = vega ?? {}; if (active) return await active.operations.toolchainCheck(context); - return await vegaAbsenceCheck(vega); + return await pluginAbsenceCheck('Vega', vega); } if (platform === 'harmonyos') { - const { harmonyToolchainCheck } = await import('@agent-device/platform-harmonyos'); - return await harmonyToolchainCheck(); + const { active } = harmony ?? {}; + if (active) return await active.operations.toolchainCheck(); + return await pluginAbsenceCheck('HarmonyOS', harmony); } if (platform === 'ios' || platform === 'macos' || platform === 'apple') { const { appleToolchainCheck } = await import('@agent-device/platform-apple/doctor'); @@ -70,17 +73,18 @@ export function createHostDiagnostics( }); } -// Doctor reaches this only for a run whose selector named Vega, so an inactive selection is the -// user's blocker rather than one family among many. The selection's own lookup owns the answer: an -// uninstalled plugin raises the typed plugin-not-installed outcome and a plugin whose load failed -// raises its own error, both through the composition's one absence reporter. The check reports that -// outcome's own fields; it never re-derives them. -async function vegaAbsenceCheck( - vega: VegaPlatformSelection | undefined, +// Doctor reaches this only for a run whose selector named the family, so an inactive selection is +// the user's blocker rather than one family among many. The selection's own lookup owns the answer: +// an uninstalled plugin raises the typed plugin-not-installed outcome and a plugin whose load +// failed raises its own error, both through the composition's one absence reporter. The check +// reports that outcome's own fields; it never re-derives them. +async function pluginAbsenceCheck( + label: string, + selection: Readonly<{ get(): unknown }> | undefined, ): Promise { - if (!vega) return undefined; + if (!selection) return undefined; try { - vega.get(); + selection.get(); return undefined; } catch (error) { const report = normalizeError(error); @@ -88,7 +92,7 @@ async function vegaAbsenceCheck( return { id: 'toolchain', status: 'fail', - summary: `Vega toolchain: ${report.message}`, + summary: `${label} toolchain: ${report.message}`, hint: report.hint, ...(typeof installCommand === 'string' ? { command: installCommand } : {}), evidence: { code: report.code, ...report.details }, diff --git a/src/platform-runtime-host.ts b/src/platform-runtime-host.ts index 366844f90e..6f045c1ac1 100644 --- a/src/platform-runtime-host.ts +++ b/src/platform-runtime-host.ts @@ -1,4 +1,5 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { HarmonyPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { DeviceInventoryHost, HostOperatingSystem, @@ -14,7 +15,10 @@ import { createHostToolchainPreparer } from './platform-runtime-toolchain-host.t import { createHostCommandRunner } from './platform-runtime-host-command-runner.ts'; import { hostHomeDirectoryFromEnv } from '@agent-device/host-kit/host-file'; -export function createDeviceInventoryHost(host: HostEnvironment): DeviceInventoryHost { +export function createDeviceInventoryHost( + host: HostEnvironment, + harmony?: HarmonyPlatformSelection, +): DeviceInventoryHost { const env = host.env; // The host names its own home; families derive default-install paths from it (#3794). A host // that names none (HOME and USERPROFILE both absent, e.g. env -i or a systemd unit without @@ -24,7 +28,7 @@ export function createDeviceInventoryHost(host: HostEnvironment): DeviceInventor return Object.freeze({ commands: createHostCommandRunner(host), appleTools: createAppleToolHost(), - toolchains: createHostToolchainPreparer(env), + toolchains: createHostToolchainPreparer(env, harmony), files: Object.freeze({ isExecutable: async (candidate: string) => await isExecutable(candidate), createTemporaryTextFile: async (options: { prefix: string; suffix: string }) => diff --git a/src/platform-runtime-operation-host.ts b/src/platform-runtime-operation-host.ts index bb9641c9dc..941c323856 100644 --- a/src/platform-runtime-operation-host.ts +++ b/src/platform-runtime-operation-host.ts @@ -1,4 +1,5 @@ import type { + HarmonyPlatformSelection, PlatformPluginSet, WebPlatformSelection, } from '@agent-device/contracts/platform-plugin'; @@ -57,6 +58,7 @@ export async function loadMacOsSurfaceSnapshot( export function createPlatformRuntimeHost(options: { host: HostEnvironment; web?: WebPlatformSelection; + harmony?: HarmonyPlatformSelection; interactors?: PlatformPluginSet; sessionsDir: string; resolveSessionArtifacts(sessionId: string): AppLogSessionArtifacts; @@ -87,7 +89,7 @@ export function createPlatformRuntimeHost(options: { hostEnvironment: host, commands, appleTools, - toolchains: createHostToolchainPreparer(env), + toolchains: createHostToolchainPreparer(env, options.harmony), artifacts: Object.freeze({ resolveSession: options.resolveSessionArtifacts }), outputs: Object.freeze({ openAppend: async (pathname: string) => diff --git a/src/platform-runtime-perf-host.test.ts b/src/platform-runtime-perf-host.test.ts index 86cf96e530..5b997ab68b 100644 --- a/src/platform-runtime-perf-host.test.ts +++ b/src/platform-runtime-perf-host.test.ts @@ -41,11 +41,10 @@ const scope = { test('exposes family-specific mechanics without a bind or platform switch surface', () => { const host = createPerfRuntimeHost(); - expect(Object.keys(host).sort()).toEqual(['android', 'apple', 'harmony']); + expect(Object.keys(host).sort()).toEqual(['android', 'apple']); expect(host).not.toHaveProperty('bind'); expect(Object.keys(host.apple)).toContain('frameSampling'); expect(Object.keys(host.android)).not.toContain('frameSampling'); - expect(Object.keys(host.harmony)).toEqual(['sampleMemory']); }); test('the composed Android perf operation reports an unavailable ADB memory sample', async () => { diff --git a/src/platform-runtime-perf-host.ts b/src/platform-runtime-perf-host.ts index 6e64811d01..6df1e01cae 100644 --- a/src/platform-runtime-perf-host.ts +++ b/src/platform-runtime-perf-host.ts @@ -18,7 +18,6 @@ const loadAndroidNativePerf = loadAndroidMechanics; const loadApplePerf = async () => await import('@agent-device/platform-apple/perf'); const loadApplePerfMechanics = async () => await import('@agent-device/platform-apple/perf'); const loadAppleXctrace = async () => await import('@agent-device/platform-apple/perf'); -const loadHarmonyPerf = async () => await import('@agent-device/platform-harmonyos'); /** Lazy host-only mechanics. Platform packages own facts, policy, and operation construction. */ export function createPerfRuntimeHost(): PerfRuntimeHost { @@ -68,11 +67,7 @@ export function createPerfRuntimeHost(): PerfRuntimeHost { input.outPath, ), }); - const harmony: PerfRuntimeHost['harmony'] = Object.freeze({ - sampleMemory: async (device, appId) => - await (await loadHarmonyPerf()).sampleHarmonyMemoryPerf(device, appId), - }); - return Object.freeze({ apple, android, harmony }); + return Object.freeze({ apple, android }); } // Durable data is untrusted at this boundary; keep every required discriminator explicit. diff --git a/src/platform-runtime-screen-recording-harmony-host.test.ts b/src/platform-runtime-screen-recording-harmony-host.test.ts deleted file mode 100644 index 5e660cf4f8..0000000000 --- a/src/platform-runtime-screen-recording-harmony-host.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { expect, test, vi } from 'vitest'; -import { createHarmonyScreenRecordingHost } from './platform-runtime-screen-recording-harmony-host.ts'; - -const hdc = vi.hoisted(() => vi.fn()); -vi.mock('@agent-device/platform-harmonyos', async () => { - const { deviceShellArgv } = await import('@agent-device/kernel/device-shell'); - return { - runHarmonyHdc: hdc, - runHarmonyShell: (device: unknown, words: readonly string[], options: unknown) => - hdc(device, deviceShellArgv('adb', 'shell', words), options), - }; -}); - -const device = { - platform: 'harmonyos' as const, - id: 'harmony-device', - name: 'Harmony device', - kind: 'device' as const, - target: 'mobile' as const, - booted: true, -}; - -test('reports artifact removal only after a confirmed HDC success', async () => { - hdc.mockResolvedValueOnce({ stdout: '', stderr: 'permission denied', exitCode: 1 }); - const host = createHarmonyScreenRecordingHost(); - - await expect(host.remove(device, '/data/local/tmp/capture.mp4')).resolves.toBe(false); - expect(hdc).toHaveBeenCalledWith(device, ['shell', 'rm', '-f', '/data/local/tmp/capture.mp4'], { - allowFailure: true, - signal: undefined, - }); -}); - -test('reads the staged byte count from focused HDC stat output', async () => { - hdc.mockResolvedValueOnce({ stdout: '12345\n', stderr: '', exitCode: 0 }); - const host = createHarmonyScreenRecordingHost(); - - await expect(host.stagedFileSize(device, '/data/local/tmp/capture.mp4')).resolves.toBe(12_345); - expect(hdc).toHaveBeenCalledWith( - device, - ['shell', 'stat', '-c', '%s', '/data/local/tmp/capture.mp4'], - { allowFailure: true, signal: undefined }, - ); -}); diff --git a/src/platform-runtime-screen-recording-host.ts b/src/platform-runtime-screen-recording-host.ts index 226f70d7be..72d41761e3 100644 --- a/src/platform-runtime-screen-recording-host.ts +++ b/src/platform-runtime-screen-recording-host.ts @@ -66,7 +66,6 @@ export function createScreenRecordingRuntimeHost(options: { return Object.freeze({ apple: createLazyAppleHost(host), android, - harmony: createLazyHarmonyHost(), web, outputs, finalize, @@ -97,26 +96,3 @@ function createLazyAppleHost(host: HostEnvironment): ScreenRecordingRuntimeHost[ isRunnerBundleId: async (bundleId) => await (await load()).isRunnerBundleId(bundleId), }); } - -function createLazyHarmonyHost(): ScreenRecordingRuntimeHost['harmony'] { - const load = async () => { - const { createHarmonyScreenRecordingHost } = - await import('./platform-runtime-screen-recording-harmony-host.ts'); - return createHarmonyScreenRecordingHost(); - }; - return Object.freeze({ - start: async (device, fileName, signal) => await (await load()).start(device, fileName, signal), - stop: async (device, signal) => await (await load()).stop(device, signal), - findMedia: async (device, fileName, signal) => - await (await load()).findMedia(device, fileName, signal), - stageMedia: async (device, input, signal) => - await (await load()).stageMedia(device, input, signal), - stagedFileSize: async (device, remotePath, signal) => - await (await load()).stagedFileSize(device, remotePath, signal), - pull: async (device, input, signal) => await (await load()).pull(device, input, signal), - remove: async (device, remotePath, signal) => - await (await load()).remove(device, remotePath, signal), - removeMedia: async (device, mediaUri, signal) => - await (await load()).removeMedia(device, mediaUri, signal), - }); -} diff --git a/src/platform-runtime-toolchain-host.test.ts b/src/platform-runtime-toolchain-host.test.ts index a6b2ec4e1c..8d9a690f6a 100644 --- a/src/platform-runtime-toolchain-host.test.ts +++ b/src/platform-runtime-toolchain-host.test.ts @@ -1,9 +1,12 @@ import { expect, test, vi } from 'vitest'; +import type { + HarmonyPlatformRegistration, + HarmonyPlatformSelection, +} from '@agent-device/contracts/platform-plugin'; const toolchains = vi.hoisted(() => ({ androidEvaluations: 0, androidPrepares: 0, - harmonyEvaluations: 0, harmonyPrepares: 0, })); @@ -16,40 +19,33 @@ vi.mock('@agent-device/platform-android/mechanics', () => { }; }); -vi.mock('@agent-device/platform-harmonyos', () => { - toolchains.harmonyEvaluations += 1; - return { - ensureHarmonyToolchainPathConfigured: async () => { - toolchains.harmonyPrepares += 1; - }, - }; -}); - import { createHostToolchainPreparer } from './platform-runtime-toolchain-host.ts'; +/** A selection whose only live member is the toolchain preparation the host arm calls. */ +function harmonySelectionFixture(): HarmonyPlatformSelection { + const active = { + operations: { + prepareToolchain: async () => { + toolchains.harmonyPrepares += 1; + }, + }, + } as unknown as HarmonyPlatformRegistration; + return { active, get: () => active }; +} + test('toolchain host loads and prepares only the selected family', async () => { - const host = createHostToolchainPreparer(process.env); + const host = createHostToolchainPreparer(process.env, harmonySelectionFixture()); - expect(toolchains).toEqual({ - androidEvaluations: 0, - androidPrepares: 0, - harmonyEvaluations: 0, - harmonyPrepares: 0, - }); + expect(toolchains).toEqual({ androidEvaluations: 0, androidPrepares: 0, harmonyPrepares: 0 }); await host.prepare('android'); - expect(toolchains).toEqual({ - androidEvaluations: 1, - androidPrepares: 1, - harmonyEvaluations: 0, - harmonyPrepares: 0, - }); + expect(toolchains).toEqual({ androidEvaluations: 1, androidPrepares: 1, harmonyPrepares: 0 }); await host.prepare('harmonyos'); - expect(toolchains).toEqual({ - androidEvaluations: 1, - androidPrepares: 1, - harmonyEvaluations: 1, - harmonyPrepares: 1, - }); + expect(toolchains).toEqual({ androidEvaluations: 1, androidPrepares: 1, harmonyPrepares: 1 }); +}); + +test('toolchain host answers a HarmonyOS request with nothing before the plugin is installed', async () => { + const host = createHostToolchainPreparer(process.env); + await expect(host.prepare('harmonyos')).resolves.toBeUndefined(); }); diff --git a/src/platform-runtime-toolchain-host.ts b/src/platform-runtime-toolchain-host.ts index 3f193ae4cc..474b869b26 100644 --- a/src/platform-runtime-toolchain-host.ts +++ b/src/platform-runtime-toolchain-host.ts @@ -1,8 +1,12 @@ import type { EnvMap } from '@agent-device/kernel/source-value'; +import type { HarmonyPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { HostToolchainPreparer } from '@agent-device/contracts/platform-runtime-host'; import { loadAndroidMechanics } from './platform-runtime-android-mechanics.ts'; -export function createHostToolchainPreparer(env: Readonly): HostToolchainPreparer { +export function createHostToolchainPreparer( + env: Readonly, + harmony?: HarmonyPlatformSelection, +): HostToolchainPreparer { return Object.freeze({ prepare: async (family) => { if (family === 'android') { @@ -10,10 +14,11 @@ export function createHostToolchainPreparer(env: Readonly): HostToolchai await ensureAndroidSdkPathConfigured(env); return; } + // Only the HarmonyOS plugin reaches this arm: its device discovery and hilog streaming ask + // the host to prepend the toolchain roots they were configured with. The plugin owns which + // roots those are; the core hands over the host environment it captured. if (family === 'harmonyos') { - const { ensureHarmonyToolchainPathConfigured } = - await import('@agent-device/platform-harmonyos'); - await ensureHarmonyToolchainPathConfigured(env); + await harmony?.get().operations.prepareToolchain(env); } }, }); diff --git a/src/platform-runtime.test.ts b/src/platform-runtime.test.ts index 1d345033c2..45062ece3b 100644 --- a/src/platform-runtime.test.ts +++ b/src/platform-runtime.test.ts @@ -33,6 +33,7 @@ vi.mock('./platform-runtime-host.ts', () => { import { webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; import { vegaSelectionFixture } from './platform-runtime-vega-provider.fixtures.ts'; +import { harmonySelectionFixture } from './platform-runtime-harmonyos-provider.fixtures.ts'; import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; import { createPlatformDeviceInventoryGateways, @@ -41,10 +42,10 @@ import { bindTestCommandHost(); -// Both optional families that ship as platform plugins are supplied here, so the registry covers -// the whole canonical family tuple. +// All three optional families that ship as platform plugins are supplied here, so the registry +// covers the whole canonical family tuple. const platformSelection = composePlatformPlugins( - [webSelectionFixture().get(), vegaSelectionFixture().get()], + [webSelectionFixture().get(), vegaSelectionFixture().get(), harmonySelectionFixture().get()], [], ); const platformModuleRegistry = createPlatformModuleRegistryForHost({}, platformSelection); diff --git a/src/platform-runtime.ts b/src/platform-runtime.ts index 8c084da3e1..6ef907e782 100644 --- a/src/platform-runtime.ts +++ b/src/platform-runtime.ts @@ -36,10 +36,6 @@ import { readAndroidAppStateWithExecutor, loadShutdownRuntime as loadAndroidShutdownRuntime, } from '@agent-device/platform-android'; -import { - createHarmonyInventoryModule, - runtimeModule as harmonyosRuntimeModule, -} from '@agent-device/platform-harmonyos'; import { captureLinuxSurfaceSnapshot, inventoryModule as linuxInventoryModule, @@ -89,11 +85,6 @@ export function createPlatformModuleRegistryForHost( createAndroidInventoryModule({ sdkRoots: configuredValues(env.ANDROID_SDK_ROOT, env.ANDROID_HOME), }), - createHarmonyInventoryModule({ - hdcSdkPath: env.HDC_SDK_PATH, - devecoSdkHome: env.DEVECO_SDK_HOME, - commandLineToolsHome: env.HARMONYOS_COMMAND_LINE_TOOLS, - }), linuxInventoryModule, ...(platforms?.inventoryModules ?? []), ], @@ -111,7 +102,7 @@ export async function createPlatformDeviceInventoryGateways( registry: createPlatformModuleRegistryForHost(host.env, platforms), loadHost: async () => { const { createDeviceInventoryHost } = await import('./platform-runtime-host.ts'); - return createDeviceInventoryHost(host); + return createDeviceInventoryHost(host, platforms?.harmony); }, provider, env: host.env, @@ -127,13 +118,7 @@ const androidRuntimeModule = createAndroidRuntimeModule({ function createPlatformRuntimeModuleRegistry(platforms: PlatformModuleSelection) { return createPlatformModuleRegistry( - [ - appleRuntimeModule, - androidRuntimeModule, - harmonyosRuntimeModule, - linuxRuntimeModule, - ...platforms.runtimeModules, - ], + [appleRuntimeModule, androidRuntimeModule, linuxRuntimeModule, ...platforms.runtimeModules], platforms.reportAbsent, platforms.assertSelectionCurrent, ); @@ -160,6 +145,7 @@ export function createPlatformRuntimeGateway( return createPlatformRuntimeHost({ host: options.host, web: options.platforms.web, + harmony: options.platforms.harmony, interactors: options.platforms.interactors, sessionsDir: options.sessionsDir, resolveSessionArtifacts: options.resolveSessionArtifacts, diff --git a/src/platform-runtime/platform-plugins.ts b/src/platform-runtime/platform-plugins.ts index c0f5af3f8a..c4dc97d855 100644 --- a/src/platform-runtime/platform-plugins.ts +++ b/src/platform-runtime/platform-plugins.ts @@ -1,4 +1,6 @@ import type { + HarmonyPlatformRegistration, + HarmonyPlatformSelection, PlatformModuleSelection, PlatformPlugin, VegaPlatformRegistration, @@ -18,6 +20,7 @@ import { missingPlatformPlugin } from '../core/platform-plugin-absence.ts'; type RuntimePlatformPlugin = PlatformPlugin & { web?: WebPlatformRegistration; vega?: VegaPlatformRegistration; + harmony?: HarmonyPlatformRegistration; }; export function builtinPlatformCandidates(): readonly PluginCandidate[] { @@ -82,6 +85,7 @@ export function composePlatformPlugins( createInteractor: platform.createInteractor.bind(platform), ...(platform.family === 'web' ? { web: platform } : {}), ...(platform.family === 'vega' ? { vega: platform } : {}), + ...(platform.family === 'harmonyos' ? { harmony: platform } : {}), })), ], reportAbsent, @@ -106,10 +110,25 @@ export function composePlatformPlugins( }, }; + // The HarmonyOS selection's `get()` is the one authority on the family's absence: an uninstalled + // plugin raises `plugin-not-installed` with its install command, and one that failed to load + // raises its own error. Doctor's toolchain row reports that outcome instead of probing a + // toolchain no plugin is there to drive. + const harmony: HarmonyPlatformSelection = { + active: interactors.tryGet('harmonyos')?.plugin.harmony, + get() { + const { harmony } = interactors.get('harmonyos').plugin; + if (!harmony) + throw new TypeError('HarmonyOS platform registration is missing its operations'); + return harmony; + }, + }; + return { interactors, web, vega, + harmony, inventoryModules: platforms.map((platform) => platform.inventoryModule), runtimeModules: platforms.map((platform) => platform.runtimeModule), reportAbsent, diff --git a/test/repo-guards/npm-package-scripts.test.ts b/test/repo-guards/npm-package-scripts.test.ts index 727032d00b..fd8a9dc198 100644 --- a/test/repo-guards/npm-package-scripts.test.ts +++ b/test/repo-guards/npm-package-scripts.test.ts @@ -99,7 +99,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', + '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', 'node --experimental-strip-types scripts/check-package.ts', ]); assert.match(packagedCliWorkflow, /with: \{ gate: package \}/); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 4590ddefd8..910131fbe6 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -615,7 +615,7 @@ agent-device capabilities --session checkout --json ### HarmonyOS command boundary -HarmonyOS support uses HDC and ArkUI `uitest`. On API 24 devices it supports lifecycle and HAP deployment, ArkUI snapshot/screenshot and selector reads, one-pointer touch and text actions, keyboard `enter`/`dismiss`, app logs, foreground app state, process RSS samples, and `settings clear-app-state`. Run `agent-device capabilities --platform harmonyos` for the command list of a selected device. +HarmonyOS runs through the optional `@agent-device/harmonyos` plugin (`agent-device plugins add @agent-device/harmonyos`; see [Installation](/docs/installation#harmonyos-prerequisites)). HarmonyOS support uses HDC and ArkUI `uitest`. On API 24 devices it supports lifecycle and HAP deployment, ArkUI snapshot/screenshot and selector reads, one-pointer touch and text actions, keyboard `enter`/`dismiss`, app logs, foreground app state, process RSS samples, and `settings clear-app-state`. Run `agent-device capabilities --platform harmonyos` for the command list of a selected device. - `gesture pan|fling|swipe` and `swipe` use single-pointer input. Multi-touch gestures and target-authored `gesture drag` return `UNSUPPORTED_OPERATION`. - Physical devices support whole-screen recording with `record start --scope device` or `--scope system`, without `--fps`, `--quality`, or `--hide-touches`. Emulator recording is rejected. diff --git a/website/docs/docs/installation.md b/website/docs/docs/installation.md index 4cd5362991..8e1f764db2 100644 --- a/website/docs/docs/installation.md +++ b/website/docs/docs/installation.md @@ -17,7 +17,7 @@ Install `agent-device` on the machine where your coding agent runs terminal comm daemon is already running; without it, the daemon uses the environment it started in. Set `DEVELOPER_DIR=""` to use the daemon host's `xcode-select` selection instead. - Android SDK and ADB for Android, Android TV, and Fire TV devices running Fire OS -- HarmonyOS Command Line Tools for HarmonyOS (`hdc` available through `HDC_SDK_PATH`, `DEVECO_SDK_HOME`, or `HARMONYOS_COMMAND_LINE_TOOLS`) +- 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 - Swift 5.9 or newer (Xcode command-line tools) for macOS desktop targets. `agent-device` builds its local macOS helper on first use @@ -63,6 +63,19 @@ npx agent-device@nightly-0.22 open Settings --platform ios One-off `npx` use is fine for you and for scripts that intentionally fetch from npm. For agents, use a global install, a project-local install, or a version pinned by you or your project config, so repeated commands resolve to a known CLI. +## HarmonyOS prerequisites + +Install the HarmonyOS Command Line Tools so `hdc` resolves, then install the HarmonyOS platform plugin: + +```bash +agent-device plugins add @agent-device/harmonyos +agent-device devices --platform harmonyos +``` + +- The plugin reads `hdc` from the daemon host's `PATH`, or from a toolchain root named by `HDC_SDK_PATH`, `DEVECO_SDK_HOME`, or `HARMONYOS_COMMAND_LINE_TOOLS`. Set the variable you use in the environment that starts the daemon. +- Without the plugin, a command that names `--platform harmonyos` fails with `details.reason: "plugin-not-installed"` and the install command. Commands that name no platform skip HarmonyOS. +- For what HarmonyOS supports, see [HarmonyOS command boundary](/docs/commands#harmonyos-command-boundary). + ## Vega OS TV prerequisites Install the Amazon Vega Developer Tools and a matching Vega SDK and Vega Virtual Device (VVD) with Amazon's installer, then load its environment and verify the tools: diff --git a/website/docs/docs/quick-start.md b/website/docs/docs/quick-start.md index 8cd22c6c4f..6c7f5ac4b7 100644 --- a/website/docs/docs/quick-start.md +++ b/website/docs/docs/quick-start.md @@ -4,7 +4,7 @@ title: Quick start Open an app, read its UI, and interact with it from the command line. -Before you start, [install `agent-device`](/docs/installation) and the platform tools for your target: Xcode for iOS, the Android SDK and ADB for Android, or the HarmonyOS Command Line Tools for HarmonyOS. To set up Cursor, Codex, Claude Code, Windsurf, Cline, Goose, or another coding agent, see [AI agent setup](/docs/agent-setup). To give an agent the whole documentation as one text file, use [llms-full.txt](https://agent-device.dev/llms-full.txt). +Before you start, [install `agent-device`](/docs/installation) and the platform tools for your target: Xcode for iOS, the Android SDK and ADB for Android, or the HarmonyOS Command Line Tools plus the `@agent-device/harmonyos` plugin for HarmonyOS. To set up Cursor, Codex, Claude Code, Windsurf, Cline, Goose, or another coding agent, see [AI agent setup](/docs/agent-setup). To give an agent the whole documentation as one text file, use [llms-full.txt](https://agent-device.dev/llms-full.txt). Device automation follows this pattern: From fdd753aed444f1d35ffe1346f842a0919cad0d45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 20:46:43 +0100 Subject: [PATCH 2/5] refactor(recording): share the transport recording snapshot builder The HarmonyOS plugin rebuilt the live recording snapshot field for field, so the shape now comes from capture-kit and the plugin names only its recorder. --- packages/capture-kit/src/index.ts | 1 + .../src/screen-recording-transport.ts | 9 ++++++-- packages/platform-harmonyos/src/index.test.ts | 21 ++++++++++++------- .../src/recording/runtime.ts | 19 ++++------------- src/commands/schema/cli-help.ts | 2 +- 5 files changed, 26 insertions(+), 26 deletions(-) diff --git a/packages/capture-kit/src/index.ts b/packages/capture-kit/src/index.ts index afc77befd0..439c56853f 100644 --- a/packages/capture-kit/src/index.ts +++ b/packages/capture-kit/src/index.ts @@ -13,6 +13,7 @@ export { decodeDurableDescriptor } from './durable-descriptor-codec.ts'; export { createRetryableCleanup } from '@agent-device/contracts/durable-resource'; export { createScreenRecordingLiveHandle } from './screen-recording-live-handle.ts'; export { createScreenRecordingCompletion } from './screen-recording-completion.ts'; +export { createTransportRecordingSnapshot } from './screen-recording-transport.ts'; export { assertScreenRecordingOptionsSupported } from './screen-recording-options.ts'; export { cleanupManagedAppLogProcess, diff --git a/packages/capture-kit/src/screen-recording-transport.ts b/packages/capture-kit/src/screen-recording-transport.ts index 4d26954667..c3bdc0b485 100644 --- a/packages/capture-kit/src/screen-recording-transport.ts +++ b/packages/capture-kit/src/screen-recording-transport.ts @@ -112,7 +112,7 @@ export async function startTransportScreenRecording(params: { throw error; } const handle = createScreenRecordingLiveHandle( - transportRecordingSnapshot(transport.backend, input), + createTransportRecordingSnapshot(transport.backend, input), { finish: async (current) => { const collectible = await stopOnce(); @@ -176,7 +176,12 @@ function memoizeStop(transport: ScreenRecordingTransport = {}): PlatformHost { +function createPluginHost(env: PlatformHost['env'] = {}): PlatformHost { return { env, cwd: '/host-cwd', stateDir: '/host-state', runCommand: async () => ({ stdout: '', stderr: '', exitCode: 0 }), - emitDiagnostic: () => undefined, - withDiagnosticTimer: async (_label, run) => await run(), - } as unknown as PlatformHost; + emitDiagnostic, + withDiagnosticTimer, + }; } function setupHarmonyPlatform(host?: PlatformHost): HarmonyPlatformRegistration { @@ -131,10 +132,14 @@ test('setup hands the host it was set up with to the inventory module it registe test('setup creates the HarmonyOS interactor lazily', async () => { const registration = setupHarmonyPlatform(); - const interactor = await registration.createInteractor(HARMONY_DEVICE, {}, { - env: {}, - cwd: '/host-cwd', - }); + const interactor = await registration.createInteractor( + HARMONY_DEVICE, + {}, + { + env: {}, + cwd: '/host-cwd', + }, + ); assert.equal(typeof interactor.snapshot, 'function'); assert.equal(typeof interactor.tap, 'function'); diff --git a/packages/platform-harmonyos/src/recording/runtime.ts b/packages/platform-harmonyos/src/recording/runtime.ts index 002251b5bf..db58683655 100644 --- a/packages/platform-harmonyos/src/recording/runtime.ts +++ b/packages/platform-harmonyos/src/recording/runtime.ts @@ -13,6 +13,7 @@ import { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; import { createScreenRecordingCompletion, createScreenRecordingLiveHandle, + createTransportRecordingSnapshot, assertScreenRecordingOptionsSupported, } from '@agent-device/capture-kit'; import { @@ -22,6 +23,8 @@ import { } from './recovery.ts'; import { createHarmonyScreenRecorder, type HarmonyScreenRecorder } from './recorder.ts'; +const HARMONY_SCREEN_RECORDING_BACKEND = 'HarmonyOS ScreenRecorder'; + /** * The host the HarmonyOS recording operations consume: output preparation and video finalization * from the shared runtime host, plus the HDC recorder this family drives. The recorder is part of @@ -122,7 +125,7 @@ async function startHarmonyRecording(params: { await cleanupLiveHarmonyDescriptor(recorder, device, descriptor).catch(() => {}); throw error; } - const initial = snapshot(input); + const initial = createTransportRecordingSnapshot(HARMONY_SCREEN_RECORDING_BACKEND, input); let recorderStopped = false; const stopRecorder = async () => { if (recorderStopped) return; @@ -142,20 +145,6 @@ async function startHarmonyRecording(params: { }); } -function snapshot(input: ScreenRecordingStartInput): ScreenRecordingLiveSnapshot { - return Object.freeze({ - backend: 'HarmonyOS ScreenRecorder', - outPath: input.outputPath, - ...(input.clientOutputPath === undefined ? {} : { clientOutPath: input.clientOutputPath }), - startedAt: Date.now(), - scope: input.scope, - showTouches: false, - recordOnlySession: input.recordOnlySession, - ...(input.activeSessionApp === undefined ? {} : { activeSessionApp: input.activeSessionApp }), - gestureEvents: [], - }); -} - async function finishHarmonyRecording( host: HarmonyScreenRecordingOperationHost, recorder: HarmonyScreenRecorder, diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 77610a9a69..0b25363701 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -97,7 +97,7 @@ Command shape: Bootstrap: open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; no provider fallback. - An absent optional platform returns details.reason plugin-not-installed with its install command. + An absent optional platform returns details.reason plugin-not-installed with its install command. HarmonyOS is an optional platform: agent-device plugins add @agent-device/harmonyos. Install arguments are app/package id then artifact path: agent-device install com.example.app ./dist/app.apk --platform android, then open --relaunch for fresh state. Use reinstall only when explicitly requested. Unknown app id: devices, then apps, then open . Never open artifact paths or invent package ids; ask if lookup misses the target. Apple CI: prepare ios-runner after boot/install, before replay/test (help prepare). Remote/cloud: connect -> open -> commands -> close -> disconnect (help remote). Reusable scripts, secret-safe fills, replay repair: help scripting. From 626d018259e9d01649240cd805cec036dd14ebe6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 21:57:09 +0100 Subject: [PATCH 3/5] refactor(harmonyos): run the plugin's commands on its setup host Every process spawn and diagnostic in @agent-device/harmonyos now goes through the PlatformHost the core hands setup(): one command runner and one HDC route are built there and handed to inventory, runtime, interactor, recorder and doctor, so the packed bundle carries no separate host-kit command or diagnostics scope. The layering policy bans those two runtime scopes for every managed platform package, with the web and Vega files that still import them registered as their own migration slices. The HarmonyOS facade stays metadata-eager, the core's toolchain preparer is android-only, and the packed-plugin smoke test drives discovery, launch, snapshot, a press, capture and close against a stub HDC reachable only through HDC_SDK_PATH. --- .../harmonyos-managed-platform-2026-11-20.md | 126 ++++++++ packages/build-config/package.json | 1 + packages/build-config/src/index.test.ts | 120 ++++++++ packages/build-config/tsconfig.json | 2 +- packages/capture-kit/src/index.ts | 1 - .../command-surface/src/management/device.ts | 4 + packages/contracts/src/platform-module.ts | 8 +- packages/contracts/src/platform-plugin.ts | 16 +- .../contracts/src/platform-runtime-host.ts | 3 +- .../composed-inventory-gateways.test.ts | 19 +- .../src/composed-inventory-gateways.ts | 11 +- packages/platform-harmonyos/package.json | 1 - .../src/__tests__/app-lifecycle.test.ts | 256 +++++++--------- .../src/__tests__/doctor.test.ts | 56 ++-- .../src/__tests__/hdc-shell.test.ts | 47 --- .../src/__tests__/hdc.test.ts | 281 ++++++++++-------- .../src/__tests__/input-actions.test.ts | 89 +++--- .../src/__tests__/keyboard-band.test.ts | 94 +++--- .../src/__tests__/perf.test.ts | 37 +-- .../src/__tests__/screenshot.test.ts | 42 ++- .../src/__tests__/settings.test.ts | 26 +- .../__tests__/snapshot-viewport-cache.test.ts | 58 ++-- .../src/__tests__/snapshot.test.ts | 46 +-- .../src/__tests__/tmp-dir.ts | 14 - .../platform-harmonyos/src/app-lifecycle.ts | 35 ++- packages/platform-harmonyos/src/app-state.ts | 5 +- .../platform-harmonyos/src/command-host.ts | 116 ++++++++ .../src/deployment/runtime.test.ts | 240 ++++++++------- .../src/deployment/runtime.ts | 126 +++----- packages/platform-harmonyos/src/doctor.ts | 25 +- packages/platform-harmonyos/src/hdc.ts | 139 +++++---- packages/platform-harmonyos/src/index.test.ts | 119 ++++---- packages/platform-harmonyos/src/index.ts | 90 +++--- .../platform-harmonyos/src/input-actions.ts | 60 ++-- .../platform-harmonyos/src/interactor.test.ts | 15 +- packages/platform-harmonyos/src/interactor.ts | 51 ++-- .../platform-harmonyos/src/inventory.test.ts | 182 ++++++------ packages/platform-harmonyos/src/inventory.ts | 118 ++------ .../platform-harmonyos/src/keyboard-band.ts | 5 +- .../src/logs/runtime.test.ts | 55 ++-- .../platform-harmonyos/src/logs/runtime.ts | 32 +- packages/platform-harmonyos/src/perf.ts | 15 +- .../src/perf/runtime.test.ts | 4 +- .../platform-harmonyos/src/perf/runtime.ts | 9 +- .../src/recording/recorder.test.ts | 134 +++++++++ .../src/recording/recorder.ts | 26 +- .../src/recording/runtime.fixtures.ts | 12 +- .../src/recording/runtime.test.ts | 2 +- .../src/recording/runtime.ts | 6 +- .../platform-harmonyos/src/runtime.test.ts | 52 ++-- packages/platform-harmonyos/src/runtime.ts | 19 +- packages/platform-harmonyos/src/screenshot.ts | 14 +- packages/platform-harmonyos/src/settings.ts | 7 +- packages/platform-harmonyos/src/snapshot.ts | 22 +- .../src/toolbox.fixtures.ts | 206 +++++++++++++ packages/platform-harmonyos/src/toolbox.ts | 31 ++ .../platform-harmonyos/test/package-smoke.mjs | 112 ++++++- packages/platform-harmonyos/tsconfig.json | 1 - packages/platform-vega/src/index.test.ts | 8 +- .../src/index-startup-cleanup.test.ts | 3 +- packages/plugins/src/platform.test.ts | 1 + packages/plugins/src/platform.ts | 6 + packages/plugins/src/validate.ts | 1 - pnpm-lock.yaml | 6 +- .../layering/platform-package-policy.test.ts | 44 +++ scripts/layering/platform-package-policy.ts | 61 ++++ src/commands/schema/cli-help.ts | 2 +- src/platform-runtime-host.ts | 8 +- src/platform-runtime-operation-host.ts | 4 +- src/platform-runtime-toolchain-host.test.ts | 37 +-- src/platform-runtime-toolchain-host.ts | 18 +- src/platform-runtime.ts | 3 +- src/platform-runtime/plugin-host.test.ts | 23 ++ src/platform-runtime/plugin-host.ts | 4 + 74 files changed, 2340 insertions(+), 1332 deletions(-) create mode 100644 docs/evidence/harmonyos-managed-platform-2026-11-20.md create mode 100644 packages/build-config/src/index.test.ts delete mode 100644 packages/platform-harmonyos/src/__tests__/hdc-shell.test.ts delete mode 100644 packages/platform-harmonyos/src/__tests__/tmp-dir.ts create mode 100644 packages/platform-harmonyos/src/command-host.ts create mode 100644 packages/platform-harmonyos/src/recording/recorder.test.ts create mode 100644 packages/platform-harmonyos/src/toolbox.fixtures.ts create mode 100644 packages/platform-harmonyos/src/toolbox.ts create mode 100644 src/platform-runtime/plugin-host.test.ts diff --git a/docs/evidence/harmonyos-managed-platform-2026-11-20.md b/docs/evidence/harmonyos-managed-platform-2026-11-20.md new file mode 100644 index 0000000000..a22b532a21 --- /dev/null +++ b/docs/evidence/harmonyos-managed-platform-2026-11-20.md @@ -0,0 +1,126 @@ +# HarmonyOS managed platform plugin — packed-plugin evidence (2026-11-20) + +Head: `refactor/0.22-harmonyos-platform-plugin`. Issue #4317, PR #4857. + +## Live HarmonyOS target: not available on this host + +The host has the toolchain but no target, so no real device or emulator was driven for this change. + +| Check | Result | +| --- | --- | +| `hdc` present | Yes — `/Applications/DevEco-Studio.app/Contents/sdk/default/openharmony/toolchains/hdc` (with `DEVECO_SDK_HOME=/Applications/DevEco-Studio.app/Contents/sdk`) | +| `hdc list targets` | `[Empty]` (re-checked after the first run) | +| Startable emulator image | None. `/Applications/DevEco-Studio.app/Contents/tools/emulator` carries the emulator binary, and there is no image directory (`~/.Huawei` and `~/Library/Huawei` do not exist; the only Huawei support directory is `Library/Application Support/Huawei/DevEcoStudio5.1`, which holds IDE settings). Downloading an image needs the IDE's signed-in account and its license acceptance, which is not something this run can do unattended. | + +No live-device claim is made anywhere in this PR. The device-facing behavior is covered by the packed +fixture below plus the plugin's unit coverage of every HDC argv. + +## Packed plugin, one stub HDC, reachable only through `HDC_SDK_PATH` + +The same sequence now runs as a gate: `packages/platform-harmonyos/test/package-smoke.mjs`. What +follows is a manual run of it against this host, kept because it shows the raw replies and the exec +trace the plugin's commands land in. + +Setup: a scratch project, an isolated store (`AGENT_DEVICE_HOME`, `AGENT_DEVICE_STATE_DIR`, +`AGENT_DEVICE_CLAIMS_DIR` under scratch), `PATH` reduced to the Node directory, `/usr/bin` and +`/bin`, and the three documented toolchain roots unset except `HDC_SDK_PATH`. The stub `hdc` is +written into that root only, so any call that reaches it came from the plugin's own root probing and +not from a host `PATH` lookup. The core was packed and installed, then +`agent-device plugins add ./harmonyos.tgz`. + +``` +########## agent-device devices --platform harmonyos --json +{ + "success": true, + "data": { + "devices": [ + { "platform": "harmonyos", "id": "127.0.0.1:5555", "name": "StubPhone", + "kind": "device", "target": "mobile", "booted": true } + ] + } +} + +########## agent-device open com.example.app --platform harmonyos --json +{ + "success": true, + "data": { + "session": "default", + "appName": "com.example.app", + "appBundleId": "com.example.app", + "selection": { "reason": "single-booted-local", "source": "local", "candidateCount": 1 }, + "platform": "harmonyos", + "target": "mobile", + "device": "StubPhone", + "id": "127.0.0.1:5555", + "message": "Opened: com.example.app" + } +} + +########## agent-device snapshot -i --platform harmonyos --json +{ + "success": true, + "data": { + "nodes": [ + { "index": 0, "type": "Button", "value": "Continue", + "rect": { "x": 84, "y": 1127, "width": 1088, "height": 168 }, + "enabled": true, "visibleToUser": true, "hittable": true, "depth": 1, + "ref": "e1", "kind": "button" } + ], + "visibility": { "partial": false, "visibleNodeCount": 1, "totalNodeCount": 1 }, + "keyboard": { "kind": "unmeasurable", "reason": "keyboard-window-not-listed" }, + "snapshotDiagnostics": { + "stats": { "count": 1, "platform": "harmonyos", "backends": { "harmonyos-uitest": 1 } } + } + } +} + +########## agent-device press 100 200 --platform harmonyos --json +{ "success": true, "data": { "x": 100, "y": 200, "message": "Tapped (100, 200)", "targetKind": "point" } } + +########## agent-device screenshot /tmp/hdckit/shot.png --platform harmonyos --json +{ "success": true, "data": { "path": "/tmp/hdckit/shot.png" } } + +########## agent-device close --platform harmonyos --json +{ "success": true, "data": { "session": "default", "message": "Closed: default" } } +``` + +Every HDC call the packed bundle made, with the `PATH` it was handed (the stub's own record): + +``` +ARGS: list targets +ARGS: -t 127.0.0.1:5555 shell param get const.product.name +ARGS: -t 127.0.0.1:5555 shell param get const.build.characteristics +ARGS: -t 127.0.0.1:5555 shell bm dump -n com.example.app +ARGS: -t 127.0.0.1:5555 shell aa start -a EntryAbility -b com.example.app -m entry +ARGS: -t 127.0.0.1:5555 shell uitest dumpLayout -p /data/local/tmp/agent-device-layout-….json +ARGS: -t 127.0.0.1:5555 file recv /data/local/tmp/agent-device-layout-….json …/layout.json +ARGS: -t 127.0.0.1:5555 shell rm -f /data/local/tmp/agent-device-layout-….json +ARGS: -t 127.0.0.1:5555 shell hidumper -s WindowManagerService -a -a +ARGS: -t 127.0.0.1:5555 shell uitest uiInput click 100 200 +ARGS: -t 127.0.0.1:5555 shell snapshot_display -f /data/local/tmp/agent-device-screen-….jpeg +ARGS: -t 127.0.0.1:5555 file recv /data/local/tmp/agent-device-screen-….jpeg /tmp/hdckit/shot.png +ARGS: -t 127.0.0.1:5555 shell rm -f /data/local/tmp/agent-device-screen-….jpeg +``` + +Each line's recorded `PATH` was `/tmp/hdckit:` followed by the host `PATH`: the plugin prepends the +root it resolved, so the calls reached the stub while the core named no HarmonyOS configuration. + +The same request under `--debug` shows the spawns in the request's own exec trace, which is what +binding to the setup host buys — a plugin that spawned through its bundled host-kit copy would trace +nothing here: + +``` +{"phase":"exec_command","requestId":"6a550a1ab3605fb3","command":"press","data":{"execId":"cc614109-…","command":"hdc","event":"spawn","pid":49635,"timeoutMs":15000}} +{"phase":"exec_command","requestId":"6a550a1ab3605fb3","command":"press","data":{"execId":"cc614109-…","command":"hdc","event":"exit","pid":49635,"exitCode":0,"signal":null}} +{"phase":"request_success","requestId":"6a550a1ab3605fb3","command":"press"} +``` + +## What this proves and what it does not + +Proves: the packed plugin resolves HDC from `HDC_SDK_PATH` through the host it was set up with, runs +discovery, launch, snapshot, interaction, capture and close on that route, and its commands are +traceable to the request that asked for them. + +Does not prove anything about a real HarmonyOS device: no target exists on this host, so device-side +behavior (real layout shape, real `aa start` output, real capture encoding, keyboard measurement) is +unchanged from before this refactor and unverified by it. diff --git a/packages/build-config/package.json b/packages/build-config/package.json index 5cae8eb212..805d334732 100644 --- a/packages/build-config/package.json +++ b/packages/build-config/package.json @@ -11,6 +11,7 @@ } }, "devDependencies": { + "@agent-device/test-kit": "workspace:*", "rolldown": "1.2.5" } } diff --git a/packages/build-config/src/index.test.ts b/packages/build-config/src/index.test.ts new file mode 100644 index 0000000000..422d769987 --- /dev/null +++ b/packages/build-config/src/index.test.ts @@ -0,0 +1,120 @@ +import { strict as assert } from 'node:assert'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test } from 'vitest'; +import { assertManagedPlatformPluginFactory } from './index.ts'; + +const HARMONYOS_CLAIM = { apiVersion: 3, platform: 'harmonyos' }; + +/** Writes a `package.json` holding one managed platform claim and returns its URL, as a build calls it. */ +function claimManifestUrl(claim: { apiVersion: unknown; platform?: unknown }): URL { + const directory = mkdtempForTestSync('build-config-claim-'); + const file = path.join(directory, 'package.json'); + fs.writeFileSync(file, JSON.stringify({ name: '@agent-device/example', 'agent-device': claim })); + return pathToFileURL(file); +} + +/** One factory shaped like a managed platform plugin's default export, with the pair a case names. */ +function factoryContribution( + apiVersion: unknown, + contributes: readonly { kind: unknown; family: unknown }[], +) { + return () => ({ apiVersion, contributes }); +} + +const validFactory = factoryContribution(3, [{ kind: 'platform', family: 'harmonyos' }]); + +test('accepts a factory whose pair matches the package claim', () => { + assert.doesNotThrow(() => + assertManagedPlatformPluginFactory( + claimManifestUrl(HARMONYOS_CLAIM), + validFactory, + 'HarmonyOS', + ), + ); +}); + +test('rejects a factory on an api version the package does not claim', () => { + assert.throws( + () => + assertManagedPlatformPluginFactory( + claimManifestUrl(HARMONYOS_CLAIM), + factoryContribution(2, [{ kind: 'platform', family: 'harmonyos' }]), + 'HarmonyOS', + ), + /managed HarmonyOS factory must match its package claim/, + ); +}); + +test('rejects a factory contributing the wrong kind', () => { + assert.throws( + () => + assertManagedPlatformPluginFactory( + claimManifestUrl(HARMONYOS_CLAIM), + factoryContribution(3, [{ kind: 'provider', family: 'harmonyos' }]), + 'HarmonyOS', + ), + /managed HarmonyOS factory must match its package claim/, + ); +}); + +test('rejects a factory contributing a family the package does not claim', () => { + assert.throws( + () => + assertManagedPlatformPluginFactory( + claimManifestUrl(HARMONYOS_CLAIM), + factoryContribution(3, [{ kind: 'platform', family: 'vega' }]), + 'HarmonyOS', + ), + /managed HarmonyOS factory must match its package claim/, + ); +}); + +for (const [name, contributes] of [ + ['no contribution', []], + [ + 'two contributions', + [ + { kind: 'platform', family: 'harmonyos' }, + { kind: 'platform', family: 'vega' }, + ], + ], +] as const) { + test(`rejects a factory contributing ${name}`, () => { + assert.throws( + () => + assertManagedPlatformPluginFactory( + claimManifestUrl(HARMONYOS_CLAIM), + factoryContribution(3, contributes), + 'HarmonyOS', + ), + /managed HarmonyOS factory must match its package claim/, + ); + }); +} + +test('rejects a manifest that carries no platform claim', () => { + assert.throws( + () => + assertManagedPlatformPluginFactory( + claimManifestUrl({ apiVersion: 3 }), + validFactory, + 'HarmonyOS', + ), + /managed HarmonyOS factory must match its package claim/, + ); +}); + +test('rejects a location the bundler cannot read', () => { + // The guard reads the manifest off the filesystem, so a non-file URL fails the read rather than + // passing an unchecked factory. + assert.throws(() => + assertManagedPlatformPluginFactory( + new URL('https://example.test/package.json'), + validFactory, + 'HarmonyOS', + ), + ); +}); diff --git a/packages/build-config/tsconfig.json b/packages/build-config/tsconfig.json index 77de1f500d..f6986f18b7 100644 --- a/packages/build-config/tsconfig.json +++ b/packages/build-config/tsconfig.json @@ -10,5 +10,5 @@ "tsBuildInfoFile": "./dist-types/index.tsbuildinfo" }, "include": ["src"], - "references": [] + "references": [{ "path": "../test-kit" }] } diff --git a/packages/capture-kit/src/index.ts b/packages/capture-kit/src/index.ts index 439c56853f..afc77befd0 100644 --- a/packages/capture-kit/src/index.ts +++ b/packages/capture-kit/src/index.ts @@ -13,7 +13,6 @@ export { decodeDurableDescriptor } from './durable-descriptor-codec.ts'; export { createRetryableCleanup } from '@agent-device/contracts/durable-resource'; export { createScreenRecordingLiveHandle } from './screen-recording-live-handle.ts'; export { createScreenRecordingCompletion } from './screen-recording-completion.ts'; -export { createTransportRecordingSnapshot } from './screen-recording-transport.ts'; export { assertScreenRecordingOptionsSupported } from './screen-recording-options.ts'; export { cleanupManagedAppLogProcess, diff --git a/packages/command-surface/src/management/device.ts b/packages/command-surface/src/management/device.ts index 7eb3bb9b53..c3044d0009 100644 --- a/packages/command-surface/src/management/device.ts +++ b/packages/command-surface/src/management/device.ts @@ -142,6 +142,10 @@ const devicesCommandFacet = defineCommandFacet({ text: { summary: 'List available devices and simulators', searchHint: 'emulators udid serial', + // HarmonyOS is the optional family a terminal user is most likely to name here without it, so + // the install command is answered where the list is asked for, not on the compact card. + cliDetail: + 'An absent optional platform answers details.reason plugin-not-installed with its install command; HarmonyOS needs agent-device plugins add @agent-device/harmonyos.', }, metadata: devicesCommandMetadata, run: (client, input) => client.devices.list(input), diff --git a/packages/contracts/src/platform-module.ts b/packages/contracts/src/platform-module.ts index 0d1d4cd6ab..4afc7dc250 100644 --- a/packages/contracts/src/platform-module.ts +++ b/packages/contracts/src/platform-module.ts @@ -186,11 +186,15 @@ export type AppDeviceResolver = ( ) => Promise; /** A family module gains this interface only with an honest package-owned source. */ -/** A family module receives only the host authority its inventory mechanics need. */ +/** + * A family module receives only the host authority its inventory mechanics need. A family whose + * authority is `never` owns its host — a plugin that runs its own tools through the host it was set + * up with — and so loads with nothing from the core. + */ export type InventoryPlatformModule = Family extends Platform ? PlatformModuleMetadata & Readonly< - Family extends 'web' + [DeviceInventoryHostFor] extends [never] ? { family: Family; loadInventory(): Promise; diff --git a/packages/contracts/src/platform-plugin.ts b/packages/contracts/src/platform-plugin.ts index e6f0aaa55f..7d21306cdc 100644 --- a/packages/contracts/src/platform-plugin.ts +++ b/packages/contracts/src/platform-plugin.ts @@ -7,7 +7,7 @@ import type { WebProvider } from './web-provider.ts'; import type { VegaToolProvider } from './vega-tool-provider.ts'; import type { AppError } from '@agent-device/kernel/errors'; import type { DeviceInfo, Platform, PlatformSelector } from '@agent-device/kernel/device'; -import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { PlatformGatedProviderResolverKey } from './platform-providers.ts'; import type { Interactor, RunnerContext } from './interactor-types.ts'; @@ -114,19 +114,13 @@ export type VegaPlatformSelection = Readonly<{ }>; /** - * What the core asks of the HarmonyOS plugin. The toolchain probe answers `doctor --platform - * harmonyos`; the toolchain preparation runs the plugin's own device discovery and log streaming, - * which need the host's documented SDK roots. Every other HarmonyOS operation — HDC discovery, - * probing, interaction, capture, recording, performance — the package owns. + * What the core asks of the HarmonyOS plugin: the toolchain probe that answers `doctor --platform + * harmonyos`. Every other HarmonyOS operation — HDC discovery, probing, interaction, capture, + * recording, performance, and the plugin's own toolchain `PATH` — the package owns, because it runs + * them through the host it was set up with. */ export type HarmonyPlatformOperations = Readonly<{ toolchainCheck(): Promise; - /** - * Prepends the HarmonyOS toolchain roots that hold an `hdc` binary to `env`'s PATH, so a spawn - * sees the same HDC an interactive shell does. The core hands over the host environment it - * captured: the plugin must not read `process.env` itself (ADR 0019). - */ - prepareToolchain(env: EnvMap): Promise; }>; export type HarmonyPlatformRegistration = Readonly<{ diff --git a/packages/contracts/src/platform-runtime-host.ts b/packages/contracts/src/platform-runtime-host.ts index 64e6932d77..1a2d51b01e 100644 --- a/packages/contracts/src/platform-runtime-host.ts +++ b/packages/contracts/src/platform-runtime-host.ts @@ -177,7 +177,8 @@ export type DeviceInventoryHost = Readonly<{ export type DeviceInventoryHostByFamily = Readonly<{ apple: Pick; android: Pick; - harmonyos: Pick; + /** The HarmonyOS plugin carries its own host, so its inventory asks the core for nothing. */ + harmonyos: never; vega: Pick; linux: Pick; web: never; diff --git a/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts b/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts index be622bd417..830919f43c 100644 --- a/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts +++ b/packages/device-selection/src/__tests__/composed-inventory-gateways.test.ts @@ -243,7 +243,11 @@ describe('composed device inventory gateway', () => { const devices = await gateways.localOnly.discover({}, scope); expect(devices.map(({ platform }) => platform)).toEqual(['android', 'apple', 'vega', 'linux']); - expect(local.sourceLoads()).toEqual(['android', 'harmonyos', 'apple', 'vega', 'linux']); + // Every local family's source is loaded exactly once. The failed family is loaded too, and its + // failure is what makes it contribute no devices. + expect(sortedFamilies(local.sourceLoads())).toEqual( + sortedFamilies(['android', 'harmonyos', 'apple', 'vega', 'linux']), + ); }); test('an absent optional family is skipped by unfiltered discovery and refused with plugin-not-installed on explicit request', async () => { @@ -274,7 +278,9 @@ describe('composed device inventory gateway', () => { 'apple', 'linux', ]); - expect(loaded).toEqual(['android', 'harmonyos', 'apple', 'linux']); + expect(sortedFamilies(loaded)).toEqual( + sortedFamilies(['android', 'harmonyos', 'apple', 'linux']), + ); // An explicit request for the absent family fails with the typed plugin-not-installed // outcome and its install hint, before any source load or device binding. @@ -351,6 +357,15 @@ describe('composed device inventory gateway', () => { }); }); +/** + * The families whose sources were loaded, sorted. Unfiltered discovery loads the sources + * concurrently, and the HarmonyOS plugin needs no core inventory host, so which source resolves + * first is a scheduling fact rather than a contract. The contract is that each loads exactly once. + */ +function sortedFamilies(families: readonly Platform[]): string[] { + return [...families].sort(); +} + function inventoryWorld( overrides: Partial Promise>> = {}, ) { diff --git a/packages/device-selection/src/composed-inventory-gateways.ts b/packages/device-selection/src/composed-inventory-gateways.ts index 8f3df1a618..156e05bed2 100644 --- a/packages/device-selection/src/composed-inventory-gateways.ts +++ b/packages/device-selection/src/composed-inventory-gateways.ts @@ -156,7 +156,8 @@ async function loadFamilyInventory( case 'android': return await module.loadInventory(androidInventoryHost(await requiredHost())); case 'harmonyos': - return await module.loadInventory(harmonyInventoryHost(await requiredHost())); + // The HarmonyOS plugin holds the host it was set up with, so it loads with nothing. + return await module.loadInventory(); case 'vega': return await module.loadInventory(vegaInventoryHost(await requiredHost())); case 'linux': @@ -185,14 +186,6 @@ function androidInventoryHost(host: DeviceInventoryHost): DeviceInventoryHostFor }); } -function harmonyInventoryHost(host: DeviceInventoryHost): DeviceInventoryHostFor<'harmonyos'> { - return Object.freeze({ - commands: host.commands, - files: host.files, - toolchains: host.toolchains, - }); -} - function vegaInventoryHost(host: DeviceInventoryHost): DeviceInventoryHostFor<'vega'> { return Object.freeze({ commands: host.commands, diff --git a/packages/platform-harmonyos/package.json b/packages/platform-harmonyos/package.json index 3f8fda37bc..7eb8b3bd1f 100644 --- a/packages/platform-harmonyos/package.json +++ b/packages/platform-harmonyos/package.json @@ -16,7 +16,6 @@ "@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:*" }, diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 7a39db79d9..d6e05df819 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -1,11 +1,7 @@ import assert from 'node:assert/strict'; import { AppError } from '@agent-device/kernel/errors'; import { afterEach, beforeEach, test, vi } from 'vitest'; - -vi.mock('@agent-device/host-kit/command', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, runCmd: vi.fn() }; -}); +import { createHarmonyHdcRunnerStub, createHarmonyHostStub } from '../toolbox.fixtures.ts'; const { invalidateHarmonyGestureViewport } = vi.hoisted(() => ({ invalidateHarmonyGestureViewport: vi.fn(), @@ -25,9 +21,6 @@ import { parseHarmonyLaunchTarget, resolveHarmonyArchiveBundleName, } from '../app-lifecycle.ts'; -import { runCmd } from '@agent-device/host-kit/command'; - -const mockRunCmd = vi.mocked(runCmd); const DEVICE = { platform: 'harmonyos' as const, @@ -40,7 +33,6 @@ const DEVICE = { beforeEach(() => { vi.useRealTimers(); - mockRunCmd.mockReset(); invalidateHarmonyGestureViewport.mockReset(); }); @@ -79,90 +71,73 @@ test('parseHarmonyIsSystemApp reads Bundle Manager application metadata', () => assert.equal(parseHarmonyIsSystemApp('bundle metadata unavailable'), undefined); }); -test('resolveHarmonyArchiveBundleName reads module metadata through unzip', async () => { - mockRunCmd.mockResolvedValue({ - exitCode: 0, +test('resolveHarmonyArchiveBundleName reads module metadata through unzip on the host', async () => { + const stub = createHarmonyHostStub(); + stub.answer({ stdout: JSON.stringify({ app: { bundleName: 'com.example.application' } }), - stderr: '', - } as Awaited>); + }); - await assert.doesNotReject(async () => { - assert.equal( - await resolveHarmonyArchiveBundleName('/tmp/example.hap'), - 'com.example.application', - ); + assert.equal( + await resolveHarmonyArchiveBundleName(stub.toolbox.commands, '/tmp/example.hap'), + 'com.example.application', + ); + assert.deepEqual(stub.commands[0], { + executable: 'unzip', + args: ['-p', '/tmp/example.hap', 'module.json'], + env: { PATH: '/usr/bin' }, + timeoutMs: 15_000, + allowFailure: true, + signal: undefined, }); - assert.deepEqual(mockRunCmd.mock.calls[0]?.slice(0, 2), [ - 'unzip', - ['-p', '/tmp/example.hap', 'module.json'], - ]); }); test('resolveHarmonyArchiveBundleName forwards the binding signal to in-flight unzip', async () => { const controller = new AbortController(); - const abortReason = new Error('request cancelled during Harmony archive resolution'); - mockRunCmd.mockImplementationOnce(async (_command, _args, options) => { - assert.equal(options?.signal, controller.signal); - return await rejectWhenAborted(options?.signal); - }); + const stub = createHarmonyHostStub(); - const pending = resolveHarmonyArchiveBundleName('/tmp/example.hap', controller.signal); - controller.abort(abortReason); + const pending = resolveHarmonyArchiveBundleName( + stub.toolbox.commands, + '/tmp/example.hap', + controller.signal, + ); + await pending; - await assert.rejects(pending, (error: unknown) => error === abortReason); + assert.equal(stub.commands[0]?.signal, controller.signal); }); -async function rejectWhenAborted(signal: AbortSignal | undefined): Promise { - return await new Promise((_resolve, reject) => { - if (!signal) { - reject(new Error('archive resolver did not receive the binding signal')); - return; - } - if (signal.aborted) { - reject(signal.reason); - return; - } - signal.addEventListener('abort', () => reject(signal.reason), { once: true }); - }); -} - test('HarmonyOS lifecycle commands use HDC bundle and ability primitives', async () => { - mockRunCmd - .mockResolvedValueOnce({ exitCode: 0, stdout: 'com.example.application\n', stderr: '' }) - .mockResolvedValueOnce({ exitCode: 0, stdout: 'start ability successfully', stderr: '' }) - .mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' }); + const hdc = createHarmonyHdcRunnerStub([ + { stdout: 'com.example.application\n' }, + { stdout: 'start ability successfully' }, + { stdout: '' }, + ]); - assert.deepEqual(await listHarmonyApps(DEVICE, 'all'), [ + assert.deepEqual(await listHarmonyApps(hdc, DEVICE, 'all'), [ { package: 'com.example.application', name: 'application' }, ]); - await openHarmonyApp(DEVICE, 'com.example.application', { activity: 'EntryAbility' }); - await closeHarmonyApp(DEVICE, 'com.example.application'); + await openHarmonyApp(hdc, DEVICE, 'com.example.application', { activity: 'EntryAbility' }); + await closeHarmonyApp(hdc, DEVICE, 'com.example.application'); assert.deepEqual( - mockRunCmd.mock.calls.map(([, args]) => args), + hdc.calls.map((call) => [call.kind, call.target, call.args]), [ - ['-t', 'harmony-1', 'shell', 'bm', 'dump', '-a'], + ['runShell', 'harmony-1', ['bm', 'dump', '-a']], [ - '-t', + 'runShell', 'harmony-1', - 'shell', - 'aa', - 'start', - '-a', - 'EntryAbility', - '-b', - 'com.example.application', + ['aa', 'start', '-a', 'EntryAbility', '-b', 'com.example.application'], ], - ['-t', 'harmony-1', 'shell', 'aa', 'force-stop', 'com.example.application'], + ['runShell', 'harmony-1', ['aa', 'force-stop', 'com.example.application']], ], ); assert.deepEqual(invalidateHarmonyGestureViewport.mock.calls, [[DEVICE], [DEVICE]]); }); test('openHarmonyApp refuses an ability name outside the module grammar before any hdc call', async () => { + const hdc = createHarmonyHdcRunnerStub(); for (const activity of ['Entry$(id)', 'Entry;reboot', 'Entry Ability', '1Entry', 'Entry"x', '']) { await assert.rejects( - () => openHarmonyApp(DEVICE, 'com.example.application', { activity }), + () => openHarmonyApp(hdc, DEVICE, 'com.example.application', { activity }), (error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS' && @@ -170,72 +145,52 @@ test('openHarmonyApp refuses an ability name outside the module grammar before a error.details?.ability === activity, ); } - assert.equal(mockRunCmd.mock.calls.length, 0); + assert.equal(hdc.calls.length, 0); }); test('HarmonyOS app listing filters user-installed bundles through Bundle Manager metadata', async () => { - mockRunCmd - .mockResolvedValueOnce({ - exitCode: 0, - stdout: 'com.example.application\ncom.ohos.settings\n', - stderr: '', - }) - .mockResolvedValueOnce({ - exitCode: 0, - stdout: JSON.stringify({ applicationInfo: { isSystemApp: false } }), - stderr: '', - }) - .mockResolvedValueOnce({ - exitCode: 0, - stdout: JSON.stringify({ applicationInfo: { isSystemApp: true } }), - stderr: '', - }); + const hdc = createHarmonyHdcRunnerStub([ + { stdout: 'com.example.application\ncom.ohos.settings\n' }, + { stdout: JSON.stringify({ applicationInfo: { isSystemApp: false } }) }, + { stdout: JSON.stringify({ applicationInfo: { isSystemApp: true } }) }, + ]); - assert.deepEqual(await listHarmonyApps(DEVICE, 'user-installed'), [ + assert.deepEqual(await listHarmonyApps(hdc, DEVICE, 'user-installed'), [ { package: 'com.example.application', name: 'application' }, ]); assert.deepEqual( - mockRunCmd.mock.calls.map(([, args]) => args), + hdc.calls.map((call) => call.args), [ - ['-t', 'harmony-1', 'shell', 'bm', 'dump', '-a'], - ['-t', 'harmony-1', 'shell', 'bm', 'dump', '-n', 'com.example.application'], - ['-t', 'harmony-1', 'shell', 'bm', 'dump', '-n', 'com.ohos.settings'], + ['bm', 'dump', '-a'], + ['bm', 'dump', '-n', 'com.example.application'], + ['bm', 'dump', '-n', 'com.ohos.settings'], ], ); }); test('HarmonyOS app listing preserves the complete inventory for the all filter', async () => { - mockRunCmd.mockResolvedValueOnce({ - exitCode: 0, - stdout: 'com.example.application\ncom.ohos.settings\n', - stderr: '', - }); + const hdc = createHarmonyHdcRunnerStub([ + { stdout: 'com.example.application\ncom.ohos.settings\n' }, + ]); - assert.deepEqual(await listHarmonyApps(DEVICE, 'all'), [ + assert.deepEqual(await listHarmonyApps(hdc, DEVICE, 'all'), [ { package: 'com.example.application', name: 'application' }, { package: 'com.ohos.settings', name: 'settings' }, ]); assert.deepEqual( - mockRunCmd.mock.calls.map(([, args]) => args), - [['-t', 'harmony-1', 'shell', 'bm', 'dump', '-a']], + hdc.calls.map((call) => call.args), + [['bm', 'dump', '-a']], ); }); test('HarmonyOS user-installed app listing rejects bundles without a system-app classification', async () => { - mockRunCmd - .mockResolvedValueOnce({ - exitCode: 0, - stdout: 'com.example.application\n', - stderr: '', - }) - .mockResolvedValueOnce({ - exitCode: 0, - stdout: JSON.stringify({ applicationInfo: {} }), - stderr: '', - }); + const hdc = createHarmonyHdcRunnerStub([ + { stdout: 'com.example.application\n' }, + { stdout: JSON.stringify({ applicationInfo: {} }) }, + ]); await assert.rejects( - () => listHarmonyApps(DEVICE, 'user-installed'), + () => listHarmonyApps(hdc, DEVICE, 'user-installed'), (error: unknown) => { assert(error instanceof AppError); assert.equal(error.code, 'COMMAND_FAILED'); @@ -247,34 +202,30 @@ test('HarmonyOS user-installed app listing rejects bundles without a system-app test('HarmonyOS user-installed app listing bounds metadata work and cancels queued work on failure', async () => { const packages = Array.from({ length: 6 }, (_, index) => `com.example.app${index + 1}`); + const hdc = createHarmonyHdcRunnerStub(); + const metadataSignals: AbortSignal[] = []; let metadataCalls = 0; - const abortedSignals: AbortSignal[] = []; - mockRunCmd.mockImplementation(async (_command, args, options) => { - if (args.at(-1) === '-a') { - return { exitCode: 0, stdout: `${packages.join('\n')}\n`, stderr: '' } as Awaited< - ReturnType - >; + hdc.runShell = async (_device, words, options) => { + if (words.at(-1) === '-a') { + return { stdout: `${packages.join('\n')}\n`, stderr: '', exitCode: 0 }; } - metadataCalls++; - if (args.at(-1) === 'com.example.app4') { - return { - exitCode: 0, - stdout: JSON.stringify({ applicationInfo: {} }), - stderr: '', - } as Awaited>; + metadataCalls += 1; + const bundle = words.at(-1); + if (bundle === 'com.example.app4') { + return { stdout: JSON.stringify({ applicationInfo: {} }), stderr: '', exitCode: 0 }; } const signal = options?.signal; assert(signal); - abortedSignals.push(signal); - return await new Promise>>((_, reject) => { + metadataSignals.push(signal); + return await new Promise((_, reject) => { signal.addEventListener('abort', () => reject(new Error('metadata request aborted')), { once: true, }); }); - }); + }; await assert.rejects( - () => listHarmonyApps(DEVICE, 'user-installed'), + () => listHarmonyApps(hdc, DEVICE, 'user-installed'), (error: unknown) => { assert(error instanceof AppError); assert.match( @@ -287,33 +238,39 @@ test('HarmonyOS user-installed app listing bounds metadata work and cancels queu ); assert.equal(metadataCalls, 4); - assert.equal(abortedSignals.length, 3); - assert(abortedSignals.every((signal) => signal.aborted)); + assert.equal(metadataSignals.length, 3); + assert(metadataSignals.every((signal) => signal.aborted)); }); test('HarmonyOS user-installed app listing aborts all metadata reads at its aggregate deadline', async () => { vi.useFakeTimers(); const packages = Array.from({ length: 6 }, (_, index) => `com.example.app${index + 1}`); - let metadataCalls = 0; + const hdc = createHarmonyHdcRunnerStub(); const metadataSignals: AbortSignal[] = []; - mockRunCmd.mockImplementation(async (_command, args, options) => { - if (args.at(-1) === '-a') { - return { exitCode: 0, stdout: `${packages.join('\n')}\n`, stderr: '' } as Awaited< - ReturnType - >; - } - metadataCalls++; + let metadataCalls = 0; + hdc.runShell = async (_device, _words, options) => { + metadataCalls += 1; const signal = options?.signal; assert(signal); metadataSignals.push(signal); - return await new Promise>>((_, reject) => { + return await new Promise((_, reject) => { signal.addEventListener('abort', () => reject(new Error('metadata request aborted')), { once: true, }); }); - }); + }; + // The bundle list itself is the first shell read; answer it and let the metadata reads hang. + const originalRunShell = hdc.runShell; + let first = true; + hdc.runShell = async (device, words, options) => { + if (first && words.at(-1) === '-a') { + first = false; + return { stdout: `${packages.join('\n')}\n`, stderr: '', exitCode: 0 }; + } + return await originalRunShell(device, words, options); + }; - const listing = listHarmonyApps(DEVICE, 'user-installed'); + const listing = listHarmonyApps(hdc, DEVICE, 'user-installed'); const listingError = listing.catch((error: unknown) => error); await vi.advanceTimersByTimeAsync(0); assert.equal(metadataCalls, 4); @@ -329,21 +286,17 @@ test('HarmonyOS user-installed app listing aborts all metadata reads at its aggr }); test('HarmonyOS launch resolves module metadata and reports missing launch data', async () => { - mockRunCmd - .mockResolvedValueOnce({ - exitCode: 0, + const hdc = createHarmonyHdcRunnerStub([ + { stdout: JSON.stringify({ hapModuleInfos: [{ mainElementName: 'EntryAbility', moduleName: 'entry' }], }), - stderr: '', - }) - .mockResolvedValueOnce({ exitCode: 0, stdout: 'start ability successfully', stderr: '' }); - - await openHarmonyApp(DEVICE, 'com.example.application'); - assert.deepEqual(mockRunCmd.mock.calls[1]?.[1], [ - '-t', - 'harmony-1', - 'shell', + }, + { stdout: 'start ability successfully' }, + ]); + + await openHarmonyApp(hdc, DEVICE, 'com.example.application'); + assert.deepEqual(hdc.calls[1]?.args, [ 'aa', 'start', '-a', @@ -354,6 +307,9 @@ test('HarmonyOS launch resolves module metadata and reports missing launch data' 'entry', ]); - mockRunCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'not installed', stderr: '' }); - await assert.rejects(() => openHarmonyApp(DEVICE, 'com.example.missing'), /launchable ability/); + hdc.answer({ stdout: 'not installed' }); + await assert.rejects( + () => openHarmonyApp(hdc, DEVICE, 'com.example.missing'), + /launchable ability/, + ); }); diff --git a/packages/platform-harmonyos/src/__tests__/doctor.test.ts b/packages/platform-harmonyos/src/__tests__/doctor.test.ts index 132c5aa575..4068c12492 100644 --- a/packages/platform-harmonyos/src/__tests__/doctor.test.ts +++ b/packages/platform-harmonyos/src/__tests__/doctor.test.ts @@ -1,24 +1,15 @@ import assert from 'node:assert/strict'; -import { beforeEach, test, vi } from 'vitest'; +import { test } from 'vitest'; import type { DoctorCheck } from '@agent-device/contracts/observability'; - -vi.mock('@agent-device/host-kit/command', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, runCmd: vi.fn() }; -}); - -import { runCmd } from '@agent-device/host-kit/command'; +import path from 'node:path'; +import { createHarmonyHostStub, createHarmonyToolchainRoot } from '../toolbox.fixtures.ts'; import { harmonyToolchainCheck } from '../doctor.ts'; -const mockRunCmd = vi.mocked(runCmd); - -beforeEach(() => { - mockRunCmd.mockReset(); -}); - test('HarmonyOS doctor reports the HDC version', async () => { - mockRunCmd.mockResolvedValue({ exitCode: 0, stdout: 'HDC 3.2.0d\n', stderr: '' } as never); - const check: DoctorCheck = await harmonyToolchainCheck(); + const stub = createHarmonyHostStub(); + stub.answer({ stdout: 'HDC 3.2.0d\n' }); + + const check: DoctorCheck = await harmonyToolchainCheck(stub.toolbox.commands); assert.deepEqual(check, { id: 'toolchain', @@ -26,5 +17,36 @@ test('HarmonyOS doctor reports the HDC version', async () => { summary: 'HarmonyOS toolchain: HDC 3.2.0d.', evidence: { hdcVersion: 'HDC 3.2.0d' }, }); - assert.deepEqual(mockRunCmd.mock.calls[0]?.slice(0, 2), ['hdc', ['-v']]); + assert.deepEqual(stub.commands[0], { + executable: 'hdc', + args: ['-v'], + env: { PATH: '/usr/bin' }, + timeoutMs: 3_000, + allowFailure: true, + signal: undefined, + }); +}); + +test('HarmonyOS doctor probes the HDC a configured root carries', async () => { + const root = createHarmonyToolchainRoot(); + const stub = createHarmonyHostStub({ env: { HDC_SDK_PATH: root, PATH: '/usr/bin' } }); + stub.answer({ stdout: 'HDC 3.2.0d\n' }); + + const check = await harmonyToolchainCheck(stub.toolbox.commands); + + // A root outside the host PATH still answers its own version, because the probe names it. + assert.equal(stub.commands[0]?.executable, path.join(root, 'hdc')); + assert.equal(check.status, 'pass'); +}); + +test('HarmonyOS doctor reports an unusable toolchain as info with the install hint', async () => { + const stub = createHarmonyHostStub(); + + const check = await harmonyToolchainCheck(stub.toolbox.commands); + + assert.equal(check.status, 'info'); + assert.equal( + check.hint, + 'Install HarmonyOS Command Line Tools, then add sdk/default/openharmony/toolchains to PATH or set HDC_SDK_PATH.', + ); }); diff --git a/packages/platform-harmonyos/src/__tests__/hdc-shell.test.ts b/packages/platform-harmonyos/src/__tests__/hdc-shell.test.ts deleted file mode 100644 index 4cbad4b176..0000000000 --- a/packages/platform-harmonyos/src/__tests__/hdc-shell.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { beforeEach, expect, test, vi } from 'vitest'; - -vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({ - ...(await importOriginal()), - runCmd: vi.fn(async () => ({ exitCode: 0, stdout: '', stderr: '' })), -})); - -import { runCmd } from '@agent-device/host-kit/command'; -import { runHarmonyHdc, runHarmonyShell } from '../hdc.ts'; - -const DEVICE = { id: 'target-1' }; - -beforeEach(() => { - vi.mocked(runCmd).mockClear(); -}); - -test('runHarmonyHdc refuses a raw shell argv and runHarmonyShell escapes for HDC quoting', async () => { - await expect(runHarmonyHdc(DEVICE, ['shell', 'uitest', 'uiInput', 'text', 'x'])).rejects.toEqual( - expect.objectContaining({ - code: 'INVALID_ARGS', - details: expect.objectContaining({ reason: 'unguarded-device-shell-argv' }), - }), - ); - expect(runCmd).not.toHaveBeenCalled(); - - await runHarmonyShell(DEVICE, ['uitest', 'uiInput', 'text', 'hello; reboot']); - await runHarmonyShell(DEVICE, ['uitest', 'uiInput', 'inputText', 307, 1334, '$(id) "x" `y`']); - await runHarmonyHdc(DEVICE, ['file', 'recv', '/data/a.png', '/tmp/a.png']); - expect(vi.mocked(runCmd).mock.calls.map(([cmd, args]) => [cmd, args])).toEqual([ - ['hdc', ['-t', 'target-1', 'shell', 'uitest', 'uiInput', 'text', 'hello; reboot']], - [ - 'hdc', - [ - '-t', - 'target-1', - 'shell', - 'uitest', - 'uiInput', - 'inputText', - '307', - '1334', - '\\$(id) \\"x\\" \\`y\\`', - ], - ], - ['hdc', ['-t', 'target-1', 'file', 'recv', '/data/a.png', '/tmp/a.png']], - ]); -}); diff --git a/packages/platform-harmonyos/src/__tests__/hdc.test.ts b/packages/platform-harmonyos/src/__tests__/hdc.test.ts index aa95fa9fdf..767859cfd8 100644 --- a/packages/platform-harmonyos/src/__tests__/hdc.test.ts +++ b/packages/platform-harmonyos/src/__tests__/hdc.test.ts @@ -1,152 +1,201 @@ -import { bindTestCommandHost } from '@agent-device/test-kit'; import assert from 'node:assert/strict'; -import { promises as fs } from 'node:fs'; +import fs from 'node:fs'; import path from 'node:path'; -import { beforeEach, test, vi } from 'vitest'; - -vi.mock('@agent-device/host-kit/command', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, runCmd: vi.fn() }; +import { test } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { AppError, asAppError, createRequestCanceledError } from '@agent-device/kernel/errors'; +import { + createHarmonyHostStub, + createHarmonyToolchainRoot, + harmonyCommandPath, +} from '../toolbox.fixtures.ts'; +import { createHarmonyCommandRunner } from '../command-host.ts'; +import { DEFAULT_HARMONY_HDC_TIMEOUT_MS } from '../hdc.ts'; + +const DEVICE = { id: 'target-1' }; + +test('the HDC route bounds ordinary commands with its default timeout', async () => { + const stub = createHarmonyHostStub(); + await stub.toolbox.hdc.runShell(DEVICE, ['uitest', 'uiInput', 'click', '10', '20']); + + assert.deepEqual(stub.commands[0], { + executable: 'hdc', + args: ['-t', 'target-1', 'shell', 'uitest', 'uiInput', 'click', '10', '20'], + env: { PATH: '/usr/bin' }, + timeoutMs: DEFAULT_HARMONY_HDC_TIMEOUT_MS, + allowFailure: undefined, + signal: undefined, + }); }); -import { runCmd } from '@agent-device/host-kit/command'; -import { - DEFAULT_HARMONY_HDC_TIMEOUT_MS, - ensureHarmonyToolchainPathConfigured, - runHarmonyHdc, - runHarmonyShell, -} from '../hdc.ts'; -import { mkdtempForTestSync } from './tmp-dir.ts'; +test('the HDC route preserves an operation-specific timeout', async () => { + const stub = createHarmonyHostStub(); + await stub.toolbox.hdc.run(DEVICE, ['install', '-r', '/tmp/example.hap'], { + timeoutMs: 180_000, + }); -bindTestCommandHost(); + assert.equal(stub.commands[0]?.timeoutMs, 180_000); +}); -const mockRunCmd = vi.mocked(runCmd); -const device = { id: '127.0.0.1:5555' }; +test('the HDC route forwards a binding abort signal to an in-flight command', async () => { + const controller = new AbortController(); + const stub = createHarmonyHostStub(); -beforeEach(() => { - mockRunCmd.mockReset(); - mockRunCmd.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); -}); + await stub.toolbox.hdc.run(DEVICE, ['install', '-r', '/tmp/example.hap'], { + signal: controller.signal, + }); -test('runHarmonyHdc bounds ordinary HDC commands by a default timeout', async () => { - await runHarmonyShell(device, ['uitest', 'uiInput', 'click', '10', '20']); + // The host owns the child, so the plugin's job is to hand the signal over with the request. + assert.equal(stub.commands[0]?.signal, controller.signal); +}); - assert.deepEqual(mockRunCmd.mock.calls[0], [ - 'hdc', - ['-t', '127.0.0.1:5555', 'shell', 'uitest', 'uiInput', 'click', '10', '20'], - { timeoutMs: DEFAULT_HARMONY_HDC_TIMEOUT_MS }, +test('the HDC route escapes shell words for HDC quoting', async () => { + const stub = createHarmonyHostStub(); + await stub.toolbox.hdc.runShell(DEVICE, ['uitest', 'uiInput', 'text', 'hello; reboot']); + await stub.toolbox.hdc.runShell(DEVICE, [ + 'uitest', + 'uiInput', + 'inputText', + 307, + 1334, + '$(id) "x" `y`', ]); + await stub.toolbox.hdc.run(DEVICE, ['file', 'recv', '/data/a.png', '/tmp/a.png']); + + assert.deepEqual( + stub.commands.map((command) => [command.executable, command.args]), + [ + ['hdc', ['-t', 'target-1', 'shell', 'uitest', 'uiInput', 'text', 'hello; reboot']], + [ + 'hdc', + [ + '-t', + 'target-1', + 'shell', + 'uitest', + 'uiInput', + 'inputText', + '307', + '1334', + '\\$(id) \\"x\\" \\`y\\`', + ], + ], + ['hdc', ['-t', 'target-1', 'file', 'recv', '/data/a.png', '/tmp/a.png']], + ], + ); }); -test('runHarmonyHdc preserves an operation-specific timeout', async () => { - await runHarmonyHdc(device, ['install', '-r', '/tmp/example.hap'], { timeoutMs: 180_000 }); +test('the HDC route refuses a raw shell argv before asking the host', async () => { + const stub = createHarmonyHostStub(); - assert.deepEqual(mockRunCmd.mock.calls[0]?.[2], { timeoutMs: 180_000 }); + await assert.rejects( + stub.toolbox.hdc.run(DEVICE, ['shell', 'uitest', 'uiInput', 'text', 'x']), + (error: unknown) => + error instanceof Error && + 'details' in error && + (error as { details?: { reason?: string } }).details?.reason === + 'unguarded-device-shell-argv', + ); + assert.equal(stub.commands.length, 0); }); -test('runHarmonyHdc forwards a binding abort signal to an in-flight HDC command', async () => { - const controller = new AbortController(); - const aborted = new Error('request aborted'); - mockRunCmd.mockImplementation( - async (_cmd, _args, options) => - await new Promise((_resolve, reject) => { - options?.signal?.addEventListener('abort', () => reject(options.signal?.reason), { - once: true, - }); - }), - ); +test('the HDC route spawns the HDC a documented root carries and puts that root on PATH', async () => { + const root = createHarmonyToolchainRoot(); + const stub = createHarmonyHostStub({ env: { HDC_SDK_PATH: root, PATH: '/usr/bin' } }); - const pending = runHarmonyHdc(device, ['install', '-r', '/tmp/example.hap'], { - signal: controller.signal, - }); - controller.abort(aborted); + assert.equal(await stub.toolbox.hdc.executable(), path.join(root, 'hdc')); + await stub.toolbox.hdc.launch(['list', 'targets']); - await assert.rejects(pending, (error: unknown) => error === aborted); - assert.equal(mockRunCmd.mock.calls[0]?.[2]?.signal, controller.signal); + assert.equal(stub.commands[0]?.executable, path.join(root, 'hdc')); + assert.deepEqual(harmonyCommandPath(stub.commands[0]!), [root, '/usr/bin']); }); -/** HDC_SDK_PATH names the toolchains directory itself, so `HDC_SDK_PATH/hdc` must exist. */ -async function seedDirectToolchain(root: string): Promise { - await fs.mkdir(root, { recursive: true }); - const hdc = path.join(root, 'hdc'); - await fs.writeFile(hdc, '#!/bin/sh\nexit 0\n', 'utf8'); - await fs.chmod(hdc, 0o755); - return root; -} - -/** DevEco's home joins `default/openharmony/toolchains`; the command-line-tools root adds `sdk` first. */ -async function seedNestedToolchain(root: string, ...segments: string[]): Promise { - const toolchains = path.join(root, ...segments, 'default', 'openharmony', 'toolchains'); - await fs.mkdir(toolchains, { recursive: true }); - const hdc = path.join(toolchains, 'hdc'); - await fs.writeFile(hdc, '#!/bin/sh\nexit 0\n', 'utf8'); - await fs.chmod(hdc, 0o755); - return root; -} - -test('ensureHarmonyToolchainPathConfigured prepends every root holding an hdc binary', async () => { - const hdcSdkRoot = await seedDirectToolchain(mkdtempForTestSync('agent-device-hdc-sdk-')); - const devecoRoot = await seedNestedToolchain(mkdtempForTestSync('agent-device-hdc-deveco-')); - const cmdlineRoot = await seedNestedToolchain( - mkdtempForTestSync('agent-device-hdc-cmdline-'), - 'sdk', - ); +test('the HDC route answers a host spawn refusal with the curated toolchain error', async () => { + // The host refused a spawn of the bare name it could not resolve from PATH. + const stub = createHarmonyHostStub({ + reject: () => new AppError('TOOL_MISSING', 'hdc not found in PATH', { cmd: 'hdc' }), + }); - const env: NodeJS.ProcessEnv = { - PATH: '/usr/bin', - HDC_SDK_PATH: hdcSdkRoot, - DEVECO_SDK_HOME: devecoRoot, - HARMONYOS_COMMAND_LINE_TOOLS: cmdlineRoot, - }; + await assert.rejects( + // Any command, not only the discovery probe, gets the curated error. + stub.toolbox.hdc.run(DEVICE, ['bm', 'dump', '-a']), + (error: unknown) => { + const failure = asAppError(error); + assert.equal(failure.code, 'TOOL_MISSING'); + assert.equal(failure.message, 'hdc not found in PATH'); + assert.equal( + failure.details?.hint, + 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH or set HDC_SDK_PATH.', + ); + return true; + }, + ); +}); - await ensureHarmonyToolchainPathConfigured(env); +test('the HDC route names the resolved path when the host refuses an absolute HDC', async () => { + const root = createHarmonyToolchainRoot(); + const stub = createHarmonyHostStub({ + env: { HDC_SDK_PATH: root, PATH: '/usr/bin' }, + reject: () => new AppError('TOOL_MISSING', 'hdc not found in PATH', { cmd: 'hdc' }), + }); - assert.deepEqual((env.PATH ?? '').split(path.delimiter), [ - hdcSdkRoot, - path.join(devecoRoot, 'default', 'openharmony', 'toolchains'), - path.join(cmdlineRoot, 'sdk', 'default', 'openharmony', 'toolchains'), - '/usr/bin', - ]); + await assert.rejects(stub.toolbox.hdc.launch(['list', 'targets']), (error: unknown) => { + const failure = asAppError(error); + // The plugin resolved a documented root, so the message names where it looked. + assert.equal(failure.message, `hdc not found at ${path.join(root, 'hdc')}`); + return true; + }); }); -test('ensureHarmonyToolchainPathConfigured leaves PATH untouched when no root holds hdc', async () => { - const env: NodeJS.ProcessEnv = { - PATH: '/usr/bin', - HDC_SDK_PATH: ' ', - DEVECO_SDK_HOME: mkdtempForTestSync('agent-device-hdc-none-'), - HARMONYOS_COMMAND_LINE_TOOLS: mkdtempForTestSync('agent-device-hdc-none-'), - }; +test('the HDC route leaves another host rejection as the host reported it', async () => { + const canceled = createRequestCanceledError({ cmd: 'hdc' }); + const stub = createHarmonyHostStub({ reject: () => canceled }); - await ensureHarmonyToolchainPathConfigured(env); + await assert.rejects(stub.toolbox.hdc.launch(['list', 'targets']), (error: unknown) => + Object.is(error, canceled), + ); +}); + +test('the command runner prefers the roots in the documented order', async () => { + const hdcSdk = createHarmonyToolchainRoot(); + const deveco = createHarmonyToolchainRoot(); + const commands = createHarmonyCommandRunner( + createHarmonyHostStub({ env: { HDC_SDK_PATH: hdcSdk, DEVECO_SDK_HOME: deveco } }).host, + ); - assert.equal(env.PATH, '/usr/bin'); + assert.equal(await commands.resolveHdc(), path.join(hdcSdk, 'hdc')); }); -test('ensureHarmonyToolchainPathConfigured creates PATH and dedupes a root already on it', async () => { - const toolchains = await seedDirectToolchain(mkdtempForTestSync('agent-device-hdc-dup-')); +test('the command runner derives the toolchains directory from the DevEco SDK layout', async () => { + // The documented layout is /default/openharmony/toolchains/hdc. + const home = mkdtempForTestSync('harmony-deveco-'); + const toolchains = path.join(home, 'default', 'openharmony', 'toolchains'); + fs.mkdirSync(toolchains, { recursive: true }); + fs.writeFileSync(path.join(toolchains, 'hdc'), '#!/bin/sh\necho stub\n', { mode: 0o755 }); + const commands = createHarmonyCommandRunner( + createHarmonyHostStub({ env: { DEVECO_SDK_HOME: home } }).host, + ); - const env: NodeJS.ProcessEnv = { - PATH: `/usr/bin${path.delimiter}${toolchains}`, - HDC_SDK_PATH: toolchains, - }; - await ensureHarmonyToolchainPathConfigured(env); + assert.equal(await commands.resolveHdc(), path.join(toolchains, 'hdc')); +}); - // The toolchain root moves to the front instead of appearing twice. - assert.equal(env.PATH, [toolchains, '/usr/bin'].join(path.delimiter)); +test('the command runner ignores a root whose hdc is not executable', async () => { + const root = createHarmonyToolchainRoot(); + const commands = createHarmonyCommandRunner( + createHarmonyHostStub({ env: { HDC_SDK_PATH: `${root}/missing`, PATH: '/bin' } }).host, + ); - const missingPath: NodeJS.ProcessEnv = { HDC_SDK_PATH: toolchains }; - await ensureHarmonyToolchainPathConfigured(missingPath); - assert.equal(missingPath.PATH, toolchains); + assert.equal(await commands.toolchainHdc(), undefined); + assert.equal(await commands.resolveHdc(), 'hdc'); }); -test('ensureHarmonyToolchainPathConfigured defaults to the host environment', async () => { - const toolchains = await seedDirectToolchain(mkdtempForTestSync('agent-device-hdc-host-')); - vi.stubEnv('PATH', '/usr/bin'); - vi.stubEnv('HDC_SDK_PATH', toolchains); - vi.stubEnv('DEVECO_SDK_HOME', undefined); - vi.stubEnv('HARMONYOS_COMMAND_LINE_TOOLS', undefined); +test('the command runner dedupes a root already on PATH', async () => { + const root = createHarmonyToolchainRoot(); + const stub = createHarmonyHostStub({ + env: { HDC_SDK_PATH: root, PATH: ['/usr/bin', root].join(path.delimiter) }, + }); - await ensureHarmonyToolchainPathConfigured(process.env); + await stub.toolbox.hdc.launch(['list', 'targets']); - assert.equal(process.env.PATH, [toolchains, '/usr/bin'].join(path.delimiter)); + assert.deepEqual(harmonyCommandPath(stub.commands[0]!), [root, '/usr/bin']); }); diff --git a/packages/platform-harmonyos/src/__tests__/input-actions.test.ts b/packages/platform-harmonyos/src/__tests__/input-actions.test.ts index 85fdf9a8fd..3b7e6d186e 100644 --- a/packages/platform-harmonyos/src/__tests__/input-actions.test.ts +++ b/packages/platform-harmonyos/src/__tests__/input-actions.test.ts @@ -2,16 +2,14 @@ import assert from 'node:assert/strict'; import { beforeEach, test, vi } from 'vitest'; import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { createHarmonyHdcRunnerStub } from '../toolbox.fixtures.ts'; -const { runHarmonyShell, sleep, readHarmonyGestureViewport, invalidateHarmonyGestureViewport } = - vi.hoisted(() => ({ - runHarmonyShell: vi.fn(), - sleep: vi.fn(), - readHarmonyGestureViewport: vi.fn(), - invalidateHarmonyGestureViewport: vi.fn(), - })); +const { sleep, readHarmonyGestureViewport, invalidateHarmonyGestureViewport } = vi.hoisted(() => ({ + sleep: vi.fn(), + readHarmonyGestureViewport: vi.fn(), + invalidateHarmonyGestureViewport: vi.fn(), +})); -vi.mock('../hdc.ts', () => ({ runHarmonyShell })); vi.mock('@agent-device/host-kit/retry', () => ({ sleep })); vi.mock('../snapshot.ts', () => ({ readHarmonyGestureViewport, @@ -42,38 +40,44 @@ const DEVICE: DeviceInfo = { booted: true, }; +let hdc: ReturnType; + beforeEach(() => { - runHarmonyShell.mockReset(); + hdc = createHarmonyHdcRunnerStub(); sleep.mockReset(); readHarmonyGestureViewport.mockReset(); invalidateHarmonyGestureViewport.mockReset(); }); +/** The shell words of every HDC call the module made. */ +function shellWords(): readonly (readonly unknown[])[] { + return hdc.calls.map((call) => call.args); +} + test('HarmonyOS input primitives use the documented uiInput command names', async () => { - await pressHarmony(DEVICE, 10, 20); - await doubleClickHarmony(DEVICE, 11, 21); - await longPressHarmony(DEVICE, 12, 22); - await typeHarmony(DEVICE, 'hello', 25); - await fillHarmony(DEVICE, 13, 23, 'world', 50); - await backHarmony(DEVICE); - await homeHarmony(DEVICE); - await appSwitcherHarmony(DEVICE); - await pressHarmonyKeyboardKey(DEVICE, 'Enter'); - - assert.deepEqual( - runHarmonyShell.mock.calls.map(([, args]) => args), - [ - ['uitest', 'uiInput', 'click', 10, 20], - ['uitest', 'uiInput', 'doubleClick', 11, 21], - ['uitest', 'uiInput', 'longClick', 12, 22], - ['uitest', 'uiInput', 'text', 'hello'], - ['uitest', 'uiInput', 'inputText', 13, 23, 'world'], - ['uitest', 'uiInput', 'keyEvent', 'Back'], - ['uitest', 'uiInput', 'keyEvent', 'Home'], - ['uitest', 'uiInput', 'keyEvent', 'Recent'], - ['uitest', 'uiInput', 'keyEvent', 'Enter'], - ], - ); + await pressHarmony(hdc, DEVICE, 10, 20); + await doubleClickHarmony(hdc, DEVICE, 11, 21); + await longPressHarmony(hdc, DEVICE, 12, 22); + await typeHarmony(hdc, DEVICE, 'hello', 25); + await fillHarmony(hdc, DEVICE, 13, 23, 'world', 50); + await backHarmony(hdc, DEVICE); + await homeHarmony(hdc, DEVICE); + await appSwitcherHarmony(hdc, DEVICE); + await pressHarmonyKeyboardKey(hdc, DEVICE, 'Enter'); + + assert.deepEqual(shellWords(), [ + ['uitest', 'uiInput', 'click', 10, 20], + ['uitest', 'uiInput', 'doubleClick', 11, 21], + ['uitest', 'uiInput', 'longClick', 12, 22], + ['uitest', 'uiInput', 'text', 'hello'], + ['uitest', 'uiInput', 'inputText', 13, 23, 'world'], + ['uitest', 'uiInput', 'keyEvent', 'Back'], + ['uitest', 'uiInput', 'keyEvent', 'Home'], + ['uitest', 'uiInput', 'keyEvent', 'Recent'], + ['uitest', 'uiInput', 'keyEvent', 'Enter'], + ]); + // Every call went to the one device this interactor was created for. + assert.deepEqual([...new Set(hdc.calls.map((call) => call.target))], ['harmony-1']); assert.deepEqual(sleep.mock.calls, [[25], [50]]); assert.deepEqual(invalidateHarmonyGestureViewport.mock.calls, [[DEVICE], [DEVICE], [DEVICE]]); }); @@ -81,10 +85,10 @@ test('HarmonyOS input primitives use the documented uiInput command names', asyn test('HarmonyOS scroll derives a viewport-aware swipe plan', async () => { readHarmonyGestureViewport.mockResolvedValue({ x: 0, y: 0, width: 100, height: 200 }); - const plan = await scrollHarmony(DEVICE, 'down', { amount: 0.5, durationMs: 456 }); + const plan = await scrollHarmony(hdc, DEVICE, 'down', { amount: 0.5, durationMs: 456 }); assert.equal(plan.direction, 'down'); - assert.deepEqual(runHarmonyShell.mock.calls[0]?.[1], [ + assert.deepEqual(hdc.calls[0]?.args, [ 'uitest', 'uiInput', 'swipe', @@ -114,7 +118,7 @@ test('HarmonyOS gestures lower a single trajectory and reject multi-touch', asyn ], }; - const result = await performHarmonyGesture(DEVICE, singlePlan); + const result = await performHarmonyGesture(hdc, DEVICE, singlePlan); assert.deepEqual(result, { backend: 'harmonyos-hdc-uiinput', @@ -122,19 +126,10 @@ test('HarmonyOS gestures lower a single trajectory and reject multi-touch', asyn velocity: 256, viewport: singlePlan.viewport, }); - assert.deepEqual(runHarmonyShell.mock.calls[0]?.[1], [ - 'uitest', - 'uiInput', - 'fling', - 10, - 20, - 90, - 120, - 256, - ]); + assert.deepEqual(hdc.calls[0]?.args, ['uitest', 'uiInput', 'fling', 10, 20, 90, 120, 256]); await assert.rejects( () => - performHarmonyGesture(DEVICE, { + performHarmonyGesture(hdc, DEVICE, { ...singlePlan, topology: 'multi', intent: 'pinch', diff --git a/packages/platform-harmonyos/src/__tests__/keyboard-band.test.ts b/packages/platform-harmonyos/src/__tests__/keyboard-band.test.ts index 2448449f29..4960603c3b 100644 --- a/packages/platform-harmonyos/src/__tests__/keyboard-band.test.ts +++ b/packages/platform-harmonyos/src/__tests__/keyboard-band.test.ts @@ -1,13 +1,11 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; -import { beforeEach, test, vi } from 'vitest'; - -const { runHarmonyHdc, runHarmonyShell } = vi.hoisted(() => ({ - runHarmonyHdc: vi.fn(), - runHarmonyShell: vi.fn(), -})); - -vi.mock('../hdc.ts', () => ({ runHarmonyHdc, runHarmonyShell })); +import { beforeEach, test } from 'vitest'; +import { + answerHarmonyShell, + createHarmonyHdcRunnerStub, + type HarmonyHdcRunnerStub, +} from '../toolbox.fixtures.ts'; import { harmonyKeyboardBandFromWindowDump, readHarmonyKeyboardBand } from '../keyboard-band.ts'; import { snapshotHarmony } from '../snapshot.ts'; @@ -53,10 +51,10 @@ const REAL_KEYBOARD_HIDDEN_ROWS = [ const PARTIAL_RECT_SHOWN_ROW = 'SCBKeyboardPanel 0 5714 17 2134 1 0 102 0 [ 0 1546 1080 860 ] [ 0 0 ] [ 1 1 0.5 0.5 ]'; +let hdc: HarmonyHdcRunnerStub; + beforeEach(() => { - runHarmonyHdc.mockReset(); - runHarmonyShell.mockReset(); - runHarmonyShell.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); + hdc = createHarmonyHdcRunnerStub(); }); test('the real display-spanning up-state rows publish visibility-only true, never a band frame', () => { @@ -165,61 +163,45 @@ test('a rect-less panel row still reads through its z-order', () => { }); test('a failed window probe answers unmeasurable and never throws', async () => { - runHarmonyShell.mockResolvedValue({ exitCode: 1, stdout: '', stderr: 'dump failed' }); - assert.deepEqual(await readHarmonyKeyboardBand(DEVICE), { + const failing = createHarmonyHdcRunnerStub([{ exitCode: 1, stderr: 'dump failed' }]); + assert.deepEqual(await readHarmonyKeyboardBand(failing, DEVICE), { kind: 'unmeasurable', reason: 'keyboard-window-probe-failed', }); - runHarmonyShell.mockRejectedValue(new Error('hdc disconnected')); - assert.deepEqual(await readHarmonyKeyboardBand(DEVICE), { + // A route that refuses outright is answered the same way as a nonzero exit. + const throwing = createHarmonyHdcRunnerStub(); + throwing.runShell = async () => { + throw new Error('hdc disconnected'); + }; + assert.deepEqual(await readHarmonyKeyboardBand(throwing, DEVICE), { kind: 'unmeasurable', reason: 'keyboard-window-probe-failed', }); }); test('readHarmonyKeyboardBand dumps the window manager table', async () => { - runHarmonyShell.mockImplementation(async (_device: unknown, words: string[]) => { - if (words[0] === 'hidumper') { - return { exitCode: 0, stdout: REAL_KEYBOARD_HIDDEN_ROWS, stderr: '' }; - } - return { exitCode: 0, stdout: '', stderr: '' }; - }); + answerHarmonyShell(hdc, (words) => + words[0] === 'hidumper' ? REAL_KEYBOARD_HIDDEN_ROWS : undefined, + ); - await readHarmonyKeyboardBand(DEVICE); + await readHarmonyKeyboardBand(hdc, DEVICE); - const hidumperCall = runHarmonyShell.mock.calls.find( - (call) => (call[1] as string[])[0] === 'hidumper', - ); - assert.deepEqual(hidumperCall?.[1], ['hidumper', '-s', 'WindowManagerService', '-a', '-a']); + assert.deepEqual(hdc.calls[0]?.args, ['hidumper', '-s', 'WindowManagerService', '-a', '-a']); + assert.equal(hdc.calls[0]?.target, 'harmony-1'); }); test('snapshotHarmony carries the keyboard band beside its tree', async () => { - runHarmonyShell.mockImplementation(async (_device: unknown, words: string[]) => { - if (words[0] === 'hidumper') { - return { - exitCode: 0, - stdout: `${WINDOW_TABLE_HEADER}\n${REAL_KEYBOARD_UP_ROWS}`, - stderr: '', - }; - } - return { exitCode: 0, stdout: '', stderr: '' }; - }); - runHarmonyHdc.mockImplementation(async (_device: unknown, args: string[]) => { - if (args[0] === 'file' && args[1] === 'recv') { - fs.writeFileSync( - args[3] as string, - JSON.stringify({ - attributes: { type: 'root', bounds: '[0,0][1080,2406]' }, - children: [{ attributes: { type: 'Button', text: 'first', clickable: 'true' } }], - }), - 'utf8', - ); - } - return { exitCode: 0, stdout: '', stderr: '' }; + const hdc = createHarmonyHdcRunnerStub(); + scriptHarmonyLayoutDump(hdc, { + attributes: { type: 'root', bounds: '[0,0][1080,2406]' }, + children: [{ attributes: { type: 'Button', text: 'first', clickable: 'true' } }], }); + answerHarmonyShell(hdc, (words) => + words[0] === 'hidumper' ? `${WINDOW_TABLE_HEADER}\n${REAL_KEYBOARD_UP_ROWS}` : undefined, + ); - const snapshot = await snapshotHarmony(DEVICE); + const snapshot = await snapshotHarmony(hdc, DEVICE); assert.deepEqual(snapshot.keyboard, { kind: 'visibility-only', @@ -230,3 +212,17 @@ test('snapshotHarmony carries the keyboard band beside its tree', async () => { ['Application', 'first'], ); }); + +/** + * Answers the layout pull so the file the transport receives at its local path is `layout`, which + * is what `snapshotHarmony` reads back. + */ +function scriptHarmonyLayoutDump(hdc: HarmonyHdcRunnerStub, layout: unknown): void { + const pull = hdc.run; + hdc.run = async (device, args, options) => { + if (args[0] === 'file' && args[1] === 'recv') { + fs.writeFileSync(String(args[3]), JSON.stringify(layout), 'utf8'); + } + return await pull(device, args, options); + }; +} diff --git a/packages/platform-harmonyos/src/__tests__/perf.test.ts b/packages/platform-harmonyos/src/__tests__/perf.test.ts index 6c12bfdb33..9d0b625055 100644 --- a/packages/platform-harmonyos/src/__tests__/perf.test.ts +++ b/packages/platform-harmonyos/src/__tests__/perf.test.ts @@ -1,9 +1,6 @@ import assert from 'node:assert/strict'; -import { beforeEach, test, vi } from 'vitest'; - -const { runHarmonyShell } = vi.hoisted(() => ({ runHarmonyShell: vi.fn() })); - -vi.mock('../hdc.ts', () => ({ runHarmonyShell })); +import { beforeEach, test } from 'vitest'; +import { createHarmonyHdcRunnerStub, type HarmonyHdcRunnerStub } from '../toolbox.fixtures.ts'; import { parseHarmonyPid, parseHarmonyProcStatusMemory, sampleHarmonyMemoryPerf } from '../perf.ts'; @@ -16,8 +13,10 @@ const DEVICE = { booted: true, }; +let hdc: HarmonyHdcRunnerStub; + beforeEach(() => { - runHarmonyShell.mockReset(); + hdc = createHarmonyHdcRunnerStub(); }); test('HarmonyOS perf parsers read process-scoped memory samples', () => { @@ -34,20 +33,15 @@ test('HarmonyOS perf parsers reject incomplete process output', () => { }); test('HarmonyOS perf samples resolve a process before collecting memory', async () => { - runHarmonyShell - .mockResolvedValueOnce({ exitCode: 0, stdout: '42\n', stderr: '' }) - .mockResolvedValueOnce({ - exitCode: 0, - stdout: 'VmRSS:\t 256 kB\nVmHWM:\t 512 kB\n', - stderr: '', - }); + hdc.answer({ stdout: '42\n' }); + hdc.answer({ stdout: 'VmRSS:\t 256 kB\nVmHWM:\t 512 kB\n' }); - const memory = await sampleHarmonyMemoryPerf(DEVICE, 'com.example.application'); + const memory = await sampleHarmonyMemoryPerf(hdc, DEVICE, 'com.example.application'); assert.deepEqual(memory.totalRssKb, 256); assert.equal(memory.peakRssKb, 512); assert.deepEqual( - runHarmonyShell.mock.calls.map(([, args]) => args), + hdc.calls.map((call) => call.args), [ ['pidof', 'com.example.application'], ['cat', '/proc/42/status'], @@ -56,17 +50,18 @@ test('HarmonyOS perf samples resolve a process before collecting memory', async }); test('HarmonyOS perf reports missing processes and incomplete samples', async () => { - runHarmonyShell.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: 'not found' }); + const missing = createHarmonyHdcRunnerStub([{ exitCode: 1, stderr: 'not found' }]); await assert.rejects( - () => sampleHarmonyMemoryPerf(DEVICE, 'com.example.application'), + () => sampleHarmonyMemoryPerf(missing, DEVICE, 'com.example.application'), /running process/, ); - runHarmonyShell - .mockResolvedValueOnce({ exitCode: 0, stdout: '42\n', stderr: '' }) - .mockResolvedValueOnce({ exitCode: 0, stdout: 'VmSize:\t 1 kB\n', stderr: '' }); + const incomplete = createHarmonyHdcRunnerStub([ + { stdout: '42\n' }, + { stdout: 'VmSize:\t 1 kB\n' }, + ]); await assert.rejects( - () => sampleHarmonyMemoryPerf(DEVICE, 'com.example.application'), + () => sampleHarmonyMemoryPerf(incomplete, DEVICE, 'com.example.application'), /resident memory/, ); }); diff --git a/packages/platform-harmonyos/src/__tests__/screenshot.test.ts b/packages/platform-harmonyos/src/__tests__/screenshot.test.ts index 10c82df9fc..8d1e11ba43 100644 --- a/packages/platform-harmonyos/src/__tests__/screenshot.test.ts +++ b/packages/platform-harmonyos/src/__tests__/screenshot.test.ts @@ -1,18 +1,14 @@ import assert from 'node:assert/strict'; import { beforeEach, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { createHarmonyHdcRunnerStub, type HarmonyHdcRunnerStub } from '../toolbox.fixtures.ts'; -const { readFile, runHarmonyHdc, runHarmonyShell } = vi.hoisted(() => ({ - readFile: vi.fn(), - runHarmonyHdc: vi.fn(), - runHarmonyShell: vi.fn(), -})); +const { readFile } = vi.hoisted(() => ({ readFile: vi.fn() })); vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => ({ ...(await importOriginal()), readHostBinaryFile: readFile, })); -vi.mock('../hdc.ts', () => ({ runHarmonyHdc, runHarmonyShell })); import { screenshotHarmony } from '../screenshot.ts'; @@ -25,33 +21,33 @@ const DEVICE: DeviceInfo = { booted: true, }; +let hdc: HarmonyHdcRunnerStub; + beforeEach(() => { + hdc = createHarmonyHdcRunnerStub(); readFile.mockReset(); - runHarmonyHdc.mockReset(); - runHarmonyShell.mockReset(); - runHarmonyHdc.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); - runHarmonyShell.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); readFile.mockResolvedValue(Buffer.from([0xff, 0xd8, 0xff, 0x00])); }); test('screenshotHarmony captures, retrieves, validates, and cleans a JPEG', async () => { - await screenshotHarmony(DEVICE, '/tmp/capture.jpg'); - - const shellCalls = runHarmonyShell.mock.calls.map(([, args]) => args); - const hdcCalls = runHarmonyHdc.mock.calls.map(([, args]) => args); - assert.deepEqual(shellCalls[0]?.slice(0, 2), ['snapshot_display', '-f']); - assert.match(String(shellCalls[0]?.[2]), /^\/data\/local\/tmp\/agent-device-screen-.+\.jpeg$/); - assert.deepEqual(hdcCalls[0]?.slice(0, 2), ['file', 'recv']); - assert.match(String(hdcCalls[0]?.[2]), /^\/data\/local\/tmp\/agent-device-screen-.+\.jpeg$/); - assert.equal(hdcCalls[0]?.[3], '/tmp/capture.jpg'); - assert.deepEqual(shellCalls[1]?.slice(0, 2), ['rm', '-f']); + await screenshotHarmony(hdc, DEVICE, '/tmp/capture.jpg'); + + const shellWords = hdc.calls.filter((call) => call.kind === 'runShell').map((call) => call.args); + const pull = hdc.calls.find((call) => call.kind === 'run')!; + assert.deepEqual(shellWords[0]?.slice(0, 2), ['snapshot_display', '-f']); + assert.match(String(shellWords[0]?.[2]), /^\/data\/local\/tmp\/agent-device-screen-.+\.jpeg$/); + assert.deepEqual(pull.args.slice(0, 2), ['file', 'recv']); + assert.match(String(pull.args[2]), /^\/data\/local\/tmp\/agent-device-screen-.+\.jpeg$/); + assert.equal(pull.args[3], '/tmp/capture.jpg'); + assert.deepEqual(shellWords[1]?.slice(0, 2), ['rm', '-f']); assert.deepEqual(readFile.mock.calls, [['/tmp/capture.jpg']]); }); test('screenshotHarmony rejects a retrieved artifact that is not JPEG data', async () => { readFile.mockResolvedValue(Buffer.from('not-a-jpeg')); - await assert.rejects(() => screenshotHarmony(DEVICE, '/tmp/invalid.jpg'), /not a JPEG/); - assert.equal(runHarmonyShell.mock.calls.length, 2); - assert.equal(runHarmonyHdc.mock.calls.length, 1); + await assert.rejects(() => screenshotHarmony(hdc, DEVICE, '/tmp/invalid.jpg'), /not a JPEG/); + // The capture, the pull, and the cleanup all still happened. + assert.equal(hdc.calls.filter((call) => call.kind === 'runShell').length, 2); + assert.equal(hdc.calls.filter((call) => call.kind === 'run').length, 1); }); diff --git a/packages/platform-harmonyos/src/__tests__/settings.test.ts b/packages/platform-harmonyos/src/__tests__/settings.test.ts index 1ef4882e78..f5b839112a 100644 --- a/packages/platform-harmonyos/src/__tests__/settings.test.ts +++ b/packages/platform-harmonyos/src/__tests__/settings.test.ts @@ -1,9 +1,6 @@ import assert from 'node:assert/strict'; -import { beforeEach, test, vi } from 'vitest'; - -vi.mock('../hdc.ts', () => ({ runHarmonyShell: vi.fn() })); - -import { runHarmonyShell } from '../hdc.ts'; +import { beforeEach, test } from 'vitest'; +import { createHarmonyHdcRunnerStub, type HarmonyHdcRunnerStub } from '../toolbox.fixtures.ts'; import { setHarmonySetting } from '../settings.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, PRE_DISPATCH_REFUSAL_REASONS } from '@agent-device/kernel/errors'; @@ -15,17 +12,17 @@ const device: DeviceInfo = { kind: 'emulator', booted: true, }; -const mockRunHarmonyShell = vi.mocked(runHarmonyShell); + +let hdc: HarmonyHdcRunnerStub; beforeEach(() => { - mockRunHarmonyShell.mockReset(); - mockRunHarmonyShell.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' } as never); + hdc = createHarmonyHdcRunnerStub(); }); test('HarmonyOS clear-app-state force stops then clears bundle data and cache', async () => { await assert.doesNotReject(async () => { assert.deepEqual( - await setHarmonySetting(device, 'clear-app-state', 'clear', 'com.example.application'), + await setHarmonySetting(hdc, device, 'clear-app-state', 'clear', 'com.example.application'), { bundleId: 'com.example.application', forceStopped: true, @@ -35,7 +32,7 @@ test('HarmonyOS clear-app-state force stops then clears bundle data and cache', ); }); assert.deepEqual( - mockRunHarmonyShell.mock.calls.map((call) => call[1]), + hdc.calls.map((call) => call.args), [ ['aa', 'force-stop', 'com.example.application'], ['bm', 'clean', '-n', 'com.example.application', '-d', '-c'], @@ -44,13 +41,18 @@ test('HarmonyOS clear-app-state force stops then clears bundle data and cache', }); test('HarmonyOS settings rejects unsupported setting and missing app bundle', async () => { - await assert.rejects(async () => await setHarmonySetting(device, 'wifi', 'on'), /not supported/); await assert.rejects( - async () => await setHarmonySetting(device, 'clear-app-state', 'clear'), + async () => await setHarmonySetting(hdc, device, 'wifi', 'on'), + /not supported/, + ); + await assert.rejects( + async () => await setHarmonySetting(hdc, device, 'clear-app-state', 'clear'), (error: unknown) => error instanceof AppError && error.message.includes('requires an app id') && error.details?.reason === PRE_DISPATCH_REFUSAL_REASONS.sessionAppRequired && error.details?.dispatched === 'no', ); + // Both refusals answered before any HDC call. + assert.equal(hdc.calls.length, 0); }); diff --git a/packages/platform-harmonyos/src/__tests__/snapshot-viewport-cache.test.ts b/packages/platform-harmonyos/src/__tests__/snapshot-viewport-cache.test.ts index 2afcecb8ff..3d17b0a6d2 100644 --- a/packages/platform-harmonyos/src/__tests__/snapshot-viewport-cache.test.ts +++ b/packages/platform-harmonyos/src/__tests__/snapshot-viewport-cache.test.ts @@ -2,13 +2,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import { afterEach, beforeEach, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; - -const { runHarmonyHdc, runHarmonyShell } = vi.hoisted(() => ({ - runHarmonyHdc: vi.fn(), - runHarmonyShell: vi.fn(), -})); - -vi.mock('../hdc.ts', () => ({ runHarmonyHdc, runHarmonyShell })); +import { createHarmonyHdcRunnerStub, type HarmonyHdcRunnerStub } from '../toolbox.fixtures.ts'; import { invalidateHarmonyGestureViewport, readHarmonyGestureViewport } from '../snapshot.ts'; @@ -31,34 +25,42 @@ const WIDE_LAYOUT = { attributes: { type: 'root', bounds: '[0,0][2340,1080]' }, }; +let hdc: HarmonyHdcRunnerStub; + beforeEach(() => { - runHarmonyHdc.mockReset(); - runHarmonyShell.mockReset(); - runHarmonyShell.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); - scriptHarmonyLayoutDump(TALL_LAYOUT); + hdc = createHarmonyHdcRunnerStub(); + layout = TALL_LAYOUT; + scriptHarmonyLayoutDump(); }); afterEach(() => { vi.useRealTimers(); }); -/** Scripts `uitest dumpLayout` + `file recv` so the pulled layout is `layout`. */ -function scriptHarmonyLayoutDump(layout: unknown): void { - runHarmonyHdc.mockImplementation(async (_device: unknown, args: string[]) => { +/** The layout the device answers the next pull with; tests swap it to change what a dump reports. */ +let layout: unknown; + +/** + * Answers the layout pull so the file the transport receives at its local path is the current + * `layout`, which is what the viewport read parses. + */ +function scriptHarmonyLayoutDump(): void { + const pull = hdc.run; + hdc.run = async (device, args, options) => { if (args[0] === 'file' && args[1] === 'recv') { - fs.writeFileSync(args[3] as string, JSON.stringify(layout), 'utf8'); + fs.writeFileSync(String(args[3]), JSON.stringify(layout), 'utf8'); } - return { exitCode: 0, stdout: '', stderr: '' }; - }); + return await pull(device, args, options); + }; } function dumpLayoutCallCount(): number { - return runHarmonyShell.mock.calls.filter(([, args]) => args.includes('dumpLayout')).length; + return hdc.calls.filter((call) => call.args.includes('dumpLayout')).length; } test('repeated viewport reads within the TTL trigger a single layout dump', async () => { - const first = await readHarmonyGestureViewport(DEVICE_A); - const second = await readHarmonyGestureViewport(DEVICE_A); + const first = await readHarmonyGestureViewport(hdc, DEVICE_A); + const second = await readHarmonyGestureViewport(hdc, DEVICE_A); assert.deepEqual(first, { x: 0, y: 0, width: 1080, height: 2340 }); assert.deepEqual(second, first); @@ -69,33 +71,33 @@ test('viewport cache expires after two seconds without explicit invalidation', a vi.useFakeTimers(); vi.setSystemTime(0); - await readHarmonyGestureViewport(DEVICE_A); + await readHarmonyGestureViewport(hdc, DEVICE_A); assert.equal(dumpLayoutCallCount(), 1); - scriptHarmonyLayoutDump(WIDE_LAYOUT); + layout = WIDE_LAYOUT; await vi.advanceTimersByTimeAsync(2_000); - const refreshed = await readHarmonyGestureViewport(DEVICE_A); + const refreshed = await readHarmonyGestureViewport(hdc, DEVICE_A); assert.deepEqual(refreshed, { x: 0, y: 0, width: 2340, height: 1080 }); assert.equal(dumpLayoutCallCount(), 2); }); test('invalidating the viewport cache forces a fresh layout dump', async () => { - await readHarmonyGestureViewport(DEVICE_A); + await readHarmonyGestureViewport(hdc, DEVICE_A); assert.equal(dumpLayoutCallCount(), 1); - scriptHarmonyLayoutDump(WIDE_LAYOUT); + layout = WIDE_LAYOUT; invalidateHarmonyGestureViewport(DEVICE_A); - const refreshed = await readHarmonyGestureViewport(DEVICE_A); + const refreshed = await readHarmonyGestureViewport(hdc, DEVICE_A); assert.deepEqual(refreshed, { x: 0, y: 0, width: 2340, height: 1080 }); assert.equal(dumpLayoutCallCount(), 2); }); test('viewport cache entries are scoped per device id', async () => { - await readHarmonyGestureViewport(DEVICE_A); + await readHarmonyGestureViewport(hdc, DEVICE_A); - const otherDevice = await readHarmonyGestureViewport(DEVICE_B); + const otherDevice = await readHarmonyGestureViewport(hdc, DEVICE_B); assert.deepEqual(otherDevice, { x: 0, y: 0, width: 1080, height: 2340 }); assert.equal(dumpLayoutCallCount(), 2); diff --git a/packages/platform-harmonyos/src/__tests__/snapshot.test.ts b/packages/platform-harmonyos/src/__tests__/snapshot.test.ts index 0abbdd89fe..d35bd217fc 100644 --- a/packages/platform-harmonyos/src/__tests__/snapshot.test.ts +++ b/packages/platform-harmonyos/src/__tests__/snapshot.test.ts @@ -1,13 +1,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; -import { beforeEach, test, vi } from 'vitest'; - -const { runHarmonyHdc, runHarmonyShell } = vi.hoisted(() => ({ - runHarmonyHdc: vi.fn(), - runHarmonyShell: vi.fn(), -})); - -vi.mock('../hdc.ts', () => ({ runHarmonyHdc, runHarmonyShell })); +import { beforeEach, test } from 'vitest'; +import { createHarmonyHdcRunnerStub, type HarmonyHdcRunnerStub } from '../toolbox.fixtures.ts'; import { collectArkUiNodes, @@ -27,20 +21,24 @@ const DEVICE = { const UNBOUNDED = { maxDepth: Number.POSITIVE_INFINITY, interactiveOnly: false }; +let hdc: HarmonyHdcRunnerStub; + beforeEach(() => { - runHarmonyHdc.mockReset(); - runHarmonyShell.mockReset(); - runHarmonyShell.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); + hdc = createHarmonyHdcRunnerStub(); }); -/** Scripts `uitest dumpLayout` + `file recv` so the pulled layout is `layout`. */ -function scriptHarmonyLayoutDump(layout: unknown): void { - runHarmonyHdc.mockImplementation(async (_device: unknown, args: string[]) => { +/** + * Answers the layout pull so the file the transport receives at its local path is `layout`, which + * is what `snapshotHarmony` reads back. + */ +function scriptHarmonyLayoutDump(stub: HarmonyHdcRunnerStub, layout: unknown): void { + const pull = stub.run; + stub.run = async (device, args, options) => { if (args[0] === 'file' && args[1] === 'recv') { - fs.writeFileSync(args[3] as string, JSON.stringify(layout), 'utf8'); + fs.writeFileSync(String(args[3]), JSON.stringify(layout), 'utf8'); } - return { exitCode: 0, stdout: '', stderr: '' }; - }); + return await pull(device, args, options); + }; } test('parseArkUiBounds converts API 24 layout bounds into a rectangle', () => { @@ -115,12 +113,12 @@ test('collectArkUiNodes keeps counting the tree below a node the limit omitted', }); test('snapshotHarmony pulls a uitest layout and reports its analysis', async () => { - scriptHarmonyLayoutDump({ + scriptHarmonyLayoutDump(hdc, { attributes: { type: 'root', bounds: '[0,0][1080,2340]' }, children: [{ attributes: { type: 'Button', text: 'first', clickable: 'true' } }], }); - const snapshot = await snapshotHarmony(DEVICE); + const snapshot = await snapshotHarmony(hdc, DEVICE); assert.equal(snapshot.truncated, undefined); assert.deepEqual( @@ -128,4 +126,14 @@ test('snapshotHarmony pulls a uitest layout and reports its analysis', async () ['Application', 'first'], ); assert.deepEqual(snapshot.analysis, { rawNodeCount: 2, maxDepth: 1 }); + // Dump, pull, then cleanup: all three on the one target. + assert.deepEqual( + hdc.calls.map((call) => [call.kind, call.target, call.args[0]]), + [ + ['runShell', 'harmony-1', 'uitest'], + ['run', 'harmony-1', 'file'], + ['runShell', 'harmony-1', 'rm'], + ['runShell', 'harmony-1', 'hidumper'], + ], + ); }); diff --git a/packages/platform-harmonyos/src/__tests__/tmp-dir.ts b/packages/platform-harmonyos/src/__tests__/tmp-dir.ts deleted file mode 100644 index cc7cb65b07..0000000000 --- a/packages/platform-harmonyos/src/__tests__/tmp-dir.ts +++ /dev/null @@ -1,14 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; - -/** - * Creates a fresh scratch directory for one test. Cleanup is automatic: the - * unit suite redirects TMPDIR to a per-run directory (scripts/vitest-tmpdir-global-setup.ts) - * that gets removed in one recursive rm after every worker finishes, so - * individual tests never need their own afterEach/afterAll for this. - */ -// fallow-ignore-next-line code-duplication -export function mkdtempForTestSync(prefix: string): string { - return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); -} diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index d330c18674..7380907c4c 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -1,8 +1,8 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { ShellWord } from '@agent-device/kernel/device-shell'; import { AppError } from '@agent-device/kernel/errors'; -import { runCmd } from '@agent-device/host-kit/command'; -import { runHarmonyShell } from './hdc.ts'; +import type { HarmonyCommandRunner } from './command-host.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; import { invalidateHarmonyGestureViewport } from './snapshot.ts'; export function parseHarmonyBundleList(rawOutput: string): string[] { @@ -43,10 +43,11 @@ interface HarmonyAppListOptions { /** Reads the bundle identity embedded in a signed HAP archive. */ export async function resolveHarmonyArchiveBundleName( + commands: HarmonyCommandRunner, archivePath: string, signal?: AbortSignal, ): Promise { - const result = await runCmd('unzip', ['-p', archivePath, 'module.json'], { + const result = await commands.run('unzip', ['-p', archivePath, 'module.json'], { allowFailure: true, timeoutMs: 15_000, signal, @@ -88,12 +89,13 @@ function parseHarmonyBundleDump(rawOutput: string): HarmonyBundleDump | undefine } export async function listHarmonyApps( + hdc: HarmonyHdcRunner, device: DeviceInfo, filter: 'all' | 'user-installed', options: HarmonyAppListOptions = {}, ): Promise> { if (filter === 'all') { - const result = await runHarmonyShell(device, ['bm', 'dump', '-a'], { + const result = await hdc.runShell(device, ['bm', 'dump', '-a'], { timeoutMs: 15_000, signal: options.signal, }); @@ -107,12 +109,17 @@ export async function listHarmonyApps( ); const signal = combineHarmonySignals(options.signal, deadlineController.signal); try { - const result = await runHarmonyShell(device, ['bm', 'dump', '-a'], { + const result = await hdc.runShell(device, ['bm', 'dump', '-a'], { timeoutMs: 15_000, signal, }); const packages = parseHarmonyBundleList(result.stdout); - const userInstalledPackages = await listHarmonyUserInstalledPackages(device, packages, signal); + const userInstalledPackages = await listHarmonyUserInstalledPackages( + hdc, + device, + packages, + signal, + ); return harmonyAppEntries(userInstalledPackages); } catch (error) { if (deadlineController.signal.aborted) { @@ -138,6 +145,7 @@ function harmonyAppEntries(packages: string[]): Array<{ package: string; name: s } async function listHarmonyUserInstalledPackages( + hdc: HarmonyHdcRunner, device: DeviceInfo, packages: string[], parentSignal: AbortSignal | undefined, @@ -157,7 +165,7 @@ async function listHarmonyUserInstalledPackages( if (packageIndex >= packages.length) return; const bundleName = packages[packageIndex]; if (!bundleName) return; - const result = await runHarmonyShell(device, ['bm', 'dump', '-n', bundleName], { + const result = await hdc.runShell(device, ['bm', 'dump', '-n', bundleName], { timeoutMs: 15_000, signal, }); @@ -212,6 +220,7 @@ function requireHarmonyAbilityName(ability: string): void { } export async function openHarmonyApp( + hdc: HarmonyHdcRunner, device: DeviceInfo, bundleId: string, options?: { activity?: string; signal?: AbortSignal }, @@ -221,7 +230,7 @@ export async function openHarmonyApp( ? { ability: options.activity } : parseHarmonyLaunchTarget( ( - await runHarmonyShell(device, ['bm', 'dump', '-n', bundleId], { + await hdc.runShell(device, ['bm', 'dump', '-n', bundleId], { signal: options?.signal, timeoutMs: 15_000, }) @@ -238,7 +247,7 @@ export async function openHarmonyApp( } const words: ShellWord[] = ['aa', 'start', '-a', launchTarget.ability, '-b', bundleId]; if (launchTarget.module) words.push('-m', launchTarget.module); - const result = await runHarmonyShell(device, words, { signal: options?.signal }); + const result = await hdc.runShell(device, words, { signal: options?.signal }); if (!result.stdout.includes('start ability successfully')) { throw new AppError('COMMAND_FAILED', `Failed to start ${bundleId}`, { details: { output: result.stdout.trim() }, @@ -247,7 +256,11 @@ export async function openHarmonyApp( invalidateHarmonyGestureViewport(device); } -export async function closeHarmonyApp(device: DeviceInfo, bundleId: string): Promise { - await runHarmonyShell(device, ['aa', 'force-stop', bundleId]); +export async function closeHarmonyApp( + hdc: HarmonyHdcRunner, + device: DeviceInfo, + bundleId: string, +): Promise { + await hdc.runShell(device, ['aa', 'force-stop', bundleId]); invalidateHarmonyGestureViewport(device); } diff --git a/packages/platform-harmonyos/src/app-state.ts b/packages/platform-harmonyos/src/app-state.ts index f655c06045..bdbb19c68e 100644 --- a/packages/platform-harmonyos/src/app-state.ts +++ b/packages/platform-harmonyos/src/app-state.ts @@ -1,14 +1,15 @@ import { AppError } from '@agent-device/kernel/errors'; import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { HarmonyHdcRunner } from './hdc.ts'; export async function readHarmonyAppState( + hdc: HarmonyHdcRunner, device: DeviceInfo, signal: AbortSignal, ): Promise { signal.throwIfAborted(); - const { runHarmonyShell } = await import('./hdc.ts'); - const result = await runHarmonyShell(device, ['aa', 'dump', '-l'], { + const result = await hdc.runShell(device, ['aa', 'dump', '-l'], { timeoutMs: 15_000, signal, }); diff --git a/packages/platform-harmonyos/src/command-host.ts b/packages/platform-harmonyos/src/command-host.ts new file mode 100644 index 0000000000..1a867c15b6 --- /dev/null +++ b/packages/platform-harmonyos/src/command-host.ts @@ -0,0 +1,116 @@ +import path from 'node:path'; +import type { PlatformHost } from 'agent-device/plugins'; + +/** What the host answered a command: its streams and its exit code. */ +export type HarmonyCommandResult = Awaited>; + +export type HarmonyRunOptions = Readonly<{ + allowFailure?: boolean; + timeoutMs?: number; + signal?: AbortSignal; +}>; + +/** + * The plugin's route to host commands, bound to the `PlatformHost` the core handed `setup()`. The + * core owns executable resolution, the spawn environment, and the exec trace, so a `--debug` log + * shows what this family ran under its request id. + * + * Every spawn and every toolchain 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. Only host-kit *types* are imported here, which cost + * the bundle nothing. + * + * Each command is launched with the documented HarmonyOS toolchain roots prepended to `PATH`, so this + * family resolves the same HDC an interactive shell does while the core names no HarmonyOS + * configuration. + */ +export type HarmonyCommandRunner = Readonly<{ + /** `executable` is an absolute path from a configured root, or a name the host `PATH` resolves. */ + run( + executable: string, + args: readonly string[], + options?: HarmonyRunOptions, + ): Promise; + /** + * HDC to spawn: an absolute path from a documented toolchain root when one carries it, else the + * bare `hdc` for the host `PATH` to resolve. Host-minted commands need the path, because the core + * builds their environment without this family's roots. + */ + resolveHdc(): Promise; + /** True when a documented root carries an executable HDC, so no `PATH` lookup is needed. */ + toolchainHdc(): Promise; +}>; + +/** + * Binds the host the plugin was set up with. Toolchain roots are probed per command, so tooling + * installed while a daemon runs is picked up without a restart. + */ +export function createHarmonyCommandRunner(host: PlatformHost): HarmonyCommandRunner { + const env = host.env; + const isExecutable = (candidate: string) => host.isFileExecutable(candidate); + return Object.freeze({ + run: async (executable, args, options) => + await host.runCommand(executable, [...args], { + ...options, + env: await harmonySpawnEnvironment(env, isExecutable), + }), + resolveHdc: async () => (await await harmonyToolchainHdc(env, isExecutable)) ?? 'hdc', + toolchainHdc: async () => await harmonyToolchainHdc(env, isExecutable), + }); +} + +/** + * 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 + * core naming HarmonyOS configuration and without this plugin reading the host environment or the + * filesystem itself (ADR 0019): both come from the host it was set up with. + */ +async function harmonySpawnEnvironment( + env: Readonly>, + isExecutable: (candidate: string) => Promise, +): Promise>> { + const root = await harmonyToolchainRoot(env, isExecutable); + const currentEntries = (env.PATH ?? '').split(path.delimiter).filter(Boolean); + const entries = root + ? [root, ...currentEntries.filter((entry) => entry !== root)] + : currentEntries; + const spawnEnv: Record = {}; + for (const [key, value] of Object.entries(env)) { + if (value !== undefined) spawnEnv[key] = value; + } + spawnEnv.PATH = entries.join(path.delimiter); + return spawnEnv; +} + +/** HDC from the first documented root that carries it, if any. */ +async function harmonyToolchainHdc( + env: Readonly>, + isExecutable: (candidate: string) => Promise, +): Promise { + const root = await harmonyToolchainRoot(env, isExecutable); + return root ? path.join(root, 'hdc') : undefined; +} + +/** + * The first documented root holding an executable HDC, checked in the documented order so + * `HDC_SDK_PATH` wins over `DEVECO_SDK_HOME`, which wins over the command-line tools home. + */ +async function harmonyToolchainRoot( + env: Readonly>, + isExecutable: (candidate: string) => Promise, +): Promise { + const roots = [ + env.HDC_SDK_PATH, + env.DEVECO_SDK_HOME + ? path.join(env.DEVECO_SDK_HOME, 'default', 'openharmony', 'toolchains') + : undefined, + env.HARMONYOS_COMMAND_LINE_TOOLS + ? path.join(env.HARMONYOS_COMMAND_LINE_TOOLS, 'sdk', 'default', 'openharmony', 'toolchains') + : undefined, + ].filter((value): value is string => Boolean(value?.trim())); + for (const root of roots) { + if (await isExecutable(path.join(root, 'hdc'))) return root; + } + return undefined; +} diff --git a/packages/platform-harmonyos/src/deployment/runtime.test.ts b/packages/platform-harmonyos/src/deployment/runtime.test.ts index f28c18c6c8..84652a5d1a 100644 --- a/packages/platform-harmonyos/src/deployment/runtime.test.ts +++ b/packages/platform-harmonyos/src/deployment/runtime.test.ts @@ -1,9 +1,7 @@ -import { expect, test, vi } from 'vitest'; -import type { - HostCommandRunner, - HostCommandResult, -} from '@agent-device/contracts/platform-runtime-host'; +import { expect, test } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { createHarmonyHostStub } from '../toolbox.fixtures.ts'; +import type { HarmonyCommandResult } from '../command-host.ts'; import { createHarmonyAppDeploymentOperations, harmonyAppDeploymentFacts } from './runtime.ts'; const device: DeviceInfo = { @@ -40,19 +38,22 @@ test.each([ ); test('exposes HarmonyOS deployApp and uninstallApp after fact admission', async () => { - const run = vi.fn(async (request: { executable: string; args: readonly string[] }) => ({ - stdout: - request.executable === 'unzip' - ? '{"app":{"bundleName":"com.example.app"}}' - : request.args.includes('dump') - ? '{"hapModuleInfos":[{"mainElementName":"MainAbility","moduleName":"entry"}]}' - : '', - stderr: '', - exitCode: 0, - })); - const commands = { which: async () => undefined, run } as HostCommandRunner; + const stub = createHarmonyHostStub({ + respond: (executable, args) => ({ + stdout: + executable === 'unzip' + ? '{"app":{"bundleName":"com.example.app"}}' + : args.includes('dump') + ? '{"hapModuleInfos":[{"mainElementName":"MainAbility","moduleName":"entry"}]}' + : '', + }), + }); const signal = new AbortController().signal; - const operations = createHarmonyAppDeploymentOperations({ commands, device, signal }); + const operations = createHarmonyAppDeploymentOperations({ + toolbox: stub.toolbox, + device, + signal, + }); await operations.deployApp?.({ app: 'com.example.app', appPath: '/tmp/app.hap', @@ -63,17 +64,18 @@ test('exposes HarmonyOS deployApp and uninstallApp after fact admission', async appPath: '/tmp/app.hap', replaceExisting: true, }); - expect(run).toHaveBeenCalledWith( - expect.objectContaining({ - executable: 'hdc', - args: ['-t', device.id, 'install', '-r', '/tmp/app.hap'], - }), - signal, - ); - expect(run).toHaveBeenCalledWith( - expect.objectContaining({ - executable: 'hdc', - args: [ + + // Every spawn names the executable and argv the plugin built, on the host it was set up with. + // The second deploy replaces an existing bundle, which additionally resolves the launch target. + expect(stub.commands.map((command) => [command.executable, command.args])).toEqual([ + ['unzip', ['-p', '/tmp/app.hap', 'module.json']], + ['hdc', ['-t', device.id, 'install', '-r', '/tmp/app.hap']], + ['unzip', ['-p', '/tmp/app.hap', 'module.json']], + ['hdc', ['-t', device.id, 'install', '-r', '/tmp/app.hap']], + ['hdc', ['-t', device.id, 'shell', 'bm', 'dump', '-n', 'com.example.app']], + [ + 'hdc', + [ '-t', device.id, 'shell', @@ -86,162 +88,178 @@ test('exposes HarmonyOS deployApp and uninstallApp after fact admission', async '-a', 'MainAbility', ], - }), - signal, - ); + ], + ]); + expect(stub.commands.every((command) => command.signal === signal)).toBe(true); expect(operations).not.toHaveProperty('materializeAppSource'); expect( createHarmonyAppDeploymentOperations({ - commands, + toolbox: stub.toolbox, device: { ...device, kind: 'simulator' }, signal, }), ).toEqual({}); }); -/** Answers each call in order; the last answer repeats when a script runs past its end. */ -function scriptAnswers(answers: readonly HostCommandResult[]) { - let next = 0; - return async (): Promise => answers[Math.min(next++, answers.length - 1)]!; +/** The answers the uninstall tests need, keyed by what the plugin asked the device. */ +/** + * Answers each inventory read in order; the last answer repeats when the script runs past its end, + * which is how a test keeps the bundle present after the uninstall attempt. + */ +function uninstallResponder(answers: { + inventories?: readonly (string | Partial)[]; + uninstall?: Partial; +}) { + const inventories = [...(answers.inventories ?? [])]; + let reads = 0; + return (_executable: string, args: readonly string[]) => { + if (args.includes('dump')) { + const inventory = inventories[Math.min(reads++, inventories.length - 1)] ?? ''; + return typeof inventory === 'string' ? { stdout: inventory } : inventory; + } + if (args.includes('uninstall')) return answers.uninstall ?? {}; + return {}; + }; } -const bundleInventory = (entries: string[]): HostCommandResult => ({ - stdout: [...entries, ''].join('\n'), - stderr: '', - exitCode: 0, -}); - -const uninstallAnswer: HostCommandResult = { - stdout: 'uninstall bundle successfully.', - stderr: '', - exitCode: 0, -}; - /** `bm dump -a` inventory answers: one bundle name per line, the shared parseHarmonyBundleList shape. */ -const installedInventory = bundleInventory(['com.example.other', 'com.example.app']); -const absentInventory = bundleInventory(['com.example.other']); +const installedInventory = 'com.example.other\ncom.example.app\n'; +const absentInventory = 'com.example.other\n'; /** * Shapes recorded on physical hardware: bm prints its per-bundle failures into * stdout while the host exit code stays 0, so this answer is an unknown read, * never a proof of absence. */ -const unknownInventoryRead: HostCommandResult = { +const unknownInventoryRead = { stdout: 'error: failed to get information and the parameters may be wrong.', stderr: '', exitCode: 0, }; test('uninstall removes an installed HarmonyOS bundle through bm uninstall', async () => { - const run = vi.fn(scriptAnswers([installedInventory, uninstallAnswer, absentInventory])); - const commands = { which: async () => undefined, run } as HostCommandRunner; + const stub = createHarmonyHostStub({ + respond: uninstallResponder({ + inventories: [installedInventory, absentInventory], + uninstall: { stdout: 'uninstall bundle successfully.' }, + }), + }); const signal = new AbortController().signal; - const operations = createHarmonyAppDeploymentOperations({ commands, device, signal }); + const operations = createHarmonyAppDeploymentOperations({ + toolbox: stub.toolbox, + device, + signal, + }); await expect(operations.uninstallApp?.({ app: 'com.example.app' })).resolves.toEqual({ wasInstalled: true, packageName: 'com.example.app', }); - expect(run).toHaveBeenCalledTimes(3); - expect(run).toHaveBeenNthCalledWith( - 1, - expect.objectContaining({ - executable: 'hdc', - args: ['-t', device.id, 'shell', 'bm', 'dump', '-a'], - }), - signal, - ); - expect(run).toHaveBeenNthCalledWith( - 2, - expect.objectContaining({ - executable: 'hdc', - args: ['-t', device.id, 'shell', 'bm', 'uninstall', '-n', 'com.example.app'], - }), - signal, - ); - expect(run).toHaveBeenNthCalledWith( - 3, - expect.objectContaining({ - executable: 'hdc', - args: ['-t', device.id, 'shell', 'bm', 'dump', '-a'], - }), - signal, - ); + expect(stub.commands.map((command) => command.args)).toEqual([ + ['-t', device.id, 'shell', 'bm', 'dump', '-a'], + ['-t', device.id, 'shell', 'bm', 'uninstall', '-n', 'com.example.app'], + ['-t', device.id, 'shell', 'bm', 'dump', '-a'], + ]); }); test('uninstall reports an absent bundle without uninstalling', async () => { - const run = vi.fn(scriptAnswers([absentInventory])); - const commands = { which: async () => undefined, run } as HostCommandRunner; + const stub = createHarmonyHostStub({ + respond: uninstallResponder({ inventories: [absentInventory] }), + }); const signal = new AbortController().signal; - const operations = createHarmonyAppDeploymentOperations({ commands, device, signal }); + const operations = createHarmonyAppDeploymentOperations({ + toolbox: stub.toolbox, + device, + signal, + }); await expect(operations.uninstallApp?.({ app: 'com.example.app' })).resolves.toEqual({ wasInstalled: false, }); - expect(run).toHaveBeenCalledTimes(1); - expect(run).not.toHaveBeenCalledWith( - expect.objectContaining({ args: expect.arrayContaining(['uninstall']) }), - signal, - ); + expect(stub.commands.map((command) => command.args)).toEqual([ + ['-t', device.id, 'shell', 'bm', 'dump', '-a'], + ]); }); test('uninstall refuses to claim removal when the inventory still lists the bundle', async () => { - const run = vi.fn(scriptAnswers([installedInventory, uninstallAnswer, installedInventory])); - const commands = { which: async () => undefined, run } as HostCommandRunner; + const stub = createHarmonyHostStub({ + respond: uninstallResponder({ + inventories: [installedInventory], + uninstall: { stdout: 'uninstall bundle successfully.' }, + }), + }); const signal = new AbortController().signal; - const operations = createHarmonyAppDeploymentOperations({ commands, device, signal }); + const operations = createHarmonyAppDeploymentOperations({ + toolbox: stub.toolbox, + device, + signal, + }); await expect(operations.uninstallApp?.({ app: 'com.example.app' })).rejects.toMatchObject({ code: 'COMMAND_FAILED', message: 'com.example.app is still installed after bm uninstall', details: { stdout: 'uninstall bundle successfully.' }, }); - expect(run).toHaveBeenCalledTimes(3); + expect(stub.commands.length).toBe(3); }); test('uninstall refuses an inventory read it cannot interpret', async () => { - const run = vi.fn(scriptAnswers([unknownInventoryRead])); - const commands = { which: async () => undefined, run } as HostCommandRunner; + const stub = createHarmonyHostStub({ + respond: uninstallResponder({ inventories: [unknownInventoryRead] }), + }); const signal = new AbortController().signal; - const operations = createHarmonyAppDeploymentOperations({ commands, device, signal }); + const operations = createHarmonyAppDeploymentOperations({ + toolbox: stub.toolbox, + device, + signal, + }); await expect(operations.uninstallApp?.({ app: 'com.example.app' })).rejects.toMatchObject({ code: 'COMMAND_FAILED', message: 'Could not read the installed bundle inventory', }); - expect(run).toHaveBeenCalledTimes(1); - expect(run).not.toHaveBeenCalledWith( - expect.objectContaining({ args: expect.arrayContaining(['uninstall']) }), - signal, - ); + expect(stub.commands.length).toBe(1); + expect(stub.commands.some((command) => command.args.includes('uninstall'))).toBe(false); }); test('uninstall refuses to claim removal when the inventory probe exits non-zero', async () => { - const run = vi.fn( - scriptAnswers([ - { stdout: '[Fail]Device not connected', stderr: '[Fail]Device not connected', exitCode: 1 }, - ]), - ); - const commands = { which: async () => undefined, run } as HostCommandRunner; + const stub = createHarmonyHostStub({ + respond: uninstallResponder({ + inventories: [ + { + stdout: '[Fail]Device not connected', + stderr: '[Fail]Device not connected', + exitCode: 1, + }, + ], + }), + }); const signal = new AbortController().signal; - const operations = createHarmonyAppDeploymentOperations({ commands, device, signal }); + const operations = createHarmonyAppDeploymentOperations({ + toolbox: stub.toolbox, + device, + signal, + }); await expect(operations.uninstallApp?.({ app: 'com.example.app' })).rejects.toMatchObject({ code: 'COMMAND_FAILED', message: 'Could not read the installed bundle inventory', details: { processExitError: true, exitCode: 1 }, }); - expect(run).toHaveBeenCalledTimes(1); + expect(stub.commands.length).toBe(1); }); test('uninstall refuses a blank bundle name', async () => { - const run = vi.fn(); - const commands = { which: async () => undefined, run } as HostCommandRunner; + const stub = createHarmonyHostStub(); const signal = new AbortController().signal; - const operations = createHarmonyAppDeploymentOperations({ commands, device, signal }); + const operations = createHarmonyAppDeploymentOperations({ + toolbox: stub.toolbox, + device, + signal, + }); await expect(operations.uninstallApp?.({ app: ' ' })).rejects.toMatchObject({ code: 'INVALID_ARGS', }); - expect(run).not.toHaveBeenCalled(); + expect(stub.commands.length).toBe(0); }); diff --git a/packages/platform-harmonyos/src/deployment/runtime.ts b/packages/platform-harmonyos/src/deployment/runtime.ts index 4f78c83ec3..ad13e8ee0f 100644 --- a/packages/platform-harmonyos/src/deployment/runtime.ts +++ b/packages/platform-harmonyos/src/deployment/runtime.ts @@ -5,14 +5,18 @@ import type { AppUninstallInput, AppUninstallResult, } from '@agent-device/contracts/app-deployment-runtime'; -import type { HostCommandRunner } from '@agent-device/contracts/platform-runtime-host'; import type { RuntimeOperationFact } from '@agent-device/contracts/platform-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { deviceShellArgv, type ShellWord } from '@agent-device/kernel/device-shell'; import { AppError } from '@agent-device/kernel/errors'; -import { execFailureDetails } from '@agent-device/host-kit/command'; -import { parseHarmonyBundleList, parseHarmonyLaunchTarget } from '../app-lifecycle.ts'; +import { + parseHarmonyBundleList, + parseHarmonyLaunchTarget, + resolveHarmonyArchiveBundleName, +} from '../app-lifecycle.ts'; import { setTimeout as sleep } from 'node:timers/promises'; +import type { HarmonyToolbox } from '../toolbox.ts'; +import type { HarmonyHdcRunner } from '../hdc.ts'; +import type { HarmonyCommandResult } from '../command-host.ts'; const available = Object.freeze({ available: true } as const); const unsupportedKind = Object.freeze({ @@ -43,29 +47,30 @@ export function harmonyAppDeploymentFacts(device: DeviceInfo): Readonly<{ } export function createHarmonyAppDeploymentOperations(params: { - commands: HostCommandRunner; + toolbox: HarmonyToolbox; device: DeviceInfo; signal: AbortSignal; }): Partial { const facts = harmonyAppDeploymentFacts(params.device); + const { toolbox, device, signal } = params; return Object.freeze({ ...(facts.deployApp.available ? { deployApp: async (input: AppDeploymentInput) => - await deployHarmonyApp(params.commands, params.device, input, params.signal), + await deployHarmonyApp(toolbox, device, input, signal), } : {}), ...(facts.uninstallApp.available ? { uninstallApp: async (input: AppUninstallInput) => - await uninstallHarmonyApp(params.commands, params.device, input, params.signal), + await uninstallHarmonyApp(toolbox.hdc, device, input, signal), } : {}), }); } async function uninstallHarmonyApp( - commands: HostCommandRunner, + hdc: HarmonyHdcRunner, device: DeviceInfo, input: AppUninstallInput, signal: AbortSignal, @@ -76,16 +81,11 @@ async function uninstallHarmonyApp( hint: 'Pass the bundle name reported by bm dump, such as com.example.app.', }); } - if (!(await readBundleInventory(commands, device, signal)).includes(bundleId)) { + if (!(await readBundleInventory(hdc, device, signal)).includes(bundleId)) { return { wasInstalled: false }; } - const uninstall = await runHdcShell( - commands, - device, - ['bm', 'uninstall', '-n', bundleId], - signal, - ); - const remaining = await readBundleInventory(commands, device, signal); + const uninstall = await hdc.runShell(device, ['bm', 'uninstall', '-n', bundleId], { signal }); + const remaining = await readBundleInventory(hdc, device, signal); if (remaining.includes(bundleId)) { // bm prints its verdict into stdout at exit code 0, so only an inventory that no // longer lists the bundle proves the removal. @@ -109,19 +109,20 @@ async function uninstallHarmonyApp( * system bundles. */ async function readBundleInventory( - commands: HostCommandRunner, + hdc: HarmonyHdcRunner, device: DeviceInfo, signal: AbortSignal, ): Promise { - const inventory = await runHdcShell(commands, device, ['bm', 'dump', '-a'], signal, { + const inventory = await hdc.runShell(device, ['bm', 'dump', '-a'], { allowFailure: true, timeoutMs: 15_000, + signal, }); if (inventory.exitCode !== 0) { throw new AppError( 'COMMAND_FAILED', 'Could not read the installed bundle inventory', - execFailureDetails(inventory), + commandFailureDetails(inventory), ); } const bundles = parseHarmonyBundleList(inventory.stdout); @@ -141,56 +142,38 @@ async function readBundleInventory( } async function deployHarmonyApp( - commands: HostCommandRunner, + toolbox: HarmonyToolbox, device: DeviceInfo, input: AppDeploymentInput, signal: AbortSignal, ): Promise { - const bundleId = (await resolveBundleName(commands, input.appPath, signal)) ?? input.app.trim(); + const bundleId = + (await resolveHarmonyArchiveBundleName(toolbox.commands, input.appPath, signal)) ?? + input.app.trim(); if (!bundleId) { throw new AppError('INVALID_ARGS', 'Could not determine the bundle name from the HAP archive', { hint: 'Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.', }); } - await runHdc(commands, device, ['install', '-r', input.appPath], signal, 180_000); + await toolbox.hdc.run(device, ['install', '-r', input.appPath], { + timeoutMs: 180_000, + signal, + }); if (input.replaceExisting) { // HDC returns after transfer; physical devices can still be replacing the running bundle. await sleep(1_000, undefined, { signal }); - await openHarmonyApp(commands, device, bundleId, signal); + await openHarmonyApp(toolbox.hdc, device, bundleId, signal); } return { packageName: bundleId, launchTarget: bundleId }; } -async function resolveBundleName( - commands: HostCommandRunner, - archivePath: string, - signal: AbortSignal, -): Promise { - const result = await commands.run( - { - executable: 'unzip', - args: ['-p', archivePath, 'module.json'], - allowFailure: true, - timeoutMs: 15_000, - }, - signal, - ); - if (result.exitCode !== 0 || result.stdout.trim().length === 0) return undefined; - try { - const manifest = JSON.parse(result.stdout) as { app?: { bundleName?: string } }; - return manifest.app?.bundleName?.trim() || undefined; - } catch { - return undefined; - } -} - async function openHarmonyApp( - commands: HostCommandRunner, + hdc: HarmonyHdcRunner, device: DeviceInfo, bundleId: string, signal: AbortSignal, ): Promise { - const dump = await runHdcShell(commands, device, ['bm', 'dump', '-n', bundleId], signal); + const dump = await hdc.runShell(device, ['bm', 'dump', '-n', bundleId], { signal }); const target = parseHarmonyLaunchTarget(dump.stdout); if (!target) { throw new AppError( @@ -201,8 +184,7 @@ async function openHarmonyApp( }, ); } - await runHdcShell( - commands, + await hdc.runShell( device, [ 'aa', @@ -213,37 +195,21 @@ async function openHarmonyApp( '-a', target.ability, ], - signal, + { signal }, ); } -async function runHdc( - commands: HostCommandRunner, - device: DeviceInfo, - args: readonly string[], - signal: AbortSignal, - timeoutMs = 15_000, -) { - return await commands.run( - { executable: 'hdc', args: ['-t', device.id, ...args], timeoutMs }, - signal, - ); -} - -async function runHdcShell( - commands: HostCommandRunner, - device: DeviceInfo, - words: readonly ShellWord[], - signal: AbortSignal, - options: Readonly<{ allowFailure?: boolean; timeoutMs?: number }> = {}, -) { - return await commands.run( - { - executable: 'hdc', - args: deviceShellArgv('hdc', 'shell', words, ['-t', device.id]), - timeoutMs: options.timeoutMs ?? 15_000, - allowFailure: options.allowFailure, - }, - signal, - ); +/** + * The host-kit's exec failure details, shaped for the host command result this plugin's runs answer + * with: `processExitError` is what makes `normalizeError` append the stderr excerpt. The plugin + * keeps the flag rather than the host kit's helper, because importing the host kit's command module + * at runtime would give the bundle a second, unscoped command scope. + */ +function commandFailureDetails(result: HarmonyCommandResult): Readonly> { + return { + stdout: result.stdout, + stderr: result.stderr, + exitCode: result.exitCode, + processExitError: true, + }; } diff --git a/packages/platform-harmonyos/src/doctor.ts b/packages/platform-harmonyos/src/doctor.ts index e8a34d494d..709e53c7b6 100644 --- a/packages/platform-harmonyos/src/doctor.ts +++ b/packages/platform-harmonyos/src/doctor.ts @@ -1,8 +1,19 @@ import type { DoctorCheck } from '@agent-device/contracts/observability'; -import { commandFirstLine } from '@agent-device/provision-kit/toolchain-probe'; +import type { HarmonyCommandRunner } from './command-host.ts'; -export async function harmonyToolchainCheck(): Promise { - const versionLine = await commandFirstLine('hdc', ['-v']); +const HARMONY_TOOLCHAIN_PROBE_TIMEOUT_MS = 3_000; + +/** + * The toolchain row `doctor --platform harmonyos` reports. The probe runs over the plugin's host + * command runner, so the version it reads is the HDC the plugin would spawn — a root outside the + * host `PATH` still answers its own version. + */ +export async function harmonyToolchainCheck(commands: HarmonyCommandRunner): Promise { + const hdc = await commands.resolveHdc(); + const result = await commands + .run(hdc, ['-v'], { allowFailure: true, timeoutMs: HARMONY_TOOLCHAIN_PROBE_TIMEOUT_MS }) + .catch(() => undefined); + const versionLine = result?.exitCode === 0 ? firstOutputLine(result.stdout) : undefined; if (!versionLine) { return { id: 'toolchain', @@ -20,3 +31,11 @@ export async function harmonyToolchainCheck(): Promise { evidence: { hdcVersion: versionLine }, }; } + +/** The first non-empty line of a probe's output, the shape every toolchain version prints. */ +function firstOutputLine(output: string): string | undefined { + return output + .split('\n') + .map((line) => line.trim()) + .find(Boolean); +} diff --git a/packages/platform-harmonyos/src/hdc.ts b/packages/platform-harmonyos/src/hdc.ts index e2b7a1dd6b..f2915d2358 100644 --- a/packages/platform-harmonyos/src/hdc.ts +++ b/packages/platform-harmonyos/src/hdc.ts @@ -1,70 +1,107 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; +import path from 'node:path'; import { assertDeviceShellArgv, deviceShellArgv, type ShellWord, } from '@agent-device/kernel/device-shell'; -import path from 'node:path'; -import { - isExecutablePath, - runCmd, - type ExecOptions, - type ExecResult, -} from '@agent-device/host-kit/command'; - -export type HarmonyHdcOptions = Pick< - ExecOptions, - 'allowFailure' | 'timeoutMs' | 'binaryStdout' | 'signal' ->; +import { AppError, asAppError } from '@agent-device/kernel/errors'; +import type { + HarmonyCommandResult, + HarmonyCommandRunner, + HarmonyRunOptions, +} from './command-host.ts'; export const DEFAULT_HARMONY_HDC_TIMEOUT_MS = 15_000; +export type HarmonyHdcOptions = HarmonyRunOptions; + +/** + * The HDC route the whole family takes: one launcher, with each call scoped to exactly one + * discovered target. Built once from the plugin's host command runner, so HDC is spawned by the + * daemon host that owns the request's environment and exec trace, never by this bundle's own copy + * of the host kit. + */ +export type HarmonyHdcRunner = Readonly<{ + /** HDC from a documented toolchain root, or the bare name for the host `PATH` to resolve. */ + executable(): Promise; + /** Runs HDC with no target selection, for the host-level command discovery starts from. */ + launch(args: readonly string[], options?: HarmonyHdcOptions): Promise; + /** Runs a non-shell HDC command. A `shell` argv is refused here; it belongs to {@link runShell}. */ + run( + device: Pick, + args: readonly string[], + options?: HarmonyHdcOptions, + ): Promise; + /** Runs `hdc shell `; every word is escaped for HDC's double-quoted transport. */ + runShell( + device: Pick, + words: readonly ShellWord[], + options?: HarmonyHdcOptions, + ): Promise; +}>; + /** - * Runs a non-shell HDC command scoped to exactly one discovered HarmonyOS target. A `shell` - * argv is refused here; it belongs to {@link runHarmonyShell}. + * Builds the family's HDC route. The executable is resolved per call, so a toolchain installed + * after the daemon started is used without a restart. A spawn the host cannot start arrives as the + * host's typed `TOOL_MISSING` rejection, which every HDC command here answers with the curated + * missing-toolchain error naming the documented roots. */ -export async function runHarmonyHdc( - device: Pick, - args: readonly string[], - options?: HarmonyHdcOptions, -): Promise { - assertDeviceShellArgv(args, 'hdc'); - return await runCmd('hdc', ['-t', device.id, ...args], { - timeoutMs: DEFAULT_HARMONY_HDC_TIMEOUT_MS, - ...options, +export function createHarmonyHdcRunner(commands: HarmonyCommandRunner): HarmonyHdcRunner { + const spawn = async (args: readonly string[], options?: HarmonyHdcOptions) => { + const executable = await commands.resolveHdc(); + try { + return await commands.run(executable, args, { + timeoutMs: DEFAULT_HARMONY_HDC_TIMEOUT_MS, + ...options, + }); + } catch (error) { + throw missingHdcError(executable, error); + } + }; + return Object.freeze({ + executable: async () => await commands.resolveHdc(), + launch: async (args, options) => await spawn(targetArgv(args), options), + run: async (device, args, options) => + await spawn(targetArgv(args, deviceShellPrefix(device)), options), + // Its argv is already minted by deviceShellArgv, so it is not checked again. + runShell: async (device, words, options) => + await spawn(deviceShellArgv('hdc', 'shell', words, deviceShellPrefix(device)), options), }); } -/** Runs `hdc shell ` for the target; every word is escaped for HDC's double-quoted transport. */ -export async function runHarmonyShell( - device: Pick, - words: readonly ShellWord[], - options?: HarmonyHdcOptions, -): Promise { - return await runHarmonyHdc(device, deviceShellArgv('hdc', 'shell', words), options); +const MISSING_HDC_HINT = + 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH or set HDC_SDK_PATH.'; + +/** + * The curated missing-toolchain error for the host's typed `TOOL_MISSING` rejection of an HDC spawn + * (the host rejects a spawn it cannot start rather than reporting an unusable exit code). Any other + * failure passes through untouched, so a canceled or timed-out command keeps its own verdict. + */ +function missingHdcError(executable: string, error: unknown): unknown { + const failure = asAppError(error); + if (failure.code !== 'TOOL_MISSING') return error; + const location = path.isAbsolute(executable) ? `at ${executable}` : 'in PATH'; + return new AppError( + 'TOOL_MISSING', + `hdc not found ${location}`, + { hint: MISSING_HDC_HINT }, + error, + ); +} + +/** The target selection HDC addresses one device with. */ +function deviceShellPrefix(device: Pick): readonly string[] { + return ['-t', device.id]; } /** - * DevEco's command-line tools do not amend PATH for non-interactive processes. - * Honor the documented roots so the daemon sees the same HDC binary as a shell. + * HDC argv for one discovered target: the target selection ahead of the command. A `shell` argv + * reaching this point would be quoted twice by HDC, so it is refused — shell words take + * {@link HarmonyHdcRunner.runShell}, which mints its argv with {@link deviceShellArgv}. */ -export async function ensureHarmonyToolchainPathConfigured(env: NodeJS.ProcessEnv): Promise { - const toolchainRoots = [ - env.HDC_SDK_PATH, - env.DEVECO_SDK_HOME - ? path.join(env.DEVECO_SDK_HOME, 'default', 'openharmony', 'toolchains') - : undefined, - env.HARMONYOS_COMMAND_LINE_TOOLS - ? path.join(env.HARMONYOS_COMMAND_LINE_TOOLS, 'sdk', 'default', 'openharmony', 'toolchains') - : undefined, - ].filter((value): value is string => Boolean(value?.trim())); - const executableRoots: string[] = []; - for (const root of toolchainRoots) { - if (await isExecutablePath(path.join(root, 'hdc'))) { - executableRoots.push(root); - } - } - if (executableRoots.length === 0) return; - const currentEntries = (env.PATH ?? '').split(path.delimiter).filter(Boolean); - env.PATH = [...new Set([...executableRoots, ...currentEntries])].join(path.delimiter); +function targetArgv(args: readonly string[], prefix: readonly string[] = []): readonly string[] { + const argv = [...prefix, ...args]; + assertDeviceShellArgv(argv, 'hdc'); + return argv; } diff --git a/packages/platform-harmonyos/src/index.test.ts b/packages/platform-harmonyos/src/index.test.ts index d321c3cb6d..0cb02577f1 100644 --- a/packages/platform-harmonyos/src/index.test.ts +++ b/packages/platform-harmonyos/src/index.test.ts @@ -1,11 +1,13 @@ import assert from 'node:assert/strict'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { HarmonyPlatformRegistration } from '@agent-device/contracts/platform-plugin'; -import type { DeviceInventoryHostFor } from '@agent-device/contracts/platform-runtime-host'; 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 path from 'node:path'; import harmonyPlatformPlugin from './index.ts'; +import { createHarmonyToolchainRoot } from './toolbox.fixtures.ts'; const HARMONY_DEVICE = { platform: 'harmonyos', @@ -16,13 +18,29 @@ const HARMONY_DEVICE = { booted: true, } satisfies DeviceInfo; +/** One command the plugin asked the host to run. */ +type HostCommand = Readonly<{ + executable: string; + args: readonly string[]; + env: PlatformHost['env'] | undefined; +}>; + /** The host the composition hands the plugin: one captured environment, no device authority. */ -function createPluginHost(env: PlatformHost['env'] = {}): PlatformHost { +function createPluginHost( + env: PlatformHost['env'] = {}, + commands: HostCommand[] = [], +): PlatformHost { return { env, cwd: '/host-cwd', stateDir: '/host-state', - runCommand: async () => ({ stdout: '', stderr: '', exitCode: 0 }), + runCommand: async (executable, args, options) => { + commands.push({ executable, args, env: options.env }); + return { stdout: '', stderr: '', exitCode: 0 }; + }, + // The real host probe: 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, emitDiagnostic, withDiagnosticTimer, }; @@ -59,75 +77,44 @@ test('setup registers the HarmonyOS modules and operations', () => { assert.equal(typeof registration.inventoryModule.loadInventory, 'function'); assert.equal(typeof registration.runtimeModule.loadRuntime, 'function'); assert.equal(typeof registration.operations.toolchainCheck, 'function'); - assert.equal(typeof registration.operations.prepareToolchain, 'function'); }); -test('setup hands the host it was set up with to the inventory module it registers', async () => { - // The plugin never reads `process.env`: the documented HarmonyOS roots reach discovery through - // the setup host only. Discovery asks the host to prepare its toolchain first, then resolves HDC - // through the roots and PATH that preparation owns, so a host without either answers its own - // missing-toolchain reason. The process environment names a different root on purpose, so an - // implementation that read it instead of the host fails here on any machine. - const originalRoots = { - HDC_SDK_PATH: process.env.HDC_SDK_PATH, - DEVECO_SDK_HOME: process.env.DEVECO_SDK_HOME, - HARMONYOS_COMMAND_LINE_TOOLS: process.env.HARMONYOS_COMMAND_LINE_TOOLS, - }; - process.env.HDC_SDK_PATH = '/process-tools/hdc'; - process.env.DEVECO_SDK_HOME = '/process-tools/deveco'; - delete process.env.HARMONYOS_COMMAND_LINE_TOOLS; - try { - const registration = setupHarmonyPlatform( - createPluginHost({ - HDC_SDK_PATH: ' /host-tools/hdc ', +test('the HarmonyOS inventory loads with no host from the core', async () => { + // The family owns its host: discovery runs over the setup host, so the core hands the inventory + // module nothing. A signature that still demanded a core host would fail here. + const registration = setupHarmonyPlatform(); + const source = await registration.inventoryModule.loadInventory(); + assert.equal(typeof source.discover, 'function'); +}); + +test('setup runs discovery on the host it was set up with, not on the process environment', async () => { + // The plugin never reads `process.env`: the documented HarmonyOS roots reach discovery through the + // setup host only. The process environment names a different root on purpose, so an implementation + // that read it instead of the host fails here on any machine. + vi.stubEnv('HDC_SDK_PATH', '/process-tools/toolchains'); + vi.stubEnv('DEVECO_SDK_HOME', '/process-tools/deveco'); + vi.stubEnv('HARMONYOS_COMMAND_LINE_TOOLS', undefined); + const hostRoot = createHarmonyToolchainRoot(); + const commands: HostCommand[] = []; + const registration = setupHarmonyPlatform( + createPluginHost( + { + HDC_SDK_PATH: hostRoot, DEVECO_SDK_HOME: '/host-tools/deveco', HARMONYOS_COMMAND_LINE_TOOLS: '', PATH: '/bin', - }), - ); - const lookedUp: string[] = []; - let prepares = 0; - const inventoryHost = { - toolchains: { - prepare: async () => { - prepares += 1; - }, - }, - commands: { - which: async (command: string) => { - lookedUp.push(command); - return undefined; - }, - run: async () => ({ stdout: '', stderr: '', exitCode: 0 }), - }, - files: { - isExecutable: async (candidate: string) => { - lookedUp.push(candidate); - return false; - }, }, - hostOs: 'darwin', - hostName: 'test-host', - } as unknown as DeviceInventoryHostFor<'harmonyos'>; + commands, + ), + ); + + const source = await registration.inventoryModule.loadInventory(); + await source.discover({}, scope); - const source = await registration.inventoryModule.loadInventory(inventoryHost); - await assert.rejects( - async () => await source.discover({}, scope), - (error: Error) => error.message === 'hdc not found in PATH', - ); - assert.equal(prepares, 1); - // Each root the setup host named is probed, trimmed, and derived; the empty root and the - // process environment's roots are not. - assert.deepEqual(lookedUp, [ - '/host-tools/hdc/hdc', - '/host-tools/deveco/default/openharmony/toolchains/hdc', - 'hdc', - ]); - } finally { - Object.assign(process.env, originalRoots); - if (originalRoots.HARMONYOS_COMMAND_LINE_TOOLS === undefined) - delete process.env.HARMONYOS_COMMAND_LINE_TOOLS; - } + // Only the host's root, which really carries an executable HDC, is spawned and prepended to PATH. + assert.equal(commands[0]?.executable, path.join(hostRoot, 'hdc')); + assert.equal(commands[0]?.env?.PATH?.split(path.delimiter)[0], hostRoot); + assert.ok(!commands[0]!.env!.PATH!.includes('/process-tools/toolchains')); }); test('setup creates the HarmonyOS interactor lazily', async () => { diff --git a/packages/platform-harmonyos/src/index.ts b/packages/platform-harmonyos/src/index.ts index aa03ea7cf8..8e3ba0ac91 100644 --- a/packages/platform-harmonyos/src/index.ts +++ b/packages/platform-harmonyos/src/index.ts @@ -1,48 +1,29 @@ -import type { PlatformContribution, PlatformHost, PlatformSetup } from 'agent-device/plugins'; +import type { PlatformContribution, PlatformHost } from 'agent-device/plugins'; import type { InventoryPlatformModule, PlatformModuleMetadata, } from '@agent-device/contracts/platform-module'; import type { PlatformRuntimeModule } from '@agent-device/contracts/platform-runtime-operations'; -import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; -import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; +import type { + HarmonyPlatformOperations, + HarmonyPlatformRegistration, +} from '@agent-device/contracts/platform-plugin'; const metadata = Object.freeze({ family: 'harmonyos', } satisfies PlatformModuleMetadata); -const runtimeModule = Object.freeze({ - ...metadata, - loadRuntime: async (host) => { - const { createHarmonyPlatformRuntime } = await import('./runtime.ts'); - return createHarmonyPlatformRuntime(host); - }, -} satisfies PlatformRuntimeModule); - /** - * Builds the inventory module from the host the plugin was set up with. The documented HarmonyOS - * toolchain roots are read there, so a daemon started with them picks them up without the core - * naming HarmonyOS configuration, and the plugin never reads `process.env` itself (ADR 0019). + * The toolbox module, resolved exactly once per process. The façade must stay metadata-eager + * (ADR-0019), so the module that binds a host's command port enters with the first operation that + * needs it rather than above it. Only the module is memoized: each `setup` call binds its own host. */ -function createHarmonyInventoryModule(host: HostEnvironment): InventoryPlatformModule<'harmonyos'> { - const config = Object.freeze({ - hdcSdkPath: normalizedRoot(host.env.HDC_SDK_PATH), - devecoSdkHome: normalizedRoot(host.env.DEVECO_SDK_HOME), - commandLineToolsHome: normalizedRoot(host.env.HARMONYOS_COMMAND_LINE_TOOLS), - }); - return Object.freeze({ - ...metadata, - loadInventory: async (inventoryHost) => { - const { createHarmonyInventory } = await import('./inventory.ts'); - return createHarmonyInventory(inventoryHost, config); - }, - }); -} +let toolboxModule: Promise | undefined; -function normalizedRoot(root: string | undefined): string | undefined { - const trimmed = root?.trim(); - return trimmed ? trimmed : undefined; +async function harmonyToolbox(host: PlatformHost) { + toolboxModule ??= import('./toolbox.ts'); + const { createHarmonyToolbox } = await toolboxModule; + return createHarmonyToolbox(host); } function harmonyPlatformPlugin() { @@ -52,28 +33,45 @@ function harmonyPlatformPlugin() { { kind: 'platform', family: 'harmonyos', - setup(host: PlatformHost): PlatformSetup<'harmonyos'> { + // The family binds its host on first use rather than in `setup`, so importing this package + // evaluates nothing but itself. Every operation below awaits this same resolution, so one + // setup builds exactly one toolbox for the whole family. + setup(host: PlatformHost): HarmonyPlatformRegistration { + const toolbox = harmonyToolbox(host); + const inventoryModule: InventoryPlatformModule<'harmonyos'> = Object.freeze({ + ...metadata, + // The family's inventory asks the core for no host: the documented HarmonyOS toolchain + // roots come from the host `setup` received, so the plugin neither reads `process.env` + // itself (ADR 0019) nor has the core name its configuration. + loadInventory: async () => { + const { createHarmonyInventory } = await import('./inventory.ts'); + return createHarmonyInventory(await toolbox); + }, + }); + const runtimeModule = Object.freeze({ + ...metadata, + loadRuntime: async (host) => { + const { createHarmonyPlatformRuntime } = await import('./runtime.ts'); + return createHarmonyPlatformRuntime(host, await toolbox); + }, + } satisfies PlatformRuntimeModule & { readonly family: 'harmonyos' }); return { family: 'harmonyos', - inventoryModule: createHarmonyInventoryModule(host), + inventoryModule, runtimeModule, - createInteractor: async ( - device: DeviceInfo, - runnerContext: RunnerContext, - ): Promise => { + createInteractor: async (device, runnerContext) => { const { createHarmonyInteractor } = await import('./interactor.ts'); - return createHarmonyInteractor(device, runnerContext); + return createHarmonyInteractor(await toolbox, device, runnerContext); }, operations: { toolchainCheck: async () => { - const { harmonyToolchainCheck } = await import('./doctor.ts'); - return await harmonyToolchainCheck(); - }, - prepareToolchain: async (env: EnvMap) => { - const { ensureHarmonyToolchainPathConfigured } = await import('./hdc.ts'); - await ensureHarmonyToolchainPathConfigured(env); + const [{ harmonyToolchainCheck }, { commands }] = await Promise.all([ + import('./doctor.ts'), + toolbox, + ]); + return await harmonyToolchainCheck(commands); }, - }, + } satisfies HarmonyPlatformOperations, }; }, }, diff --git a/packages/platform-harmonyos/src/input-actions.ts b/packages/platform-harmonyos/src/input-actions.ts index 1500465720..f6287be1ec 100644 --- a/packages/platform-harmonyos/src/input-actions.ts +++ b/packages/platform-harmonyos/src/input-actions.ts @@ -8,18 +8,29 @@ import { import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { sleep } from '@agent-device/host-kit/retry'; -import { runHarmonyShell } from './hdc.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; import { invalidateHarmonyGestureViewport, readHarmonyGestureViewport } from './snapshot.ts'; -export async function pressHarmony(device: DeviceInfo, x: number, y: number): Promise { - await runHarmonyShell(device, ['uitest', 'uiInput', 'click', x, y]); +export async function pressHarmony( + hdc: HarmonyHdcRunner, + device: DeviceInfo, + x: number, + y: number, +): Promise { + await hdc.runShell(device, ['uitest', 'uiInput', 'click', x, y]); } -export async function doubleClickHarmony(device: DeviceInfo, x: number, y: number): Promise { - await runHarmonyShell(device, ['uitest', 'uiInput', 'doubleClick', x, y]); +export async function doubleClickHarmony( + hdc: HarmonyHdcRunner, + device: DeviceInfo, + x: number, + y: number, +): Promise { + await hdc.runShell(device, ['uitest', 'uiInput', 'doubleClick', x, y]); } export async function longPressHarmony( + hdc: HarmonyHdcRunner, device: DeviceInfo, x: number, y: number, @@ -28,15 +39,21 @@ export async function longPressHarmony( // API 24's native longClick produces the actual ArkUI long-press gesture. A // stationary swipe returns success but does not dispatch LongPressGesture on // either verified target, so do not treat it as an equivalent fallback. - await runHarmonyShell(device, ['uitest', 'uiInput', 'longClick', x, y]); + await hdc.runShell(device, ['uitest', 'uiInput', 'longClick', x, y]); } -export async function typeHarmony(device: DeviceInfo, text: string, delayMs = 0): Promise { - await runHarmonyShell(device, ['uitest', 'uiInput', 'text', text]); +export async function typeHarmony( + hdc: HarmonyHdcRunner, + device: DeviceInfo, + text: string, + delayMs = 0, +): Promise { + await hdc.runShell(device, ['uitest', 'uiInput', 'text', text]); if (delayMs > 0) await sleep(delayMs); } export async function fillHarmony( + hdc: HarmonyHdcRunner, device: DeviceInfo, x: number, y: number, @@ -45,16 +62,17 @@ export async function fillHarmony( ): Promise { // `inputText` focuses the exact point before writing. It is the supported API 24 // path and avoids relying on desktop-only Ctrl+A key aliases. - await runHarmonyShell(device, ['uitest', 'uiInput', 'inputText', x, y, text]); + await hdc.runShell(device, ['uitest', 'uiInput', 'inputText', x, y, text]); if (delayMs > 0) await sleep(delayMs); } export async function scrollHarmony( + hdc: HarmonyHdcRunner, device: DeviceInfo, direction: ScrollDirection, options?: { amount?: number; pixels?: number; durationMs?: number }, ): Promise> { - const viewport = await readHarmonyGestureViewport(device); + const viewport = await readHarmonyGestureViewport(hdc, device); const plan = buildScrollGesturePlan({ direction, amount: options?.amount, @@ -62,7 +80,7 @@ export async function scrollHarmony( referenceWidth: viewport.width, referenceHeight: viewport.height, }); - await runHarmonyShell(device, [ + await hdc.runShell(device, [ 'uitest', 'uiInput', 'swipe', @@ -77,6 +95,7 @@ export async function scrollHarmony( /** Lowers HDC's public one-pointer primitives from a shared semantic plan. */ export async function performHarmonyGesture( + hdc: HarmonyHdcRunner, device: DeviceInfo, plan: GesturePlan, ): Promise> { @@ -98,7 +117,7 @@ export async function performHarmonyGesture( Math.min(40_000, Math.round((distance / plan.durationMs) * 1_000)), ); const command = plan.intent === 'fling' ? 'fling' : 'swipe'; - await runHarmonyShell(device, [ + await hdc.runShell(device, [ 'uitest', 'uiInput', command, @@ -111,30 +130,31 @@ export async function performHarmonyGesture( return { backend: 'harmonyos-hdc-uiinput', command, velocity, viewport: plan.viewport }; } -export async function backHarmony(device: DeviceInfo): Promise { - await runHarmonyShell(device, ['uitest', 'uiInput', 'keyEvent', 'Back']); +export async function backHarmony(hdc: HarmonyHdcRunner, device: DeviceInfo): Promise { + await hdc.runShell(device, ['uitest', 'uiInput', 'keyEvent', 'Back']); invalidateHarmonyGestureViewport(device); } -export async function homeHarmony(device: DeviceInfo): Promise { - await runHarmonyShell(device, ['uitest', 'uiInput', 'keyEvent', 'Home']); +export async function homeHarmony(hdc: HarmonyHdcRunner, device: DeviceInfo): Promise { + await hdc.runShell(device, ['uitest', 'uiInput', 'keyEvent', 'Home']); invalidateHarmonyGestureViewport(device); } -export async function appSwitcherHarmony(device: DeviceInfo): Promise { - await runHarmonyShell(device, ['uitest', 'uiInput', 'keyEvent', 'Recent']); +export async function appSwitcherHarmony(hdc: HarmonyHdcRunner, device: DeviceInfo): Promise { + await hdc.runShell(device, ['uitest', 'uiInput', 'keyEvent', 'Recent']); invalidateHarmonyGestureViewport(device); } export async function pressHarmonyKeyboardKey( + hdc: HarmonyHdcRunner, device: DeviceInfo, key: 'Enter' | 'Back', ): Promise { if (key === 'Back') { - await backHarmony(device); + await backHarmony(hdc, device); return; } - await runHarmonyShell(device, ['uitest', 'uiInput', 'keyEvent', key]); + await hdc.runShell(device, ['uitest', 'uiInput', 'keyEvent', key]); } export async function setHarmonyOrientation( diff --git a/packages/platform-harmonyos/src/interactor.test.ts b/packages/platform-harmonyos/src/interactor.test.ts index 3d94a308c6..eaa8c09a12 100644 --- a/packages/platform-harmonyos/src/interactor.test.ts +++ b/packages/platform-harmonyos/src/interactor.test.ts @@ -1,5 +1,6 @@ import { expect, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { createHarmonyHostStub } from './toolbox.fixtures.ts'; const { pressHarmonyKeyboardKey, snapshotHarmony } = vi.hoisted(() => ({ pressHarmonyKeyboardKey: vi.fn(async () => undefined), @@ -31,18 +32,26 @@ const device: DeviceInfo = { }; test('harmonyos snapshot stamps its channel and producer', async () => { - const result = await createHarmonyInteractor(device).snapshot(); + const { toolbox } = createHarmonyHostStub(); + const result = await createHarmonyInteractor(toolbox, device).snapshot(); if ('stage' in result) throw new Error('HarmonyOS snapshot must be presented'); expect(result.backend).toBe('harmonyos-arkui'); expect(result.producer).toBe('harmonyos-uitest'); expect(result.nodes).toEqual([{ index: 0, type: 'Button', label: 'Continue' }]); + expect(snapshotHarmony).toHaveBeenCalledWith(expect.objectContaining({}), device, undefined); }); test('harmonyos keyboard dismiss invalidates gesture viewport through the Back route', async () => { - await expect(createHarmonyInteractor(device).keyboardDismiss?.()).resolves.toEqual({ + const { toolbox } = createHarmonyHostStub(); + + await expect(createHarmonyInteractor(toolbox, device).keyboardDismiss?.()).resolves.toEqual({ kind: 'acknowledged', }); - expect(pressHarmonyKeyboardKey).toHaveBeenCalledWith(device, 'Back'); + expect(pressHarmonyKeyboardKey).toHaveBeenCalledWith( + expect.objectContaining({ runShell: expect.any(Function) }), + device, + 'Back', + ); }); diff --git a/packages/platform-harmonyos/src/interactor.ts b/packages/platform-harmonyos/src/interactor.ts index b6626e93d2..faaf5b3fcb 100644 --- a/packages/platform-harmonyos/src/interactor.ts +++ b/packages/platform-harmonyos/src/interactor.ts @@ -2,7 +2,7 @@ import { stampSnapshotIdentity } from '@agent-device/contracts/snapshot-producer import { AppError } from '@agent-device/kernel/errors'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; -import { withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; +import type { HarmonyToolbox } from './toolbox.ts'; import { closeHarmonyApp, openHarmonyApp } from './app-lifecycle.ts'; import { appSwitcherHarmony, @@ -22,28 +22,33 @@ import { screenshotHarmony } from './screenshot.ts'; import { setHarmonySetting } from './settings.ts'; import { readHarmonyGestureViewport, snapshotHarmony } from './snapshot.ts'; -export function createHarmonyInteractor(device: DeviceInfo, _runner?: RunnerContext): Interactor { +export function createHarmonyInteractor( + toolbox: HarmonyToolbox, + device: DeviceInfo, + _runner?: RunnerContext, +): Interactor { + const { hdc } = toolbox; const unsupported = (name: string) => async (): Promise => { throw new AppError('UNSUPPORTED_OPERATION', `${name} is not supported on HarmonyOS`); }; return { - open: (app, options) => openHarmonyApp(device, app, { activity: options?.activity }), - openDevice: () => homeHarmony(device), - close: (app) => closeHarmonyApp(device, app), - tap: (x, y) => pressHarmony(device, x, y), - doubleTap: (x, y) => doubleClickHarmony(device, x, y), - longPress: (x, y, durationMs) => longPressHarmony(device, x, y, durationMs), - focus: (x, y) => pressHarmony(device, x, y), - type: (text, delayMs) => typeHarmony(device, text, delayMs), - fill: (x, y, text, delayMs) => fillHarmony(device, x, y, text, delayMs), - scroll: (direction, options) => scrollHarmony(device, direction, options), - performGesture: (plan) => performHarmonyGesture(device, plan), - gestureViewport: () => readHarmonyGestureViewport(device), - screenshot: (outPath) => screenshotHarmony(device, outPath), + open: (app, options) => openHarmonyApp(hdc, device, app, { activity: options?.activity }), + openDevice: () => homeHarmony(hdc, device), + close: (app) => closeHarmonyApp(hdc, device, app), + tap: (x, y) => pressHarmony(hdc, device, x, y), + doubleTap: (x, y) => doubleClickHarmony(hdc, device, x, y), + longPress: (x, y, durationMs) => longPressHarmony(hdc, device, x, y, durationMs), + focus: (x, y) => pressHarmony(hdc, device, x, y), + type: (text, delayMs) => typeHarmony(hdc, device, text, delayMs), + fill: (x, y, text, delayMs) => fillHarmony(hdc, device, x, y, text, delayMs), + scroll: (direction, options) => scrollHarmony(hdc, device, direction, options), + performGesture: (plan) => performHarmonyGesture(hdc, device, plan), + gestureViewport: () => readHarmonyGestureViewport(hdc, device), + screenshot: (outPath) => screenshotHarmony(hdc, device, outPath), snapshot: async (options) => { - const result = await withDiagnosticTimer( + const result = await toolbox.withDiagnosticTimer( 'snapshot_capture', - async () => await snapshotHarmony(device, options), + async () => await snapshotHarmony(hdc, device, options), { backend: 'harmonyos-arkui' }, ); return stampSnapshotIdentity(result, { @@ -51,21 +56,21 @@ export function createHarmonyInteractor(device: DeviceInfo, _runner?: RunnerCont producer: 'harmonyos-uitest', }); }, - back: () => backHarmony(device), - home: () => homeHarmony(device), + back: () => backHarmony(hdc, device), + home: () => homeHarmony(hdc, device), setOrientation: (orientation) => setHarmonyOrientation(device, orientation), - appSwitcher: () => appSwitcherHarmony(device), + appSwitcher: () => appSwitcherHarmony(hdc, device), tvRemote: unsupported('tv-remote'), keyboardDismiss: async () => { - await pressHarmonyKeyboardKey(device, 'Back'); + await pressHarmonyKeyboardKey(hdc, device, 'Back'); return { kind: 'acknowledged' }; }, keyboardEnter: async () => { - await pressHarmonyKeyboardKey(device, 'Enter'); + await pressHarmonyKeyboardKey(hdc, device, 'Enter'); return { kind: 'harmonyos-acknowledged' }; }, readClipboard: unsupported('clipboard'), writeClipboard: unsupported('clipboard'), - setSetting: (setting, state, appId) => setHarmonySetting(device, setting, state, appId), + setSetting: (setting, state, appId) => setHarmonySetting(hdc, device, setting, state, appId), }; } diff --git a/packages/platform-harmonyos/src/inventory.test.ts b/packages/platform-harmonyos/src/inventory.test.ts index ff7eaa00cf..ef93f8e1fe 100644 --- a/packages/platform-harmonyos/src/inventory.test.ts +++ b/packages/platform-harmonyos/src/inventory.test.ts @@ -1,10 +1,13 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; -import type { - DeviceInventoryHostFor, - HostCommandRequest, - PlatformRequestScope, -} from '@agent-device/contracts/platform-runtime-host'; +import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; +import { AppError, asAppError } from '@agent-device/kernel/errors'; +import path from 'node:path'; +import { + createHarmonyHostStub, + createHarmonyToolchainRoot, + harmonyCommandPath, +} from './toolbox.fixtures.ts'; import { createHarmonyInventory, parseHarmonyTargetList } from './inventory.ts'; const scope: PlatformRequestScope = { @@ -13,21 +16,24 @@ const scope: PlatformRequestScope = { progress: { report: () => undefined }, }; -test('Harmony inventory parses targets, probes through the host port, and applies serial selection', async () => { +test('Harmony inventory parses targets and applies serial selection', async () => { assert.deepEqual(parseHarmonyTargetList('\n127.0.0.1:5555\n[Empty]\n'), ['127.0.0.1:5555']); - const calls: HostCommandRequest[] = []; - const host = createHost(async (request) => { - calls.push(request); - const key = request.args.join('\0'); - if (key === 'list\0targets') return result('emulator-1\nphysical-1\n'); - if (key.includes('const.product.name')) { - return result(key.startsWith('-t\0emulator-1') ? 'emulator\n' : 'Mate 60\n'); - } - if (key.includes('const.build.characteristics')) return result('tv\n'); - throw new Error(`Unexpected HDC invocation: ${key}`); + const stub = createHarmonyHostStub({ + respond: (_executable, args) => { + const key = args.join('\0'); + if (key === 'list\0targets') return { stdout: 'emulator-1\nphysical-1\n' }; + if (key.includes('const.product.name')) { + return { stdout: key.startsWith('-t\0emulator-1') ? 'emulator\n' : 'Mate 60\n' }; + } + if (key.includes('const.build.characteristics')) return { stdout: 'tv\n' }; + throw new Error(`Unexpected HDC invocation: ${key}`); + }, }); - const devices = await createHarmonyInventory(host).discover({ serial: 'physical-1' }, scope); + const devices = await createHarmonyInventory(stub.toolbox).discover( + { serial: 'physical-1' }, + scope, + ); assert.deepEqual(devices, [ { @@ -39,87 +45,89 @@ test('Harmony inventory parses targets, probes through the host port, and applie booted: true, }, ]); - assert.ok(calls.every((call) => call.executable === 'hdc')); - assert.ok(calls.every((call) => call.timeoutMs === 10_000)); -}); - -test('Harmony inventory resolves captured HDC toolchain roots without mutating host state', async () => { - const host = createHost( - async (request) => { - assert.equal(request.executable, '/opt/deveco/default/openharmony/toolchains/hdc'); - return result(''); - }, - { - which: async () => undefined, - isExecutable: async (candidate) => - candidate === '/opt/deveco/default/openharmony/toolchains/hdc', - }, + // Discovery is host-owned: every command names the executable and the target selection, never a + // shell string. + assert.ok( + stub.commands.every((command) => command.args[0] === '-t' || command.args[0] === 'list'), ); - - assert.deepEqual( - await createHarmonyInventory(host, { devecoSdkHome: '/opt/deveco' }).discover({}, scope), - [], + assert.ok( + stub.commands + .filter((command) => command.args[0] === '-t') + .every((command) => command.args[1] === 'physical-1'), ); }); -test('Harmony inventory prepares a configured legacy toolchain before discovery', async () => { - const preparedFamilies: string[] = []; - const host = { - ...createHost( - async (request) => { - assert.equal(request.executable, '/opt/deveco/default/openharmony/toolchains/hdc'); - return result(''); - }, - { - which: async () => undefined, - isExecutable: async (candidate) => - candidate === '/opt/deveco/default/openharmony/toolchains/hdc', - }, - ), - toolchains: { - prepare: async (family: string) => { - preparedFamilies.push(family); - }, - }, - }; +test('Harmony inventory spawns the HDC a documented root carries and puts that root on PATH', async () => { + const root = createHarmonyToolchainRoot(); + const stub = createHarmonyHostStub({ + env: { HDC_SDK_PATH: root, PATH: '/usr/bin' }, + respond: (_executable, args) => + args.join('\0') === 'list\0targets' ? { stdout: '[Empty]\n' } : { stdout: '' }, + }); - await createHarmonyInventory(host, { devecoSdkHome: '/opt/deveco' }).discover({}, scope); + assert.deepEqual(await createHarmonyInventory(stub.toolbox).discover({}, scope), []); - assert.deepEqual(preparedFamilies, ['harmonyos']); + const command = stub.commands[0]!; + assert.equal(command.executable, path.join(root, 'hdc')); + assert.deepEqual(command.args, ['list', 'targets']); + assert.ok(harmonyCommandPath(command).includes(root)); }); -test('Harmony inventory preserves the legacy curated HDC failure shape', async () => { - const host = createHost(async () => result('ignored', 'transport failed', 7)); +test('Harmony inventory hands the host environment plus the toolchain root to every command', async () => { + const root = createHarmonyToolchainRoot(); + const stub = createHarmonyHostStub({ + env: { HDC_SDK_PATH: root, PATH: '/usr/bin', HOME: '/host-home' }, + respond: (_executable, args) => + args.join('\0') === 'list\0targets' ? { stdout: '[Empty]\n' } : { stdout: '' }, + }); - await assert.rejects(createHarmonyInventory(host).discover({}, scope), (error: unknown) => { - if (!(error instanceof Error) || !('details' in error)) return false; - assert.deepEqual(error.details, { - stderr: 'transport failed', - hint: 'Confirm the HarmonyOS emulator or device is running, then run hdc list targets.', - }); - return true; + await createHarmonyInventory(stub.toolbox).discover({}, scope); + + // The plugin never reads `process.env`: what the host named is what the spawn gets, with only + // PATH extended. + assert.deepEqual(stub.commands[0]!.env, { + HDC_SDK_PATH: root, + HOME: '/host-home', + PATH: [root, '/usr/bin'].join(path.delimiter), }); }); -function createHost( - run: DeviceInventoryHostFor<'harmonyos'>['commands']['run'], - tools: { - which?: DeviceInventoryHostFor<'harmonyos'>['commands']['which']; - isExecutable?: DeviceInventoryHostFor<'harmonyos'>['files']['isExecutable']; - } = {}, -): DeviceInventoryHostFor<'harmonyos'> { - return { - commands: { which: tools.which ?? (async () => 'hdc'), run }, - toolchains: { prepare: async () => undefined }, - files: { - isExecutable: tools.isExecutable ?? (async () => false), - createTemporaryTextFile: async () => { - throw new Error('unused'); - }, +test('Harmony inventory preserves the curated HDC failure shape', async () => { + const stub = createHarmonyHostStub({ + respond: () => ({ stdout: 'ignored', stderr: 'transport failed', exitCode: 7 }), + }); + + await assert.rejects( + createHarmonyInventory(stub.toolbox).discover({}, scope), + (error: unknown) => { + if (!(error instanceof Error) || !('details' in error)) return false; + assert.deepEqual(error.details, { + stderr: 'transport failed', + hint: 'Confirm the HarmonyOS emulator or device is running, then run hdc list targets.', + }); + return true; }, - }; -} + ); +}); -function result(stdout: string, stderr = '', exitCode = 0) { - return { stdout, stderr, exitCode }; -} +test('Harmony inventory names the toolchain roots when no root or PATH carries HDC', async () => { + // The host rejects a spawn it cannot start with its own typed TOOL_MISSING, so the curated + // missing-toolchain error has to come from the HDC route rather than from an exit code. + const stub = createHarmonyHostStub({ + reject: () => new AppError('TOOL_MISSING', 'hdc not found in PATH', { cmd: 'hdc' }), + }); + + await assert.rejects( + createHarmonyInventory(stub.toolbox).discover({}, scope), + (error: unknown) => { + const failure = asAppError(error); + assert.equal(failure.code, 'TOOL_MISSING'); + assert.equal(failure.message, 'hdc not found in PATH'); + assert.equal( + failure.details?.hint, + 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH or set HDC_SDK_PATH.', + ); + return true; + }, + ); +}); diff --git a/packages/platform-harmonyos/src/inventory.ts b/packages/platform-harmonyos/src/inventory.ts index ea6130b934..0b0e2a6c37 100644 --- a/packages/platform-harmonyos/src/inventory.ts +++ b/packages/platform-harmonyos/src/inventory.ts @@ -1,30 +1,22 @@ -import path from 'node:path'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { deviceShellArgv } from '@agent-device/kernel/device-shell'; import { AppError } from '@agent-device/kernel/errors'; -import type { - DeviceInventoryHostFor, - HostCommandResult, - PlatformRequestScope, -} from '@agent-device/contracts/platform-runtime-host'; +import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; import type { DeviceInventorySource } from '@agent-device/contracts/platform-module'; import type { DeviceInventoryRequest } from '@agent-device/contracts/device'; - -/** The raw HarmonyOS toolchain roots the plugin was configured with, captured inertly by its host. */ -export type HarmonyInventoryConfig = Readonly<{ - hdcSdkPath?: string; - devecoSdkHome?: string; - commandLineToolsHome?: string; -}>; +import { type HarmonyHdcRunner } from './hdc.ts'; +import type { HarmonyToolbox } from './toolbox.ts'; const PROBE_TIMEOUT_MS = 10_000; -export function createHarmonyInventory( - host: DeviceInventoryHostFor<'harmonyos'>, - config: HarmonyInventoryConfig = {}, -): DeviceInventorySource { +/** + * HarmonyOS device discovery. It runs entirely over the plugin's own HDC route, so the toolchain + * roots the plugin was configured with are already honored — the core prepares no HarmonyOS + * toolchain and resolves no HDC for it. A machine without HDC fails in that route with the curated + * missing-toolchain error, so discovery only answers for what a started HDC reported. + */ +export function createHarmonyInventory(toolbox: HarmonyToolbox): DeviceInventorySource { return { - discover: async (request, scope) => await discoverHarmonyDevices(host, config, request, scope), + discover: async (request, scope) => await discoverHarmonyDevices(toolbox.hdc, request, scope), }; } @@ -36,19 +28,15 @@ export function parseHarmonyTargetList(rawOutput: string): string[] { } async function discoverHarmonyDevices( - host: DeviceInventoryHostFor<'harmonyos'>, - config: HarmonyInventoryConfig, + hdc: HarmonyHdcRunner, request: Readonly, scope: PlatformRequestScope, ): Promise { - await host.toolchains.prepare('harmonyos'); - const hdc = await resolveHdc(host, configuredToolchainRoots(config)); - if (!hdc) { - throw new AppError('TOOL_MISSING', 'hdc not found in PATH', { - hint: 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.', - }); - } - const result = await runHdc(host, hdc, ['list', 'targets'], scope); + const result = await hdc.launch(['list', 'targets'], { + allowFailure: true, + timeoutMs: PROBE_TIMEOUT_MS, + signal: scope.signal, + }); if (result.exitCode !== 0) { throw new AppError('COMMAND_FAILED', 'hdc list targets failed', { stderr: result.stderr, @@ -58,56 +46,20 @@ async function discoverHarmonyDevices( const targets = parseHarmonyTargetList(result.stdout).filter( (target) => !request.serial || request.serial === target, ); - const devices = await Promise.all( - targets.map(async (target) => await probeHarmonyDevice(host, hdc, target, scope)), + return await Promise.all( + targets.map(async (target) => await probeHarmonyDevice(hdc, target, scope)), ); - return devices; -} - -function configuredToolchainRoots(config: HarmonyInventoryConfig): readonly string[] { - return [ - config.hdcSdkPath, - config.devecoSdkHome && path.join(config.devecoSdkHome, 'default', 'openharmony', 'toolchains'), - config.commandLineToolsHome && - path.join(config.commandLineToolsHome, 'sdk', 'default', 'openharmony', 'toolchains'), - ].filter((root): root is string => root !== undefined); -} - -async function resolveHdc( - host: DeviceInventoryHostFor<'harmonyos'>, - toolchainRoots: readonly string[], -): Promise { - for (const root of toolchainRoots) { - const candidate = path.join(root, 'hdc'); - if (await host.files.isExecutable(candidate)) return candidate; - } - return await host.commands.which('hdc'); } async function probeHarmonyDevice( - host: DeviceInventoryHostFor<'harmonyos'>, - hdc: string, + hdc: HarmonyHdcRunner, target: string, scope: PlatformRequestScope, ): Promise { + const device = { id: target }; const [nameResult, characteristicsResult] = await Promise.all([ - runHdc( - host, - hdc, - deviceShellArgv('hdc', 'shell', ['param', 'get', 'const.product.name'], ['-t', target]), - scope, - ), - runHdc( - host, - hdc, - deviceShellArgv( - 'hdc', - 'shell', - ['param', 'get', 'const.build.characteristics'], - ['-t', target], - ), - scope, - ), + probe(hdc, device, ['param', 'get', 'const.product.name'], scope), + probe(hdc, device, ['param', 'get', 'const.build.characteristics'], scope), ]); const name = nameResult.exitCode === 0 ? nameResult.stdout.trim() : ''; const emulator = name.toLowerCase() === 'emulator'; @@ -121,19 +73,15 @@ async function probeHarmonyDevice( }; } -async function runHdc( - host: DeviceInventoryHostFor<'harmonyos'>, - executable: string, - args: readonly string[], +async function probe( + hdc: HarmonyHdcRunner, + device: { id: string }, + words: readonly string[], scope: PlatformRequestScope, -): Promise { - return await host.commands.run( - { - executable, - args, - allowFailure: true, - timeoutMs: PROBE_TIMEOUT_MS, - }, - scope.signal, - ); +) { + return await hdc.runShell(device, words, { + allowFailure: true, + timeoutMs: PROBE_TIMEOUT_MS, + signal: scope.signal, + }); } diff --git a/packages/platform-harmonyos/src/keyboard-band.ts b/packages/platform-harmonyos/src/keyboard-band.ts index 8e1b60d2f3..a6005c62d1 100644 --- a/packages/platform-harmonyos/src/keyboard-band.ts +++ b/packages/platform-harmonyos/src/keyboard-band.ts @@ -1,6 +1,6 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { SnapshotKeyboardBandFact } from '@agent-device/kernel/snapshot'; -import { runHarmonyShell } from './hdc.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; /** * The system window that hosts the on-screen keyboard. HarmonyOS keeps this SceneBoard panel @@ -23,11 +23,12 @@ const KEYBOARD_BAND_PROBE_TIMEOUT_MS = 5_000; * derivation and its fail-open verdict exactly as they were before this probe existed. */ export async function readHarmonyKeyboardBand( + hdc: HarmonyHdcRunner, device: DeviceInfo, ): Promise { let stdout: string; try { - const result = await runHarmonyShell( + const result = await hdc.runShell( device, ['hidumper', '-s', 'WindowManagerService', '-a', '-a'], { timeoutMs: KEYBOARD_BAND_PROBE_TIMEOUT_MS }, diff --git a/packages/platform-harmonyos/src/logs/runtime.test.ts b/packages/platform-harmonyos/src/logs/runtime.test.ts index c4c5067dfb..f298ca1fa4 100644 --- a/packages/platform-harmonyos/src/logs/runtime.test.ts +++ b/packages/platform-harmonyos/src/logs/runtime.test.ts @@ -5,6 +5,7 @@ import type { import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { expect, test, vi } from 'vitest'; +import { createHarmonyHostStub, createHarmonyToolchainRoot } from '../toolbox.fixtures.ts'; import { createHarmonyAppLogEnvelope, harmonyAppLogDescriptorCodec } from './descriptor.ts'; import { createHarmonyAppLogRuntime } from './runtime.ts'; @@ -33,7 +34,7 @@ test('rejects durable HarmonyOS descriptors without the canonical process marker test('starts HarmonyOS hilog with the resolved application pid', async () => { const fixture = hostFixture(); - const binding = await createHarmonyAppLogRuntime(fixture.host).bind({ + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ device, intent: { kind: 'ordinary' }, scope, @@ -55,7 +56,7 @@ test('starts HarmonyOS hilog with the resolved application pid', async () => { test('rejects cross-session start and recovery paths before host authority is used', async () => { const fixture = hostFixture(); - const runtimeOwner = createHarmonyAppLogRuntime(fixture.host); + const runtimeOwner = createHarmonyAppLogRuntime(fixture.host, fixture.toolbox); const binding = await runtimeOwner.bind({ device, intent: { kind: 'ordinary' }, scope }); const envelope = createHarmonyAppLogEnvelope({ sessionId: 'session', @@ -91,7 +92,7 @@ test('rejects cross-session start and recovery paths before host authority is us test('rejects a missing HDC tool before opening output or starting a process', async () => { const fixture = hostFixture({ whichHdc: async () => undefined }); - const binding = await createHarmonyAppLogRuntime(fixture.host).bind({ + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ device, intent: { kind: 'ordinary' }, scope, @@ -115,18 +116,11 @@ test('rejects a missing HDC tool before opening output or starting a process', a expect(fixture.backgroundCommands).toEqual([]); }); -test('provider-selected HarmonyOS logs prepare configured HDC without local inventory discovery', async () => { - const events: string[] = []; - const prepare = vi.fn(async () => { - events.push('prepare'); - }); - const whichHdc = vi.fn(async () => { - expect(events).toEqual(['prepare']); - events.push('which'); - return '/configured/toolchains/hdc'; - }); - const fixture = hostFixture({ prepare, whichHdc }); - const binding = await createHarmonyAppLogRuntime(fixture.host).bind({ +test('HarmonyOS logs name the HDC a configured toolchain root carries and skip the PATH lookup', async () => { + const root = createHarmonyToolchainRoot(); + const whichHdc = vi.fn(async () => 'hdc'); + const fixture = hostFixture({ whichHdc, env: { HDC_SDK_PATH: root, PATH: '/usr/bin' } }); + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ device, intent: { kind: 'ordinary' }, scope, @@ -139,28 +133,21 @@ test('provider-selected HarmonyOS logs prepare configured HDC without local inve fence: { token: 'fence', generation: 1 }, }); - expect(prepare).toHaveBeenCalledWith('harmonyos'); - expect(whichHdc).toHaveBeenCalledWith('hdc'); - expect(events).toEqual(['prepare', 'which']); + // The plugin owns its documented roots, so it never asks the host to resolve HDC it already has. + expect(whichHdc).not.toHaveBeenCalled(); expect(fixture.backgroundCommands).toEqual([ - ['/configured/toolchains/hdc', '-t', 'harmony-1', 'shell', 'hilog', '-P', '456'], + [`${root}/hdc`, '-t', 'harmony-1', 'shell', 'hilog', '-P', '456'], ]); await started?.pendingHandle.transfer().finish(); }); -test('HarmonyOS log preflight preserves cancellation when toolchain preparation rejects differently', async () => { +test('HarmonyOS log preflight answers an already-aborted request before any HDC lookup', async () => { const controller = new AbortController(); const reason = new Error('cancelled'); - const transportError = new Error('toolchain preparation failed'); + controller.abort(reason); const whichHdc = vi.fn(async () => 'hdc'); - const fixture = hostFixture({ - prepare: async () => { - controller.abort(reason); - throw transportError; - }, - whichHdc, - }); - const binding = await createHarmonyAppLogRuntime(fixture.host).bind({ + const fixture = hostFixture({ whichHdc }); + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ device, intent: { kind: 'ordinary' }, scope: { ...scope, signal: controller.signal }, @@ -189,7 +176,7 @@ test('HarmonyOS log preflight preserves cancellation when HDC lookup rejects dif throw transportError; }, }); - const binding = await createHarmonyAppLogRuntime(fixture.host).bind({ + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ device, intent: { kind: 'ordinary' }, scope: { ...scope, signal: controller.signal }, @@ -209,8 +196,9 @@ test('HarmonyOS log preflight preserves cancellation when HDC lookup rejects dif function hostFixture( options: { - prepare?: AppLogRuntimeHost['toolchains']['prepare']; whichHdc?: AppLogRuntimeHost['commands']['which']; + /** The environment the plugin's own setup host names, including its toolchain roots. */ + env?: Readonly>; } = {}, ) { const backgroundCommands: string[][] = []; @@ -237,7 +225,7 @@ function hostFixture( throw new Error('unused'); }, }, - toolchains: { prepare: options.prepare ?? (async () => undefined) }, + toolchains: { prepare: async () => undefined }, artifacts: { resolveSession: () => ({ outputPath: '/tmp/app.log', pidPath: '/tmp/app-log.pid' }), }, @@ -267,8 +255,11 @@ function hostFixture( }, clock: { now: () => 10, sleep: waitForMonitorWake }, }; + // The plugin's toolbox is built from the host it was set up with, same as in composition. + const { toolbox } = createHarmonyHostStub({ env: options.env }); return { host, + toolbox, backgroundCommands, markerReads: () => markerReads, outputOpens: () => outputOpens, diff --git a/packages/platform-harmonyos/src/logs/runtime.ts b/packages/platform-harmonyos/src/logs/runtime.ts index 01cd81fbf5..7ab507dc36 100644 --- a/packages/platform-harmonyos/src/logs/runtime.ts +++ b/packages/platform-harmonyos/src/logs/runtime.ts @@ -5,12 +5,17 @@ import { createPidScopedAppLogRuntimeOwner, resolveFirstNumericAppLogPid, } from '@agent-device/capture-kit'; +import type { HarmonyToolbox } from '../toolbox.ts'; import { createHarmonyAppLogEnvelope, harmonyAppLogDescriptorCodec } from './descriptor.ts'; const START_UNAVAILABLE_HINT = 'The selected HarmonyOS transport cannot start a background hilog stream.'; -export function createHarmonyAppLogRuntime(host: AppLogRuntimeHost) { +/** + * HarmonyOS app logs. The `hdc` the two host-minted commands name is resolved by the plugin, because + * the core builds those commands' environment without this family's documented toolchain roots. + */ +export function createHarmonyAppLogRuntime(host: AppLogRuntimeHost, toolbox: HarmonyToolbox) { return createPidScopedAppLogRuntimeOwner(host, { family: 'harmonyos', backend: 'harmonyos', @@ -26,7 +31,7 @@ export function createHarmonyAppLogRuntime(host: AppLogRuntimeHost) { : ['No app bundle is tracked in this session. Run open first for app-scoped logs.'], }), process: async ({ host: runtimeHost, device, input, signal }) => { - const hdc = await prepareHarmonyLogs(runtimeHost, signal); + const hdc = await resolveHarmonyLogsHdc(host, toolbox, signal); return { resolvePid: async (pidSignal) => await resolveFirstNumericAppLogPid( @@ -66,21 +71,34 @@ export function createHarmonyAppLogRuntime(host: AppLogRuntimeHost) { }); } -async function prepareHarmonyLogs(host: AppLogRuntimeHost, signal: AbortSignal): Promise { +/** + * HDC for the host-minted hilog commands: the binary a documented toolchain root carries, else the + * host's own `PATH`. Both answers keep a cancellation a cancellation: an aborted request aborts the + * log stream rather than surfacing a probe failure. + */ +async function resolveHarmonyLogsHdc( + host: AppLogRuntimeHost, + toolbox: HarmonyToolbox, + signal: AbortSignal, +): Promise { signal.throwIfAborted(); - await preserveHarmonyCancellation(async () => await host.toolchains.prepare('harmonyos'), signal); + const fromToolchain = await preserveHarmonyCancellation( + async () => await toolbox.commands.toolchainHdc(), + signal, + ); + if (fromToolchain) return fromToolchain; signal.throwIfAborted(); - const hdc = await preserveHarmonyCancellation( + const fromPath = await preserveHarmonyCancellation( async () => await host.commands.which('hdc'), signal, ); signal.throwIfAborted(); - if (!hdc) { + if (!fromPath) { throw new AppError('TOOL_MISSING', 'hdc not found in PATH', { hint: 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.', }); } - return hdc; + return fromPath; } async function preserveHarmonyCancellation( diff --git a/packages/platform-harmonyos/src/perf.ts b/packages/platform-harmonyos/src/perf.ts index 5b0055c607..6a9f3afbc7 100644 --- a/packages/platform-harmonyos/src/perf.ts +++ b/packages/platform-harmonyos/src/perf.ts @@ -1,6 +1,6 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; -import { runHarmonyShell } from './hdc.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; const HARMONYOS_MEMORY_SAMPLE_METHOD = 'hdc-shell-proc-status'; @@ -32,11 +32,12 @@ export function parseHarmonyProcStatusMemory(rawOutput: string): } export async function sampleHarmonyMemoryPerf( + hdc: HarmonyHdcRunner, device: DeviceInfo, bundleName: string, ): Promise { - const pid = await resolveHarmonyProcessPid(device, bundleName); - const result = await runHarmonyShell(device, ['cat', `/proc/${pid}/status`], { + const pid = await resolveHarmonyProcessPid(hdc, device, bundleName); + const result = await hdc.runShell(device, ['cat', `/proc/${pid}/status`], { timeoutMs: 15_000, }); const memory = parseHarmonyProcStatusMemory(result.stdout); @@ -54,8 +55,12 @@ export async function sampleHarmonyMemoryPerf( }; } -async function resolveHarmonyProcessPid(device: DeviceInfo, bundleName: string): Promise { - const result = await runHarmonyShell(device, ['pidof', bundleName], { +async function resolveHarmonyProcessPid( + hdc: HarmonyHdcRunner, + device: DeviceInfo, + bundleName: string, +): Promise { + const result = await hdc.runShell(device, ['pidof', bundleName], { allowFailure: true, timeoutMs: 15_000, }); diff --git a/packages/platform-harmonyos/src/perf/runtime.test.ts b/packages/platform-harmonyos/src/perf/runtime.test.ts index dedc2e864f..70258cb269 100644 --- a/packages/platform-harmonyos/src/perf/runtime.test.ts +++ b/packages/platform-harmonyos/src/perf/runtime.test.ts @@ -1,5 +1,6 @@ import { expect, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { createHarmonyHostStub } from '../toolbox.fixtures.ts'; import { createHarmonyPerfOperations } from './runtime.ts'; const device: DeviceInfo = { @@ -13,7 +14,8 @@ const device: DeviceInfo = { test('keeps HarmonyOS perf limited to its existing memory sample', async () => { const sampleMemory = vi.fn(async () => ({ residentKb: 256 })); - const operations = createHarmonyPerfOperations({ device, sampleMemory }); + const { toolbox } = createHarmonyHostStub(); + const operations = createHarmonyPerfOperations({ hdc: toolbox.hdc, device, sampleMemory }); await expect(operations.perfMemorySample({ appId: 'com.example.app' })).resolves.toMatchObject({ metric: { available: true, residentKb: 256 }, diff --git a/packages/platform-harmonyos/src/perf/runtime.ts b/packages/platform-harmonyos/src/perf/runtime.ts index 139d123b8b..898d640a5f 100644 --- a/packages/platform-harmonyos/src/perf/runtime.ts +++ b/packages/platform-harmonyos/src/perf/runtime.ts @@ -5,6 +5,7 @@ import { import type { PerfRuntimeOperations } from '@agent-device/contracts/perf-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { sampleHarmonyMemoryPerf } from '../perf.ts'; +import type { HarmonyHdcRunner } from '../hdc.ts'; /** * The HarmonyOS performance cells. Memory sampling reads `/proc//status` over HDC, which the @@ -12,13 +13,17 @@ import { sampleHarmonyMemoryPerf } from '../perf.ts'; */ export function createHarmonyPerfOperations( params: Readonly<{ + hdc: HarmonyHdcRunner; device: DeviceInfo; /** The HDC memory read; the binding supplies the package's own sampler so a test can stub it. */ sampleMemory?: (device: DeviceInfo, appId: string) => Promise; }>, ): Pick { - const { device } = params; - const sampleMemory = params.sampleMemory ?? sampleHarmonyMemoryPerf; + const { hdc, device } = params; + const sampleMemory = + params.sampleMemory ?? + (async (device: DeviceInfo, appId: string) => + await sampleHarmonyMemoryPerf(hdc, device, appId)); const frameUnavailable = { available: false, reason: diff --git a/packages/platform-harmonyos/src/recording/recorder.test.ts b/packages/platform-harmonyos/src/recording/recorder.test.ts new file mode 100644 index 0000000000..f9a8883dfa --- /dev/null +++ b/packages/platform-harmonyos/src/recording/recorder.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, test } from 'vitest'; +import { createHarmonyHdcRunnerStub } from '../toolbox.fixtures.ts'; +import { createHarmonyScreenRecorder } from './recorder.ts'; + +const device = { + platform: 'harmonyos' as const, + id: 'harmony-device', + name: 'Harmony device', + kind: 'device' as const, + target: 'mobile' as const, + booted: true, +}; + +describe('the HarmonyOS screen recorder', () => { + test('removes staged media only after HDC confirms', async () => { + const hdc = createHarmonyHdcRunnerStub([{ exitCode: 1, stderr: 'permission denied' }]); + const recorder = createHarmonyScreenRecorder(hdc); + + await expect(recorder.remove(device, '/data/local/tmp/capture.mp4')).resolves.toBe(false); + expect(hdc.calls[0]).toMatchObject({ + kind: 'runShell', + target: 'harmony-device', + args: ['rm', '-f', '/data/local/tmp/capture.mp4'], + options: { allowFailure: true }, + }); + }); + + test('reads the staged byte count from focused HDC stat output', async () => { + const hdc = createHarmonyHdcRunnerStub([{ stdout: '12345\n' }]); + const recorder = createHarmonyScreenRecorder(hdc); + + await expect(recorder.stagedFileSize(device, '/data/local/tmp/capture.mp4')).resolves.toBe( + 12_345, + ); + expect(hdc.calls[0]?.args).toEqual(['stat', '-c', '%s', '/data/local/tmp/capture.mp4']); + }); + + test('treats a failed or unusable stat as no staged size', async () => { + const failing = createHarmonyScreenRecorder(createHarmonyHdcRunnerStub([{ exitCode: 1 }])); + await expect(failing.stagedFileSize(device, '/data/local/tmp/capture.mp4')).resolves.toBe( + undefined, + ); + + const unreadable = createHarmonyScreenRecorder( + createHarmonyHdcRunnerStub([{ stdout: 'not-a-size\n' }]), + ); + await expect(unreadable.stagedFileSize(device, '/data/local/tmp/capture.mp4')).resolves.toBe( + undefined, + ); + }); + + test('reads the media uri the device reports for the recorded file name', async () => { + const hdc = createHarmonyHdcRunnerStub([ + { stdout: 'FileID: 12 file://media/Video/record.mp4\n' }, + ]); + const recorder = createHarmonyScreenRecorder(hdc); + + await expect(recorder.findMedia(device, 'record.mp4')).resolves.toBe( + 'file://media/Video/record.mp4', + ); + expect(hdc.calls[0]?.args).toEqual(['mediatool', 'query', 'record.mp4', '-u']); + }); + + test('starts and stops the recorder ability through the shell route', async () => { + const hdc = createHarmonyHdcRunnerStub(); + const recorder = createHarmonyScreenRecorder(hdc); + + await recorder.start(device, 'record.mp4'); + await recorder.stop(device); + + expect(hdc.calls.map((call) => call.args)).toEqual([ + [ + 'aa', + 'start', + '-b', + 'com.huawei.hmos.screenrecorder', + '-a', + 'com.huawei.hmos.screenrecorder.ServiceExtAbility', + '--ps', + 'CustomizedFileName', + 'record.mp4', + ], + [ + 'aa', + 'start', + '-b', + 'com.huawei.hmos.screenrecorder', + '-a', + 'com.huawei.hmos.screenrecorder.ServiceExtAbility', + ], + ]); + }); + + test('stages and pulls media through the documented HDC file commands', async () => { + const hdc = createHarmonyHdcRunnerStub(); + const recorder = createHarmonyScreenRecorder(hdc); + + await expect( + recorder.stageMedia(device, { + mediaUri: 'file://media/Video/record.mp4', + remotePath: '/data/local/tmp/capture.mp4', + }), + ).resolves.toBe(true); + await recorder.pull(device, { + remotePath: '/data/local/tmp/capture.mp4', + outputPath: '/tmp/capture.mp4', + }); + + expect(hdc.calls.map((call) => [call.kind, call.args])).toEqual([ + [ + 'runShell', + ['mediatool', 'recv', 'file://media/Video/record.mp4', '/data/local/tmp/capture.mp4'], + ], + ['run', ['file', 'recv', '/data/local/tmp/capture.mp4', '/tmp/capture.mp4']], + ]); + }); + + test('reports media removal only when the device confirms the delete', async () => { + const removed = createHarmonyHdcRunnerStub(); + await expect( + createHarmonyScreenRecorder(removed).removeMedia(device, 'file://media/Video/record.mp4'), + ).resolves.toBe(true); + expect(removed.calls[0]?.args).toEqual([ + 'mediatool', + 'delete', + 'file://media/Video/record.mp4', + ]); + + const refused = createHarmonyHdcRunnerStub([{ exitCode: 1 }]); + await expect( + createHarmonyScreenRecorder(refused).removeMedia(device, 'file://media/Video/record.mp4'), + ).resolves.toBe(false); + }); +}); diff --git a/packages/platform-harmonyos/src/recording/recorder.ts b/packages/platform-harmonyos/src/recording/recorder.ts index 455ebc1e82..b63e621ec2 100644 --- a/packages/platform-harmonyos/src/recording/recorder.ts +++ b/packages/platform-harmonyos/src/recording/recorder.ts @@ -1,7 +1,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { HostCommandResult } from '@agent-device/contracts/platform-runtime-host'; import type { ShellWord } from '@agent-device/kernel/device-shell'; -import { runHarmonyHdc, runHarmonyShell } from '../hdc.ts'; +import type { HarmonyHdcRunner } from '../hdc.ts'; /** * The device-side HarmonyOS screen recorder, driven entirely through HDC. It is the family's own @@ -38,7 +38,19 @@ export type HarmonyScreenRecorder = Readonly<{ const SCREEN_RECORDER_ABILITY = 'com.huawei.hmos.screenrecorder'; const SCREEN_RECORDER_SERVICE_ABILITY = 'com.huawei.hmos.screenrecorder.ServiceExtAbility'; -export function createHarmonyScreenRecorder(): HarmonyScreenRecorder { +/** Binds the recorder to the plugin's HDC route, so every HDC call runs on the host. */ +export function createHarmonyScreenRecorder(hdc: HarmonyHdcRunner): HarmonyScreenRecorder { + const hdcShell = async ( + device: DeviceInfo, + words: readonly ShellWord[], + signal?: AbortSignal, + ): Promise => + await hdc.runShell(device, words, { allowFailure: true, signal }); + const hdcCommand = async ( + device: DeviceInfo, + args: readonly string[], + signal?: AbortSignal, + ): Promise => await hdc.run(device, args, { allowFailure: true, signal }); return Object.freeze({ start: async (device, fileName, signal) => await hdcShell( @@ -76,18 +88,10 @@ export function createHarmonyScreenRecorder(): HarmonyScreenRecorder { return Number.isSafeInteger(size) && size > 0 ? size : undefined; }, pull: async (device, input, signal) => - await hdc(device, ['file', 'recv', input.remotePath, input.outputPath], signal), + await hdcCommand(device, ['file', 'recv', input.remotePath, input.outputPath], signal), remove: async (device, remotePath, signal) => (await hdcShell(device, ['rm', '-f', remotePath], signal)).exitCode === 0, removeMedia: async (device, mediaUri, signal) => (await hdcShell(device, ['mediatool', 'delete', mediaUri], signal)).exitCode === 0, }); } - -async function hdc(device: DeviceInfo, args: string[], signal?: AbortSignal) { - return await runHarmonyHdc(device, args, { allowFailure: true, signal }); -} - -async function hdcShell(device: DeviceInfo, words: readonly ShellWord[], signal?: AbortSignal) { - return await runHarmonyShell(device, words, { allowFailure: true, signal }); -} diff --git a/packages/platform-harmonyos/src/recording/runtime.fixtures.ts b/packages/platform-harmonyos/src/recording/runtime.fixtures.ts index b8ea9b3aca..c509182db7 100644 --- a/packages/platform-harmonyos/src/recording/runtime.fixtures.ts +++ b/packages/platform-harmonyos/src/recording/runtime.fixtures.ts @@ -2,6 +2,7 @@ import { recordingFileStore } from '@agent-device/capture-kit/recording-artifact import type { ScreenRecordingRuntimeHost } from '@agent-device/contracts/screen-recording-runtime-host'; import type { ScreenRecordingStartInput } from '@agent-device/contracts/screen-recording-runtime'; import type { HarmonyScreenRecorder } from './recorder.ts'; +import type { HarmonyScreenRecordingOperationHost } from './runtime.ts'; export const harmonyDevice = Object.freeze({ platform: 'harmonyos' as const, @@ -33,18 +34,15 @@ export function harmonyCommandSuccess() { /** * The host and recorder pair the recording operations consume. Every recorder port is a stub the - * test overrides, so no HDC process is spawned from these tests. + * test overrides, so no HDC process is spawned from these tests; `recorder.test.ts` covers what the + * real recorder asks the host to spawn. */ export function harmonyRecordingHost( overrides: Partial & { complete?: ScreenRecordingRuntimeHost['finalize']['complete']; prepare?: ScreenRecordingRuntimeHost['outputs']['prepare']; } = {}, -): Readonly<{ - screenRecording: Pick; - clock: Readonly<{ now: () => number; sleep: (ms?: number) => Promise }>; - recorder: HarmonyScreenRecorder; -}> { +): HarmonyScreenRecordingOperationHost { return { screenRecording: { outputs: { @@ -55,7 +53,7 @@ export function harmonyRecordingHost( }, clock: { now: () => 0, sleep: async () => {} }, recorder: harmonyRecordingRecorder(overrides), - }; + } as unknown as HarmonyScreenRecordingOperationHost; } function harmonyRecordingRecorder( diff --git a/packages/platform-harmonyos/src/recording/runtime.test.ts b/packages/platform-harmonyos/src/recording/runtime.test.ts index be476ff266..06880b770f 100644 --- a/packages/platform-harmonyos/src/recording/runtime.test.ts +++ b/packages/platform-harmonyos/src/recording/runtime.test.ts @@ -11,7 +11,7 @@ import { harmonyRecordingHost as harmonyHost, harmonyRecordingInput as input, } from './runtime.fixtures.ts'; -import { mkdtempForTestSync } from '../__tests__/tmp-dir.ts'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; test('runs whole-screen capture and finalizes through the closed Harmony host', async () => { const operations = createHarmonyScreenRecordingOperations({ diff --git a/packages/platform-harmonyos/src/recording/runtime.ts b/packages/platform-harmonyos/src/recording/runtime.ts index db58683655..d76d496778 100644 --- a/packages/platform-harmonyos/src/recording/runtime.ts +++ b/packages/platform-harmonyos/src/recording/runtime.ts @@ -13,15 +13,16 @@ import { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; import { createScreenRecordingCompletion, createScreenRecordingLiveHandle, - createTransportRecordingSnapshot, assertScreenRecordingOptionsSupported, } from '@agent-device/capture-kit'; +import { createTransportRecordingSnapshot } from '@agent-device/capture-kit/screen-recording-transport'; import { cleanupRecoveredHarmonyRecording, createHarmonyRecordingEnvelope, type HarmonyRecordingDescriptor, } from './recovery.ts'; import { createHarmonyScreenRecorder, type HarmonyScreenRecorder } from './recorder.ts'; +import type { HarmonyToolbox } from '../toolbox.ts'; const HARMONY_SCREEN_RECORDING_BACKEND = 'HarmonyOS ScreenRecorder'; @@ -39,11 +40,12 @@ export type HarmonyScreenRecordingOperationHost = Readonly<{ /** Binds the shared runtime host's recording authorities to the HDC recorder this family drives. */ export function createHarmonyRecordingHost( host: PlatformRuntimeHost, + toolbox: HarmonyToolbox, ): HarmonyScreenRecordingOperationHost { return Object.freeze({ screenRecording: host.screenRecording, clock: host.clock, - recorder: createHarmonyScreenRecorder(), + recorder: createHarmonyScreenRecorder(toolbox.hdc), }); } diff --git a/packages/platform-harmonyos/src/runtime.test.ts b/packages/platform-harmonyos/src/runtime.test.ts index 8fae95be52..143b5e41cc 100644 --- a/packages/platform-harmonyos/src/runtime.test.ts +++ b/packages/platform-harmonyos/src/runtime.test.ts @@ -1,9 +1,11 @@ import { runtimeSubjectFact } from '@agent-device/contracts/platform-runtime'; -import { expect, test, vi } from 'vitest'; - -vi.mock('./hdc.ts', () => ({ runHarmonyShell: vi.fn() })); - -import { runHarmonyShell } from './hdc.ts'; +import { expect, test } from 'vitest'; +import { + answerHarmonyShell, + createHarmonyHostStub, + createHarmonyHdcRunnerStub, + createHarmonyToolboxWith, +} from './toolbox.fixtures.ts'; import type { DeviceBinding } from '@agent-device/contracts/platform-runtime'; import type { PlatformRuntimeHost, @@ -30,20 +32,22 @@ test.each([ ['device', device], ['emulator', { ...device, kind: 'emulator' as const }], ])('classifies the HarmonyOS %s runtime denominator', async (_name, runtimeDevice) => { - const hdc = vi.mocked(runHarmonyShell); - hdc.mockReset(); - hdc.mockImplementation(async (_device, args) => ({ - exitCode: 0, - stderr: '', - stdout: args.includes('bm') + // The family's HDC route answers `bm dump -a` with one bundle and the mission list with a + // foreground ability, which is what the listApps and appState cells read. + const hdc = createHarmonyHdcRunnerStub(); + answerHarmonyShell(hdc, (words) => + words.includes('bm') ? 'com.example.application\n' : 'Mission ID #76 mission name #[#com.example.harmony:entry:MainAbility]\nstate #FOREGROUND', - })); + ); const host = { processTransports: { resolve: async () => ({ mode: 'local' as const }) }, localInteractors: { resolve: async () => ({}) }, } as unknown as PlatformRuntimeHost; - const binding = await createHarmonyPlatformRuntime(host).bind({ + const binding = await createHarmonyPlatformRuntime( + host, + createHarmonyToolboxWith(createHarmonyHostStub().toolbox, { hdc }), + ).bind({ device: runtimeDevice, intent: { kind: 'ordinary' }, scope: { @@ -150,11 +154,9 @@ test.each([ await expect( binding.operations.listApps?.({ device: runtimeDevice, filter: 'all' }), ).resolves.toEqual([{ id: 'com.example.application', name: 'application' }]); - expect(hdc).toHaveBeenCalledWith( - runtimeDevice, - ['bm', 'dump', '-a'], - expect.objectContaining({ timeoutMs: 15_000 }), - ); + expect(hdc.calls.map((call) => [call.target, call.args, call.options.timeoutMs])).toEqual([ + ['harmony-fact', ['bm', 'dump', '-a'], 15_000], + ]); await expect(binding.operations.appState?.()).resolves.toEqual({ package: 'com.example.harmony', activity: 'MainAbility', @@ -167,7 +169,7 @@ test('rejects the non-discovered HarmonyOS simulator cell for appstate', async ( processTransports: { resolve: async () => ({ mode: 'local' as const }) }, localInteractors: { resolve: async () => ({}) }, } as unknown as PlatformRuntimeHost; - const binding = await createHarmonyPlatformRuntime(host).bind({ + const binding = await createHarmonyPlatformRuntime(host, createHarmonyHostStub().toolbox).bind({ device: runtimeDevice, intent: { kind: 'ordinary' }, scope: { @@ -259,7 +261,7 @@ test.each([ processTransports: { resolve: async () => ({ mode: 'local' as const }) }, localInteractors: { resolve: async () => ({}) }, } as unknown as PlatformRuntimeHost; - const binding = await createHarmonyPlatformRuntime(host).bind({ + const binding = await createHarmonyPlatformRuntime(host, createHarmonyHostStub().toolbox).bind({ device: runtimeDevice, intent: { kind: 'ordinary' }, scope: { @@ -322,7 +324,10 @@ test.each([ ['device', device], ['emulator', { ...device, kind: 'emulator' as const }], ])('declares the HarmonyOS %s gesture and scroll cells', async (_name, runtimeDevice) => { - const facts = await createHarmonyPlatformRuntime(gestureHost()).inspectFacts(runtimeDevice); + const facts = await createHarmonyPlatformRuntime( + gestureHost(), + createHarmonyHostStub().toolbox, + ).inspectFacts(runtimeDevice); expect(facts.operations.performGesturePlan).toEqual({ available: true }); expect(facts.operations.performDirectionalFlingPlan).toEqual({ available: true }); expect(facts.operations.gestureViewport).toEqual({ available: true }); @@ -340,7 +345,10 @@ test.each([ }); test('binds the HarmonyOS gesture tiers it admitted and omits the rest', async () => { - const binding = await createHarmonyPlatformRuntime(gestureHost()).bind({ + const binding = await createHarmonyPlatformRuntime( + gestureHost(), + createHarmonyHostStub().toolbox, + ).bind({ device, intent: { kind: 'ordinary' }, scope: { diff --git a/packages/platform-harmonyos/src/runtime.ts b/packages/platform-harmonyos/src/runtime.ts index 92dfc3d9b2..d6ee5ae7dc 100644 --- a/packages/platform-harmonyos/src/runtime.ts +++ b/packages/platform-harmonyos/src/runtime.ts @@ -51,6 +51,7 @@ import { harmonyScreenRecordingFacts, } from './recording/runtime.ts'; import { readHarmonyAppState } from './app-state.ts'; +import type { HarmonyToolbox } from './toolbox.ts'; import { bindLocalDirectApplicationLifecycle } from '@agent-device/contracts/application-lifecycle-interaction'; import { createHarmonyAppDeploymentOperations, @@ -179,8 +180,11 @@ const audioProbeUnavailable = unavailableFact( 'audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts', ); -export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): PlatformRuntimeOwner { - const appLogs = createHarmonyAppLogRuntime(host); +export function createHarmonyPlatformRuntime( + host: PlatformRuntimeHost, + toolbox: HarmonyToolbox, +): PlatformRuntimeOwner { + const appLogs = createHarmonyAppLogRuntime(host, toolbox); const inspectFacts = async (device: Parameters[0]) => { const logs = await appLogs.inspectFacts(device); const deployment = harmonyAppDeploymentFacts(device); @@ -315,20 +319,20 @@ export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): Platfor operations: Object.freeze({ ...logs.operations, ...createHarmonyAppDeploymentOperations({ - commands: host.commands, + toolbox, device: request.device, signal: request.scope.signal, }), ...(facts.operations.appState.available ? { appState: async () => - await readHarmonyAppState(request.device, request.scope.signal), + await readHarmonyAppState(toolbox.hdc, request.device, request.scope.signal), } : {}), ensureReady: async () => ({ ...request.device, booted: true }), ...(recordingFacts.available ? createHarmonyScreenRecordingOperations({ - host: createHarmonyRecordingHost(host), + host: createHarmonyRecordingHost(host, toolbox), device: request.device, owner, signal: request.scope.signal, @@ -352,6 +356,7 @@ export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): Platfor }), ...whenAdmitted(facts.operations.perfFrames, () => createHarmonyPerfOperations({ + hdc: toolbox.hdc, device: request.device, }), ), @@ -359,7 +364,9 @@ export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): Platfor request.scope.signal.throwIfAborted(); const { listHarmonyApps } = await import('./app-lifecycle.ts'); return ( - await listHarmonyApps(input.device, input.filter, { signal: request.scope.signal }) + await listHarmonyApps(toolbox.hdc, input.device, input.filter, { + signal: request.scope.signal, + }) ).map((app) => ({ id: app.package, name: app.name })); }, ...availableApplicationLifecycleOperations( diff --git a/packages/platform-harmonyos/src/screenshot.ts b/packages/platform-harmonyos/src/screenshot.ts index e928d57b02..e355c46990 100644 --- a/packages/platform-harmonyos/src/screenshot.ts +++ b/packages/platform-harmonyos/src/screenshot.ts @@ -2,20 +2,24 @@ import { randomUUID } from 'node:crypto'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { readHostBinaryFile } from '@agent-device/host-kit/host-file'; -import { runHarmonyHdc, runHarmonyShell } from './hdc.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; -export async function screenshotHarmony(device: DeviceInfo, outPath: string): Promise { +export async function screenshotHarmony( + hdc: HarmonyHdcRunner, + device: DeviceInfo, + outPath: string, +): Promise { const remotePath = `/data/local/tmp/agent-device-screen-${randomUUID()}.jpeg`; try { - await runHarmonyShell(device, ['snapshot_display', '-f', remotePath], { + await hdc.runShell(device, ['snapshot_display', '-f', remotePath], { timeoutMs: 15_000, }); - await runHarmonyHdc(device, ['file', 'recv', remotePath, outPath], { timeoutMs: 15_000 }); + await hdc.run(device, ['file', 'recv', remotePath, outPath], { timeoutMs: 15_000 }); const data = await readHostBinaryFile(outPath); if (data.length < 3 || data[0] !== 0xff || data[1] !== 0xd8 || data[2] !== 0xff) { throw new AppError('COMMAND_FAILED', 'HarmonyOS screenshot is not a JPEG file'); } } finally { - await runHarmonyShell(device, ['rm', '-f', remotePath], { allowFailure: true }).catch(() => {}); + await hdc.runShell(device, ['rm', '-f', remotePath], { allowFailure: true }).catch(() => {}); } } diff --git a/packages/platform-harmonyos/src/settings.ts b/packages/platform-harmonyos/src/settings.ts index ec3124ef1c..fb80e003aa 100644 --- a/packages/platform-harmonyos/src/settings.ts +++ b/packages/platform-harmonyos/src/settings.ts @@ -1,8 +1,9 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, sessionAppRequiredDetails } from '@agent-device/kernel/errors'; -import { runHarmonyShell } from './hdc.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; export async function setHarmonySetting( + hdc: HarmonyHdcRunner, device: DeviceInfo, setting: string, state: string, @@ -24,8 +25,8 @@ export async function setHarmonySetting( ); } - await runHarmonyShell(device, ['aa', 'force-stop', appBundleId], { timeoutMs: 15_000 }); - await runHarmonyShell(device, ['bm', 'clean', '-n', appBundleId, '-d', '-c'], { + await hdc.runShell(device, ['aa', 'force-stop', appBundleId], { timeoutMs: 15_000 }); + await hdc.runShell(device, ['bm', 'clean', '-n', appBundleId, '-d', '-c'], { timeoutMs: 15_000, }); return { bundleId: appBundleId, forceStopped: true, clearedData: true, clearedCache: true }; diff --git a/packages/platform-harmonyos/src/snapshot.ts b/packages/platform-harmonyos/src/snapshot.ts index 2c6dddeaea..3e354f369b 100644 --- a/packages/platform-harmonyos/src/snapshot.ts +++ b/packages/platform-harmonyos/src/snapshot.ts @@ -14,7 +14,7 @@ import { readHostTextFile, removeHostDirectory, } from '@agent-device/host-kit/host-file'; -import { runHarmonyHdc, runHarmonyShell } from './hdc.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; import { readHarmonyKeyboardBand } from './keyboard-band.ts'; const MAX_NODES = 5_000; @@ -41,6 +41,7 @@ type ArkUiLayoutNode = { }; export async function snapshotHarmony( + hdc: HarmonyHdcRunner, device: DeviceInfo, options: SnapshotOptions = {}, ): Promise<{ @@ -49,13 +50,14 @@ export async function snapshotHarmony( analysis: { rawNodeCount: number; maxDepth: number }; keyboard: SnapshotKeyboardBandFact; }> { - const snapshot = await captureHarmonyLayout(device, options); + const snapshot = await captureHarmonyLayout(hdc, device, options); // Measured after the tree so the band answers for a screen at least as new as the nodes. - const keyboard = await readHarmonyKeyboardBand(device); + const keyboard = await readHarmonyKeyboardBand(hdc, device); return { ...snapshot, keyboard }; } async function captureHarmonyLayout( + hdc: HarmonyHdcRunner, device: DeviceInfo, options: SnapshotOptions, ): Promise<{ @@ -68,26 +70,29 @@ async function captureHarmonyLayout( const localDirectory = await makeHostTemporaryDirectory('agent-device-harmony-layout-'); const localPath = path.join(localDirectory, 'layout.json'); try { - await runHarmonyShell(device, ['uitest', 'dumpLayout', '-p', remotePath], { + await hdc.runShell(device, ['uitest', 'dumpLayout', '-p', remotePath], { timeoutMs: 30_000, }); - await runHarmonyHdc(device, ['file', 'recv', remotePath, localPath], { timeoutMs: 15_000 }); + await hdc.run(device, ['file', 'recv', remotePath, localPath], { timeoutMs: 15_000 }); const raw = await readHostTextFile(localPath); return buildHarmonySnapshot(parseHarmonyLayout(raw), options); } finally { - await runHarmonyShell(device, ['rm', '-f', remotePath], { allowFailure: true }).catch(() => {}); + await hdc.runShell(device, ['rm', '-f', remotePath], { allowFailure: true }).catch(() => {}); await removeHostDirectory(localDirectory); } } /** Returns the current ArkUI application viewport for coordinate gestures. */ -export async function readHarmonyGestureViewport(device: DeviceInfo): Promise { +export async function readHarmonyGestureViewport( + hdc: HarmonyHdcRunner, + device: DeviceInfo, +): Promise { const memoKey = device.id; const cached = harmonyGestureViewportMemo.get(memoKey); if (cached) return cached; // Gesture planning reads geometry only, so this capture skips the keyboard-band probe the // snapshot command carries. - const snapshot = await captureHarmonyLayout(device, {}); + const snapshot = await captureHarmonyLayout(hdc, device, {}); const viewport = snapshot.nodes.find((node) => node.type === 'Application' && node.rect)?.rect; if (!viewport || viewport.width <= 0 || viewport.height <= 0) { throw new AppError( @@ -125,7 +130,6 @@ export function parseHarmonyLayout(raw: string): ArkUiLayoutNode { ); } } - function buildHarmonySnapshot( root: ArkUiLayoutNode, options: SnapshotOptions, diff --git a/packages/platform-harmonyos/src/toolbox.fixtures.ts b/packages/platform-harmonyos/src/toolbox.fixtures.ts new file mode 100644 index 0000000000..7ab580d03f --- /dev/null +++ b/packages/platform-harmonyos/src/toolbox.fixtures.ts @@ -0,0 +1,206 @@ +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { PlatformHost } from 'agent-device/plugins'; +import type { HarmonyCommandResult } from './command-host.ts'; +import { createHarmonyToolbox, type HarmonyToolbox } from './toolbox.ts'; +import type { HarmonyHdcRunner } from './hdc.ts'; + +/** One command this stubbed host was asked to run, plus the environment it was handed. */ +export type HarmonyHostStubCommand = Readonly<{ + executable: string; + args: readonly string[]; + env: HostEnvironment['env'] | undefined; + timeoutMs: number | undefined; + allowFailure: boolean | undefined; + signal: AbortSignal | undefined; +}>; + +export type HarmonyHostStub = Readonly<{ + toolbox: HarmonyToolbox; + host: PlatformHost; + /** Every command the plugin asked the host to run, in order. */ + commands: HarmonyHostStubCommand[]; + /** Queues one answer for the next command; exit code 0 is the common case. */ + answer(answer?: Partial & Readonly<{ stdout?: string }>): void; +}>; + +const NO_ANSWER: HarmonyCommandResult = Object.freeze({ + stdout: '', + stderr: 'harmony-host-stub: no answer queued', + exitCode: 1, +}); + +/** + * Binds the plugin's toolbox to an in-memory host for colocated unit tests: nothing spawns, and + * every command the plugin asks for is recorded with the environment the plugin built. Tests assert + * on the argv and on `PATH`, which is what the family's toolchain contract is. + */ +export function createHarmonyHostStub( + input: Readonly<{ + env?: Readonly>; + /** Answers one command. Takes precedence over the queued answers. */ + respond?: ( + executable: string, + args: readonly string[], + ) => Partial & Readonly<{ stdout?: string }>; + /** Rejected one command, the way the host rejects a spawn it cannot start. */ + reject?: (executable: string, args: readonly string[]) => Error; + }> = {}, +): HarmonyHostStub { + const env = input.env ?? { PATH: '/usr/bin' }; + const commands: HarmonyHostStubCommand[] = []; + const answers: HarmonyCommandResult[] = []; + const host = Object.freeze({ + env, + cwd: '/host-cwd', + stateDir: '/host-state', + emitDiagnostic: () => {}, + withDiagnosticTimer: async (_phase: string, operation: () => Promise) => + await operation(), + // The host's own executable probe, reading the real filesystem: the family's documented-root + // probe stays a real answer here rather than a stubbed verdict, so a test that names a root + // proves the plugin resolves HDC from it. + isFileExecutable: async (candidate: string) => { + try { + const stat = await fs.promises.stat(candidate); + await fs.promises.access(candidate, fs.constants.X_OK); + return stat.isFile(); + } catch { + return false; + } + }, + runCommand: async ( + executable: string, + args: string[], + options: { + env?: Readonly>; + timeoutMs?: number; + allowFailure?: boolean; + signal?: AbortSignal; + }, + ): Promise => { + commands.push({ + executable, + args, + env: options.env, + timeoutMs: options.timeoutMs, + allowFailure: options.allowFailure, + signal: options.signal, + }); + if (input.reject) throw input.reject(executable, args); + if (input.respond) return toResult(input.respond(executable, args)); + return answers.shift() ?? NO_ANSWER; + }, + }) as unknown as PlatformHost; + return Object.freeze({ + toolbox: createHarmonyToolbox(host), + host, + commands, + answer: (answer) => { + answers.push(toResult(answer)); + }, + }); +} + +/** + * The plugin's toolbox with one part replaced, for a test about one module's HDC calls rather than + * about the host seam. `createHarmonyHdcRunnerStub` records what the module asked the device. + */ +export function createHarmonyToolboxWith( + toolbox: HarmonyToolbox, + overrides: Readonly<{ hdc?: HarmonyHdcRunner }>, +): HarmonyToolbox { + return Object.freeze({ ...toolbox, ...overrides }); +} + +/** + * A toolchain root the plugin can find: a scratch directory holding an executable `hdc`, so the + * family's documented-root probe answers for real instead of through a stubbed filesystem. + */ +export function createHarmonyToolchainRoot(contents = '#!/bin/sh\necho stub\n'): string { + const root = mkdtempForTestSync('harmony-toolchain-'); + fs.writeFileSync(path.join(root, 'hdc'), contents, { mode: 0o755 }); + return root; +} + +/** The `PATH` entries the plugin handed one command. */ +export function harmonyCommandPath(command: HarmonyHostStubCommand): readonly string[] { + return (command.env?.PATH ?? '').split(path.delimiter).filter(Boolean); +} + +/** One HDC call a module made through the family's HDC route. */ +export type HarmonyHdcStubCall = Readonly<{ + kind: 'launch' | 'run' | 'runShell'; + target: string | undefined; + /** The command words as the module passed them; shell words for `runShell`. */ + args: readonly unknown[]; + options: Readonly>; +}>; + +export type HarmonyHdcRunnerStub = { + -readonly [K in keyof HarmonyHdcRunner]: HarmonyHdcRunner[K]; +} & Readonly<{ + calls: HarmonyHdcStubCall[]; + /** Queues the answer for the next call of any kind; exit code 0 is the common case. */ + answer(answer?: Partial & Readonly<{ stdout?: string }>): void; +}>; + +/** + * Records the HDC calls a module makes, for tests about one module's commands rather than about the + * host seam. It answers queued results and nothing spawns. + */ +export function createHarmonyHdcRunnerStub( + answers: readonly (Partial & Readonly<{ stdout?: string }>)[] = [], +): HarmonyHdcRunnerStub { + const calls: HarmonyHdcStubCall[] = []; + const queued = answers.map(toResult); + const record = ( + kind: HarmonyHdcStubCall['kind'], + device: Readonly<{ id: string }> | undefined, + args: readonly unknown[], + options: Readonly>, + ): HarmonyCommandResult => { + calls.push({ kind, target: device?.id, args, options: { ...options } }); + return queued.shift() ?? { stdout: '', stderr: '', exitCode: 0 }; + }; + return { + calls, + answer: (answer) => { + queued.push(toResult(answer)); + }, + executable: async () => 'hdc', + launch: async (args, options) => record('launch', undefined, args, options ?? {}), + run: async (device, args, options) => record('run', device, args, options ?? {}), + runShell: async (device, words, options) => + record('runShell', device, [...words], options ?? {}), + }; +} + +/** Fills the parts of a host answer a test does not name: exit code 0 and empty streams. */ +/** + * Rewrites the stdout of the shell reads a test names, while still recording the call. Use it when + * a test is about the answer a module gets; assert on `calls` for the argv behind it. + */ +export function answerHarmonyShell( + stub: HarmonyHdcRunnerStub, + answer: (words: readonly unknown[]) => string | undefined, +): void { + const runShell = stub.runShell; + stub.runShell = async (device, words, options) => { + const result = await runShell(device, words, options); + const stdout = answer(words); + return stdout === undefined ? result : { ...result, stdout }; + }; +} + +function toResult( + answer?: Partial & Readonly<{ stdout?: string }>, +): HarmonyCommandResult { + return { + stdout: answer?.stdout ?? '', + stderr: answer?.stderr ?? '', + exitCode: answer?.exitCode ?? 0, + }; +} diff --git a/packages/platform-harmonyos/src/toolbox.ts b/packages/platform-harmonyos/src/toolbox.ts new file mode 100644 index 0000000000..e1730ee068 --- /dev/null +++ b/packages/platform-harmonyos/src/toolbox.ts @@ -0,0 +1,31 @@ +import type { PlatformHost } from 'agent-device/plugins'; +import { createHarmonyCommandRunner, type HarmonyCommandRunner } from './command-host.ts'; +import { createHarmonyHdcRunner, type HarmonyHdcRunner } from './hdc.ts'; + +/** + * Everything the HarmonyOS family needs from the machine it runs on, built once from the + * `PlatformHost` the core hands `setup()`, and shared by inventory, the runtime, the interactor and + * the recorder. + * + * It exists so the plugin never reaches for process globals of its own. The package is bundled with + * its own copy of the host kit, and the daemon's command scope never enters that copy, so a spawn + * made through it would run with the daemon's environment and outside the request's exec trace. + * Going through the host keeps resolution, cwd, environment and diagnostics where the core put them. + */ +export type HarmonyToolbox = Readonly<{ + /** Host commands, run with the documented HarmonyOS toolchain roots already on `PATH`. */ + commands: HarmonyCommandRunner; + /** The HDC route: one launcher, scoped to one target per call. */ + hdc: HarmonyHdcRunner; + /** Timings and traces for this family's operations, in the request's diagnostic store. */ + withDiagnosticTimer: PlatformHost['withDiagnosticTimer']; +}>; + +export function createHarmonyToolbox(host: PlatformHost): HarmonyToolbox { + const commands = createHarmonyCommandRunner(host); + return Object.freeze({ + commands, + hdc: createHarmonyHdcRunner(commands), + withDiagnosticTimer: host.withDiagnosticTimer, + }); +} diff --git a/packages/platform-harmonyos/test/package-smoke.mjs b/packages/platform-harmonyos/test/package-smoke.mjs index ea887125a2..e4a98b22cd 100644 --- a/packages/platform-harmonyos/test/package-smoke.mjs +++ b/packages/platform-harmonyos/test/package-smoke.mjs @@ -7,6 +7,52 @@ import { test } from 'node:test'; const repo = path.resolve(import.meta.dirname, '../../..'); +/** + * A stand-in for the HarmonyOS HDC toolchain, installed into a directory that is the only + * `HDC_SDK_PATH` root the plugin is told about. It answers the commands this family asks a target, + * and appends every invocation to `logFile` so the test can prove which executable ran and with what + * `PATH`. The log path is baked in rather than passed by environment: the plugin builds each spawn + * environment from the host it was set up with, so nothing this fixture needs travels through it. + */ +function hdcStubSource(logFile) { + return [ + '#!/usr/bin/env node', + "const fs = require('node:fs');", + 'const args = process.argv.slice(2);', + 'const joined = args.join(" ");', + 'fs.appendFileSync(' + + JSON.stringify(logFile) + + String.raw`, "ARGS: " + joined + "\nPATH: " + process.env.PATH + "\n");`, + String.raw`const answer = (text) => process.stdout.write(text + "\n");`, + 'const LAYOUT = JSON.stringify({', + ' attributes: { type: "root", bounds: "[0,0][1080,2340]" },', + ' children: [', + ' {', + ' attributes: {', + ' type: "Button",', + ' text: "Continue",', + ' clickable: "true",', + ' bounds: "[84,1127][1172,1295]",', + ' },', + ' },', + ' ],', + '});', + 'if (joined.includes("list targets")) answer("stub-target");', + 'else if (joined.includes("const.product.name")) answer("StubPhone");', + 'else if (joined.includes("const.build.characteristics")) answer("default");', + 'else if (joined.includes("bm dump -n"))', + ' answer(JSON.stringify({ hapModuleInfos: [{ moduleName: "entry", mainElementName: "EntryAbility" }] }));', + 'else if (joined.includes("aa start")) answer("start ability successfully.");', + 'else if (joined.includes("dumpLayout")) answer("DumpLayout saved to:/data/local/tmp/layout.json");', + 'else if (args[2] === "file" && args[3] === "recv") {', + ' const destination = args[5];', + ' if (destination.endsWith(".json")) fs.writeFileSync(destination, LAYOUT);', + ' else fs.writeFileSync(destination, Buffer.from([0xff, 0xd8, 0xff, 0xd9]));', + ' answer("FileTransfer finish");', + '} else answer("No errors.");', + ].join('\n'); +} + test('packed core discovers harmonyos only after the managed platform is installed', () => { const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-harmonyos-pack-')); // HDC is a host tool the plugin reads through PATH and through the three documented SDK roots. @@ -38,12 +84,12 @@ test('packed core discovers harmonyos only after the managed platform is install // Help is the CLI's local fast path: it renders text and never takes `--json`. const cliText = (...args) => exec(process.execPath, ['node_modules/agent-device/bin/agent-device.mjs', ...args], scratch); - const runCli = (expectedExit, ...args) => { + const runCliWith = (environment, expectedExit, ...args) => { const invoke = () => execFileSync( process.execPath, ['node_modules/agent-device/bin/agent-device.mjs', ...args, '--json'], - { cwd: scratch, env: cliEnv, encoding: 'utf8', timeout: 120_000 }, + { cwd: scratch, env: environment, encoding: 'utf8', timeout: 120_000 }, ); try { const reply = JSON.parse(invoke()); @@ -54,6 +100,7 @@ test('packed core discovers harmonyos only after the managed platform is install throw error; } }; + const runCli = (expectedExit, ...args) => runCliWith(cliEnv, expectedExit, ...args); try { const [packed] = JSON.parse( exec('npm', ['pack', '--ignore-scripts', '--json', '--pack-destination', scratch], repo), @@ -111,6 +158,67 @@ test('packed core discovers harmonyos only after the managed platform is install assert.ok( plugins.some((plugin) => plugin.platform === 'harmonyos' && plugin.state === 'active'), ); + + // Now the same store with the family's toolchain present, named only by `HDC_SDK_PATH`: the + // packed plugin must run a whole interaction on commands it resolved from that root. Nothing in + // the bundle spawns through its own copy of the host kit, so the replies and the recorded calls + // are the plugin's route through the host it was set up with. + const toolchainRoot = path.join(scratch, 'toolchains'); + fs.mkdirSync(toolchainRoot, { recursive: true }); + const hdcCalls = path.join(scratch, 'hdc-calls.log'); + const stub = path.join(toolchainRoot, 'hdc'); + fs.writeFileSync(stub, hdcStubSource(hdcCalls), 'utf8'); + fs.chmodSync(stub, 0o755); + // The stub stays off `PATH`, so a call reaching it can only have come from the documented root. + const reachableFromPath = (cliEnv.PATH ?? '') + .split(path.delimiter) + .filter(Boolean) + .some((dir) => fs.existsSync(path.join(dir, 'hdc'))); + assert.ok(!reachableFromPath, 'the fixture HDC must not be reachable through PATH'); + // The running daemon was launched without the root, so the plugin needs a host that carries it. + runCli(0, 'daemon', 'stop'); + const toolchainEnv = { ...cliEnv, HDC_SDK_PATH: toolchainRoot }; + + const found = runCliWith(toolchainEnv, 0, 'devices', '--platform', 'harmonyos'); + assert.deepEqual( + found.data.devices.map(({ id, name }) => ({ id, name })), + [{ id: 'stub-target', name: 'StubPhone' }], + ); + const opened = runCliWith( + toolchainEnv, + 0, + 'open', + 'com.example.app', + '--platform', + 'harmonyos', + ); + assert.equal(opened.data.message, 'Opened: com.example.app'); + const pressed = runCliWith(toolchainEnv, 0, 'press', '100', '200', '--platform', 'harmonyos'); + assert.equal(pressed.data.targetKind, 'point'); + runCliWith(toolchainEnv, 0, 'close', '--platform', 'harmonyos'); + + const recorded = fs.readFileSync(hdcCalls, 'utf8').split('\n').filter(Boolean); + const invoked = recorded.filter((line) => line.startsWith('ARGS: ')); + const paths = recorded.filter((line) => line.startsWith('PATH: ')); + assert.equal(paths.length, invoked.length, 'each recorded call names the PATH it ran with'); + assert.ok( + invoked.some((line) => line.endsWith('list targets')), + `discovery never ran the toolchain probe: ${invoked.join(' | ')}`, + ); + assert.ok( + invoked.some((line) => line.endsWith('shell uitest uiInput click 100 200')), + `the press command never reached HDC through the documented root: ${invoked.join(' | ')}`, + ); + assert.ok( + invoked.every((line) => line === 'ARGS: list targets' || line.includes('-t stub-target')), + 'every call after discovery names the discovered target', + ); + // Each spawn got the root ahead of the host PATH, which is how the plugin reaches HDC without + // the core naming HarmonyOS configuration. + assert.ok( + paths.every((line) => line.startsWith(`PATH: ${toolchainRoot}${path.delimiter}`)), + `HDC ran with a PATH the plugin did not build: ${paths.join(' | ')}`, + ); } finally { try { if (fs.existsSync(path.join(scratch, 'node_modules/agent-device'))) diff --git a/packages/platform-harmonyos/tsconfig.json b/packages/platform-harmonyos/tsconfig.json index 5acae24d04..9852f4d325 100644 --- a/packages/platform-harmonyos/tsconfig.json +++ b/packages/platform-harmonyos/tsconfig.json @@ -17,7 +17,6 @@ { "path": "../contracts" }, { "path": "../host-kit" }, { "path": "../kernel" }, - { "path": "../provision-kit" }, { "path": "../test-kit" } ] } diff --git a/packages/platform-vega/src/index.test.ts b/packages/platform-vega/src/index.test.ts index 4212e02a75..6520777503 100644 --- a/packages/platform-vega/src/index.test.ts +++ b/packages/platform-vega/src/index.test.ts @@ -13,7 +13,12 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => { return { ...actual, runCmd: vi.fn(), whichCmd: vi.fn() }; }); -import { runCmd, whichCmd, withCommandHost } from '@agent-device/host-kit/command'; +import { + runCmd, + whichCmd, + withCommandHost, + isExecutablePath, +} from '@agent-device/host-kit/command'; import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; import vegaPlatformPlugin from './index.ts'; @@ -80,6 +85,7 @@ function createPluginHost(): PlatformHost { cwd: scratch, stateDir: path.join(scratch, 'state'), runCommand: runCmd, + isFileExecutable: isExecutablePath, 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 13f5175bef..2b835ca1a6 100644 --- a/packages/platform-web/src/index-startup-cleanup.test.ts +++ b/packages/platform-web/src/index-startup-cleanup.test.ts @@ -18,13 +18,14 @@ vi.mock('./agent-browser-lifecycle.ts', async (importOriginal) => ({ import webPlatformPlugin from './index.ts'; import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; -import { runCmd } from '@agent-device/host-kit/command'; +import { runCmd, isExecutablePath } from '@agent-device/host-kit/command'; function cleanupWebBrowserOrphansForDaemonStartup(stateDir: string) { const host = { ...createLiveTestHostEnvironment(), stateDir, runCommand: runCmd, + isFileExecutable: isExecutablePath, emitDiagnostic, withDiagnosticTimer, }; diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts index 897f37bddb..ce9375b53d 100644 --- a/packages/plugins/src/platform.test.ts +++ b/packages/plugins/src/platform.test.ts @@ -48,6 +48,7 @@ async function startStore(env: HostEnvironment['env']) { runCommand: async () => { throw new Error('setup must not start a process'); }, + isFileExecutable: async () => false, emitDiagnostic: () => {}, withDiagnosticTimer: async (_phase, run) => await run(), }, diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index f379f79f46..3b9025ddb6 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -33,6 +33,12 @@ export type PlatformHost = HostEnvironment & stdin?: string; }, ): Promise<{ stdout: string; stderr: string; exitCode: number }>; + /** + * True when `path` is a file the host can execute. A plugin that resolves a tool from a + * directory it was configured with asks the host rather than reading the filesystem itself, so + * the probe uses the same host authority as the spawn it authorizes. + */ + isFileExecutable(path: string): Promise; emitDiagnostic(event: DiagnosticEventInput): void; withDiagnosticTimer: typeof withDiagnosticTimer; }>; diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index 5c7a8f31d8..f0fa87ed5d 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -350,7 +350,6 @@ const VEGA_OPERATIONS: Record = { const HARMONY_OPERATIONS: Record = { toolchainCheck: true, - prepareToolchain: true, }; const PLATFORM_SETUP_CHECKS: Partial) => void>> = { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c416c54eaa..d1f3137a39 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -297,6 +297,9 @@ importers: packages/build-config: devDependencies: + '@agent-device/test-kit': + specifier: workspace:* + version: link:../test-kit rolldown: specifier: 1.2.5 version: 1.2.5 @@ -825,9 +828,6 @@ importers: '@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 diff --git a/scripts/layering/platform-package-policy.test.ts b/scripts/layering/platform-package-policy.test.ts index b42dd1a7df..4e6c2419f4 100644 --- a/scripts/layering/platform-package-policy.test.ts +++ b/scripts/layering/platform-package-policy.test.ts @@ -914,3 +914,47 @@ test('managed platform code enters core only through the registry', () => { ), ); }); + +// A managed plugin ships its own copy of host-kit, so the daemon's command scope and request +// 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. +for (const family of ['web', 'vega', 'harmonyos'] as const) { + test(`a managed platform package reaches the host-kit command or diagnostics scope only in its listed migration files (${family})`, () => { + const file = `packages/platform-${family}/src/new-surface.ts`; + for (const specifier of [ + '@agent-device/host-kit/command', + '@agent-device/host-kit/diagnostics', + ]) { + const found = messages( + new Map([ + ...validSources(), + [file, `import { runCmd } from '${specifier}';\nvoid runCmd;`], + ]), + ); + assert.ok( + found.some( + (message) => + message.includes(`@agent-device/${family} may not import the host-kit`) && + message.includes('PlatformHost given to setup'), + ), + `${family} must not spawn or trace through its own host-kit copy: ${specifier}`, + ); + } + }); +} + +test('a type-only host-kit import stays legal in a managed platform package', () => { + const sources = new Map([ + ...validSources(), + [ + 'packages/platform-harmonyos/src/new-surface.ts', + "import type { HostCommandResult } from '@agent-device/host-kit/command';\nexport type R = HostCommandResult;", + ], + ]); + assert.deepEqual( + checkPlatformPackagePolicy(sources, declarations()).filter((violation) => + violation.message.includes('host-kit'), + ), + [], + ); +}); diff --git a/scripts/layering/platform-package-policy.ts b/scripts/layering/platform-package-policy.ts index b9f500bb27..ac5b16fce4 100644 --- a/scripts/layering/platform-package-policy.ts +++ b/scripts/layering/platform-package-policy.ts @@ -115,6 +115,63 @@ const MANAGED_PLATFORMS: Readonly>> = { harmonyos: '@agent-device/harmonyos', }; +// The host-kit scopes a managed platform package must never reach at runtime. `command` reads the +// daemon's ambient command scope and `diagnostics` reads its request diagnostic store, and a managed +// plugin is bundled with its own copy of host-kit, so the daemon's scope never enters that copy: a +// spawn or trace made through it runs with the daemon process environment, outside the request's +// captured environment and exec trace. A managed plugin therefore binds to the `PlatformHost` its +// `setup` receives. Type-only edges are allowed — they cost the bundle nothing. +const MANAGED_HOST_KIT_SCOPES = [ + '@agent-device/host-kit/command', + '@agent-device/host-kit/diagnostics', +]; + +// The web and Vega files that still import one of those scopes, as of the HarmonyOS plugin (#4317). +// Each entry is that package's own migration slice, not an exception to this rule: no file joins the +// list, and an entry leaves it when its file binds to the host its plugin was set up with. HarmonyOS +// carries no entry: its plugin builds one HDC command runner from `host.runCommand` in `setup`, so +// its packed bundle carries no separate host-kit command or diagnostics scope. +const MANAGED_HOST_KIT_IMPORT_DEBT: Readonly> = { + '@agent-device/web': [ + 'packages/platform-web/src/agent-browser-install.ts', + 'packages/platform-web/src/agent-browser-lifecycle.ts', + 'packages/platform-web/src/agent-browser-process-record.ts', + 'packages/platform-web/src/agent-browser-provider.ts', + 'packages/platform-web/src/agent-browser-tool.ts', + 'packages/platform-web/src/interactor.ts', + ], + '@agent-device/vega': [ + 'packages/platform-vega/src/app-lifecycle.ts', + 'packages/platform-vega/src/input-actions.ts', + 'packages/platform-vega/src/inventory.ts', + 'packages/platform-vega/src/tool-provider.ts', + 'packages/platform-vega/src/vega-executable.ts', + ], + '@agent-device/harmonyos': [], +}; + +function isManagedHostKitScope(spec: string): boolean { + return MANAGED_HOST_KIT_SCOPES.some((scope) => spec === scope || spec.startsWith(`${scope}/`)); +} + +function managedHostKitScopeViolations( + file: string, + site: { spec: string; line: number; typeOnly: boolean }, + managedName: string, +): LayeringViolation[] { + if (site.typeOnly || !isManagedHostKitScope(site.spec)) return []; + if ((MANAGED_HOST_KIT_IMPORT_DEBT[managedName] ?? []).includes(file)) return []; + return [ + violation( + file, + site.line, + `${managedName} may not import the host-kit '${site.spec}' scope at runtime: run the command ` + + 'or emit the diagnostic through the PlatformHost given to setup, so the packed plugin stays ' + + 'inside the request environment and exec trace', + ), + ]; +} + const INTERACTOR_COMPOSITION_FILE = 'src/core/interactors/register-builtins.ts'; function isInteractorSubpathImport( @@ -392,6 +449,10 @@ function checkSource(file: string, source: string): LayeringViolation[] { ); } if (!ownerFamily) continue; + const managedName = MANAGED_PLATFORMS[ownerFamily as PlatformFamily]; + if (managedName && isProductionSourceFile(file)) { + violations.push(...managedHostKitScopeViolations(file, site, managedName)); + } if ( site.spec.startsWith('@agent-device/') && !site.spec.startsWith('@agent-device/contracts/') && diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 0b25363701..77610a9a69 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -97,7 +97,7 @@ Command shape: Bootstrap: open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; no provider fallback. - An absent optional platform returns details.reason plugin-not-installed with its install command. HarmonyOS is an optional platform: agent-device plugins add @agent-device/harmonyos. + An absent optional platform returns details.reason plugin-not-installed with its install command. Install arguments are app/package id then artifact path: agent-device install com.example.app ./dist/app.apk --platform android, then open --relaunch for fresh state. Use reinstall only when explicitly requested. Unknown app id: devices, then apps, then open . Never open artifact paths or invent package ids; ask if lookup misses the target. Apple CI: prepare ios-runner after boot/install, before replay/test (help prepare). Remote/cloud: connect -> open -> commands -> close -> disconnect (help remote). Reusable scripts, secret-safe fills, replay repair: help scripting. diff --git a/src/platform-runtime-host.ts b/src/platform-runtime-host.ts index 6f045c1ac1..366844f90e 100644 --- a/src/platform-runtime-host.ts +++ b/src/platform-runtime-host.ts @@ -1,5 +1,4 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import type { HarmonyPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { DeviceInventoryHost, HostOperatingSystem, @@ -15,10 +14,7 @@ import { createHostToolchainPreparer } from './platform-runtime-toolchain-host.t import { createHostCommandRunner } from './platform-runtime-host-command-runner.ts'; import { hostHomeDirectoryFromEnv } from '@agent-device/host-kit/host-file'; -export function createDeviceInventoryHost( - host: HostEnvironment, - harmony?: HarmonyPlatformSelection, -): DeviceInventoryHost { +export function createDeviceInventoryHost(host: HostEnvironment): DeviceInventoryHost { const env = host.env; // The host names its own home; families derive default-install paths from it (#3794). A host // that names none (HOME and USERPROFILE both absent, e.g. env -i or a systemd unit without @@ -28,7 +24,7 @@ export function createDeviceInventoryHost( return Object.freeze({ commands: createHostCommandRunner(host), appleTools: createAppleToolHost(), - toolchains: createHostToolchainPreparer(env, harmony), + toolchains: createHostToolchainPreparer(env), files: Object.freeze({ isExecutable: async (candidate: string) => await isExecutable(candidate), createTemporaryTextFile: async (options: { prefix: string; suffix: string }) => diff --git a/src/platform-runtime-operation-host.ts b/src/platform-runtime-operation-host.ts index 941c323856..bb9641c9dc 100644 --- a/src/platform-runtime-operation-host.ts +++ b/src/platform-runtime-operation-host.ts @@ -1,5 +1,4 @@ import type { - HarmonyPlatformSelection, PlatformPluginSet, WebPlatformSelection, } from '@agent-device/contracts/platform-plugin'; @@ -58,7 +57,6 @@ export async function loadMacOsSurfaceSnapshot( export function createPlatformRuntimeHost(options: { host: HostEnvironment; web?: WebPlatformSelection; - harmony?: HarmonyPlatformSelection; interactors?: PlatformPluginSet; sessionsDir: string; resolveSessionArtifacts(sessionId: string): AppLogSessionArtifacts; @@ -89,7 +87,7 @@ export function createPlatformRuntimeHost(options: { hostEnvironment: host, commands, appleTools, - toolchains: createHostToolchainPreparer(env, options.harmony), + toolchains: createHostToolchainPreparer(env), artifacts: Object.freeze({ resolveSession: options.resolveSessionArtifacts }), outputs: Object.freeze({ openAppend: async (pathname: string) => diff --git a/src/platform-runtime-toolchain-host.test.ts b/src/platform-runtime-toolchain-host.test.ts index 8d9a690f6a..873e8acfff 100644 --- a/src/platform-runtime-toolchain-host.test.ts +++ b/src/platform-runtime-toolchain-host.test.ts @@ -1,13 +1,8 @@ import { expect, test, vi } from 'vitest'; -import type { - HarmonyPlatformRegistration, - HarmonyPlatformSelection, -} from '@agent-device/contracts/platform-plugin'; const toolchains = vi.hoisted(() => ({ androidEvaluations: 0, androidPrepares: 0, - harmonyPrepares: 0, })); vi.mock('@agent-device/platform-android/mechanics', () => { @@ -21,31 +16,23 @@ vi.mock('@agent-device/platform-android/mechanics', () => { import { createHostToolchainPreparer } from './platform-runtime-toolchain-host.ts'; -/** A selection whose only live member is the toolchain preparation the host arm calls. */ -function harmonySelectionFixture(): HarmonyPlatformSelection { - const active = { - operations: { - prepareToolchain: async () => { - toolchains.harmonyPrepares += 1; - }, - }, - } as unknown as HarmonyPlatformRegistration; - return { active, get: () => active }; -} - -test('toolchain host loads and prepares only the selected family', async () => { - const host = createHostToolchainPreparer(process.env, harmonySelectionFixture()); +test('the toolchain host loads and prepares the android mechanics once', async () => { + const host = createHostToolchainPreparer(process.env); - expect(toolchains).toEqual({ androidEvaluations: 0, androidPrepares: 0, harmonyPrepares: 0 }); + expect(toolchains).toEqual({ androidEvaluations: 0, androidPrepares: 0 }); await host.prepare('android'); - expect(toolchains).toEqual({ androidEvaluations: 1, androidPrepares: 1, harmonyPrepares: 0 }); - - await host.prepare('harmonyos'); - expect(toolchains).toEqual({ androidEvaluations: 1, androidPrepares: 1, harmonyPrepares: 1 }); + await host.prepare('android'); + expect(toolchains).toEqual({ androidEvaluations: 1, androidPrepares: 2 }); }); -test('toolchain host answers a HarmonyOS request with nothing before the plugin is installed', async () => { +test('the toolchain host answers every other family with nothing', async () => { + // HarmonyOS owns its toolchain: the plugin runs HDC on its setup host with its documented roots + // on PATH, so the core must not load the android mechanics for a HarmonyOS request. + const before = { ...toolchains }; const host = createHostToolchainPreparer(process.env); + await expect(host.prepare('harmonyos')).resolves.toBeUndefined(); + await expect(host.prepare('web')).resolves.toBeUndefined(); + expect(toolchains).toEqual(before); }); diff --git a/src/platform-runtime-toolchain-host.ts b/src/platform-runtime-toolchain-host.ts index 474b869b26..0920f6602f 100644 --- a/src/platform-runtime-toolchain-host.ts +++ b/src/platform-runtime-toolchain-host.ts @@ -1,24 +1,18 @@ import type { EnvMap } from '@agent-device/kernel/source-value'; -import type { HarmonyPlatformSelection } from '@agent-device/contracts/platform-plugin'; import type { HostToolchainPreparer } from '@agent-device/contracts/platform-runtime-host'; import { loadAndroidMechanics } from './platform-runtime-android-mechanics.ts'; -export function createHostToolchainPreparer( - env: Readonly, - harmony?: HarmonyPlatformSelection, -): HostToolchainPreparer { +/** + * Prepares the toolchains the core still names. The HarmonyOS plugin needs no arm here: it runs + * every HDC command through the host it was set up with, with its documented SDK roots already on + * `PATH`, so nothing in the core has to know that family's toolchain configuration. + */ +export function createHostToolchainPreparer(env: Readonly): HostToolchainPreparer { return Object.freeze({ prepare: async (family) => { if (family === 'android') { const { ensureAndroidSdkPathConfigured } = await loadAndroidMechanics(); await ensureAndroidSdkPathConfigured(env); - return; - } - // Only the HarmonyOS plugin reaches this arm: its device discovery and hilog streaming ask - // the host to prepend the toolchain roots they were configured with. The plugin owns which - // roots those are; the core hands over the host environment it captured. - if (family === 'harmonyos') { - await harmony?.get().operations.prepareToolchain(env); } }, }); diff --git a/src/platform-runtime.ts b/src/platform-runtime.ts index 6ef907e782..0368f7cd73 100644 --- a/src/platform-runtime.ts +++ b/src/platform-runtime.ts @@ -102,7 +102,7 @@ export async function createPlatformDeviceInventoryGateways( registry: createPlatformModuleRegistryForHost(host.env, platforms), loadHost: async () => { const { createDeviceInventoryHost } = await import('./platform-runtime-host.ts'); - return createDeviceInventoryHost(host, platforms?.harmony); + return createDeviceInventoryHost(host); }, provider, env: host.env, @@ -145,7 +145,6 @@ export function createPlatformRuntimeGateway( return createPlatformRuntimeHost({ host: options.host, web: options.platforms.web, - harmony: options.platforms.harmony, interactors: options.platforms.interactors, sessionsDir: options.sessionsDir, resolveSessionArtifacts: options.resolveSessionArtifacts, diff --git a/src/platform-runtime/plugin-host.test.ts b/src/platform-runtime/plugin-host.test.ts new file mode 100644 index 0000000000..7fb240f0f0 --- /dev/null +++ b/src/platform-runtime/plugin-host.test.ts @@ -0,0 +1,23 @@ +import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { expect, test } from 'vitest'; +import { createPlatformPluginHost } from './plugin-host.ts'; +import fs from 'node:fs'; +import path from 'node:path'; + +// The managed HarmonyOS plugin resolves HDC from the toolchain roots its host names, and it asks +// this host whether a candidate is executable rather than reading the filesystem itself (R13). A +// host that cannot answer makes the family report a missing toolchain, so the port has to work. +test('the platform plugin host answers whether a path is an executable file', () => { + const root = mkdtempForTestSync('plugin-host-executable-'); + const script = path.join(root, 'hdc'); + fs.writeFileSync(script, '#!/bin/sh\necho stub\n', { mode: 0o755 }); + const notAFile = path.join(root, 'missing'); + fs.writeFileSync(path.join(root, 'notes.txt'), 'text\n'); + const host = createPlatformPluginHost(createLiveTestHostEnvironment(), root); + + return Promise.all([ + expect(host.isFileExecutable(script)).resolves.toBe(true), + expect(host.isFileExecutable(path.join(root, 'notes.txt'))).resolves.toBe(false), + expect(host.isFileExecutable(notAFile)).resolves.toBe(false), + ]); +}); diff --git a/src/platform-runtime/plugin-host.ts b/src/platform-runtime/plugin-host.ts index ed3a12b106..95f18a139e 100644 --- a/src/platform-runtime/plugin-host.ts +++ b/src/platform-runtime/plugin-host.ts @@ -17,5 +17,9 @@ export function createPlatformPluginHost( const { runCmd } = await import('@agent-device/host-kit/command'); return await runCmd(executable, args, options); }, + isFileExecutable: async (path) => { + const { isExecutablePath } = await import('@agent-device/host-kit/command'); + return await isExecutablePath(path); + }, } satisfies PlatformHost); } From de014dd8fba394f0bda366c1102cc13eb099fe4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 23:11:27 +0100 Subject: [PATCH 4/5] refactor(harmonyos): bind the plugin's toolbox on first command The facade said the toolbox binds on first use while `setup` built it immediately, so the resolution is now lazy and memoized per setup: a setup that never runs a command imports and builds nothing, and the operations of one setup still share the one toolbox that binds its host. One toolchain root probe per spawn instead of two: `resolveHdc` read a Promise of the resolved HDC through a doubled await. The packed-plugin smoke now also runs `snapshot -i` and `screenshot` against the stub `hdc`, asserting each CLI reply, the JPEG the stub wrote, and the layout-dump and frame-capture argv the stub recorded, so the evidence file names the six commands the gate covers. --- .../harmonyos-managed-platform-2026-11-20.md | 8 +++-- .../platform-harmonyos/src/command-host.ts | 2 +- packages/platform-harmonyos/src/index.ts | 29 ++++++++++++------- .../platform-harmonyos/test/package-smoke.mjs | 21 ++++++++++++++ 4 files changed, 45 insertions(+), 15 deletions(-) diff --git a/docs/evidence/harmonyos-managed-platform-2026-11-20.md b/docs/evidence/harmonyos-managed-platform-2026-11-20.md index a22b532a21..4ea49ebf79 100644 --- a/docs/evidence/harmonyos-managed-platform-2026-11-20.md +++ b/docs/evidence/harmonyos-managed-platform-2026-11-20.md @@ -17,9 +17,11 @@ fixture below plus the plugin's unit coverage of every HDC argv. ## Packed plugin, one stub HDC, reachable only through `HDC_SDK_PATH` -The same sequence now runs as a gate: `packages/platform-harmonyos/test/package-smoke.mjs`. What -follows is a manual run of it against this host, kept because it shows the raw replies and the exec -trace the plugin's commands land in. +`packages/platform-harmonyos/test/package-smoke.mjs` runs this sequence as a gate inside +`pnpm run check:package`: `devices`, `open`, `snapshot -i`, `screenshot`, `press` and `close`, each +asserted on its CLI reply and on the argv the stub recorded. What follows is a manual run of the same +sequence against this host, kept because it shows the raw replies and the exec trace the plugin's +commands land in. Setup: a scratch project, an isolated store (`AGENT_DEVICE_HOME`, `AGENT_DEVICE_STATE_DIR`, `AGENT_DEVICE_CLAIMS_DIR` under scratch), `PATH` reduced to the Node directory, `/usr/bin` and diff --git a/packages/platform-harmonyos/src/command-host.ts b/packages/platform-harmonyos/src/command-host.ts index 1a867c15b6..cc28c5f33d 100644 --- a/packages/platform-harmonyos/src/command-host.ts +++ b/packages/platform-harmonyos/src/command-host.ts @@ -55,7 +55,7 @@ export function createHarmonyCommandRunner(host: PlatformHost): HarmonyCommandRu ...options, env: await harmonySpawnEnvironment(env, isExecutable), }), - resolveHdc: async () => (await await harmonyToolchainHdc(env, isExecutable)) ?? 'hdc', + resolveHdc: async () => (await harmonyToolchainHdc(env, isExecutable)) ?? 'hdc', toolchainHdc: async () => await harmonyToolchainHdc(env, isExecutable), }); } diff --git a/packages/platform-harmonyos/src/index.ts b/packages/platform-harmonyos/src/index.ts index 8e3ba0ac91..1099f3117a 100644 --- a/packages/platform-harmonyos/src/index.ts +++ b/packages/platform-harmonyos/src/index.ts @@ -1,4 +1,5 @@ import type { PlatformContribution, PlatformHost } from 'agent-device/plugins'; +import type { HarmonyToolbox } from './toolbox.ts'; import type { InventoryPlatformModule, PlatformModuleMetadata, @@ -20,10 +21,16 @@ const metadata = Object.freeze({ */ let toolboxModule: Promise | undefined; -async function harmonyToolbox(host: PlatformHost) { - toolboxModule ??= import('./toolbox.ts'); - const { createHarmonyToolbox } = await toolboxModule; - return createHarmonyToolbox(host); +/** + * A bound toolbox, made on first use and then reused: a `setup` that never runs a command imports + * and builds nothing, and the operations of one setup share the one toolbox it binds its host to. + */ +function harmonyToolbox(host: PlatformHost) { + let toolbox: Promise | undefined; + return async () => + (toolbox ??= (toolboxModule ??= import('./toolbox.ts')).then(({ createHarmonyToolbox }) => + createHarmonyToolbox(host), + )); } function harmonyPlatformPlugin() { @@ -33,9 +40,9 @@ function harmonyPlatformPlugin() { { kind: 'platform', family: 'harmonyos', - // The family binds its host on first use rather than in `setup`, so importing this package - // evaluates nothing but itself. Every operation below awaits this same resolution, so one - // setup builds exactly one toolbox for the whole family. + // Importing this package evaluates nothing but itself, and the host is bound to a toolbox + // only when an operation first needs one. Every operation below asks the same lazy + // resolution, so one setup builds exactly one toolbox for the whole family. setup(host: PlatformHost): HarmonyPlatformRegistration { const toolbox = harmonyToolbox(host); const inventoryModule: InventoryPlatformModule<'harmonyos'> = Object.freeze({ @@ -45,14 +52,14 @@ function harmonyPlatformPlugin() { // itself (ADR 0019) nor has the core name its configuration. loadInventory: async () => { const { createHarmonyInventory } = await import('./inventory.ts'); - return createHarmonyInventory(await toolbox); + return createHarmonyInventory(await toolbox()); }, }); const runtimeModule = Object.freeze({ ...metadata, loadRuntime: async (host) => { const { createHarmonyPlatformRuntime } = await import('./runtime.ts'); - return createHarmonyPlatformRuntime(host, await toolbox); + return createHarmonyPlatformRuntime(host, await toolbox()); }, } satisfies PlatformRuntimeModule & { readonly family: 'harmonyos' }); return { @@ -61,13 +68,13 @@ function harmonyPlatformPlugin() { runtimeModule, createInteractor: async (device, runnerContext) => { const { createHarmonyInteractor } = await import('./interactor.ts'); - return createHarmonyInteractor(await toolbox, device, runnerContext); + return createHarmonyInteractor(await toolbox(), device, runnerContext); }, operations: { toolchainCheck: async () => { const [{ harmonyToolchainCheck }, { commands }] = await Promise.all([ import('./doctor.ts'), - toolbox, + toolbox(), ]); return await harmonyToolchainCheck(commands); }, diff --git a/packages/platform-harmonyos/test/package-smoke.mjs b/packages/platform-harmonyos/test/package-smoke.mjs index e4a98b22cd..0f2577b435 100644 --- a/packages/platform-harmonyos/test/package-smoke.mjs +++ b/packages/platform-harmonyos/test/package-smoke.mjs @@ -193,6 +193,17 @@ test('packed core discovers harmonyos only after the managed platform is install 'harmonyos', ); assert.equal(opened.data.message, 'Opened: com.example.app'); + // The two capture commands, so the run covers a layout read and a screen grab as well as a + // gesture: each answers from the stub's own fixture and is asserted on the reply it returned. + const captured = runCliWith(toolchainEnv, 0, 'snapshot', '-i', '--platform', 'harmonyos'); + assert.deepEqual( + captured.data.nodes.map(({ type, value }) => ({ type, value })), + [{ type: 'Button', value: 'Continue' }], + ); + const shot = path.join(scratch, 'screen.png'); + const shotResult = runCliWith(toolchainEnv, 0, 'screenshot', shot, '--platform', 'harmonyos'); + assert.equal(shotResult.data.path, shot); + assert.deepEqual([...fs.readFileSync(shot).subarray(0, 3)], [0xff, 0xd8, 0xff]); const pressed = runCliWith(toolchainEnv, 0, 'press', '100', '200', '--platform', 'harmonyos'); assert.equal(pressed.data.targetKind, 'point'); runCliWith(toolchainEnv, 0, 'close', '--platform', 'harmonyos'); @@ -205,6 +216,16 @@ test('packed core discovers harmonyos only after the managed platform is install invoked.some((line) => line.endsWith('list targets')), `discovery never ran the toolchain probe: ${invoked.join(' | ')}`, ); + assert.ok( + invoked.some((line) => /^ARGS: -t stub-target shell uitest dumpLayout -p \S+$/.test(line)), + `the snapshot never asked the device for a layout: ${invoked.join(' | ')}`, + ); + assert.ok( + invoked.some((line) => + /^ARGS: -t stub-target shell snapshot_display -f \S+\.jpeg$/.test(line), + ), + `the screenshot never asked the device for a frame: ${invoked.join(' | ')}`, + ); assert.ok( invoked.some((line) => line.endsWith('shell uitest uiInput click 100 200')), `the press command never reached HDC through the documented root: ${invoked.join(' | ')}`, From 2edb39e3d0b8b09046a54d0475aeea895dc9d46e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 14:24:52 +0100 Subject: [PATCH 5/5] fix(harmonyos): stream hilog through the plugin's setup host `logs start` ran both of its HDC commands outside the host the plugin was set up with: the PID lookup went through the runtime host's command port and the hilog stream through its local process transport, so neither got the family's documented toolchain roots on `PATH`. A toolchain that needs a sibling executable there served discovery and interaction and failed the stream. The plugin's command runner now owns both routes. The one-shot `pidof` takes `toolbox.hdc.runShell`, and the plan names its own process route: the setup host's new managed background command entry, backed by the same app-log process service the core's own transport uses, so the stream keeps its ownership marker, stop, and cleanup and spawns with the same prepared environment. --- .../capture-kit/src/app-log-pid-process.ts | 6 +- .../capture-kit/src/app-log-pid-runtime.ts | 35 ++- packages/capture-kit/src/index.ts | 1 + .../src/__tests__/hdc.test.ts | 38 +++ .../platform-harmonyos/src/command-host.ts | 60 +++- .../src/logs/runtime.test.ts | 296 +++++++++++------- .../platform-harmonyos/src/logs/runtime.ts | 129 ++++---- .../src/toolbox.fixtures.ts | 62 +++- .../platform-harmonyos/test/package-smoke.mjs | 32 ++ packages/plugins/src/contract.ts | 9 +- packages/plugins/src/platform.ts | 45 +++ src/daemon-composition.ts | 1 + src/platform-runtime/installed-platforms.ts | 8 +- src/platform-runtime/plugin-host.test.ts | 66 ++++ src/platform-runtime/plugin-host.ts | 43 ++- src/sdk/plugins.ts | 3 + 16 files changed, 633 insertions(+), 201 deletions(-) diff --git a/packages/capture-kit/src/app-log-pid-process.ts b/packages/capture-kit/src/app-log-pid-process.ts index 7e9accd46a..6108abed77 100644 --- a/packages/capture-kit/src/app-log-pid-process.ts +++ b/packages/capture-kit/src/app-log-pid-process.ts @@ -18,7 +18,7 @@ export type PidScopedAppLogProcessOptions = Readonly<{ processStart: AppLogProcessStart; setupSignal: AbortSignal; resolvePid(signal?: AbortSignal): Promise; - command(pid: string): AppLogProcessCommand; + command(pid: string): AppLogProcessCommand | Promise; cleanupFailureMessage: string; }>; @@ -42,7 +42,7 @@ export async function createPidScopedAppLogProcess( try { active = await options.processStart( { - command: options.command(initialPid), + command: await options.command(initialPid), output, markerPath: options.pidPath, }, @@ -79,7 +79,7 @@ export async function createPidScopedAppLogProcess( resolvePid: async () => await options.resolvePid(), startProcess: async (pid) => await options.processStart({ - command: options.command(pid), + command: await options.command(pid), output, markerPath: options.pidPath, }), diff --git a/packages/capture-kit/src/app-log-pid-runtime.ts b/packages/capture-kit/src/app-log-pid-runtime.ts index 5fcf160d46..7df9d3392e 100644 --- a/packages/capture-kit/src/app-log-pid-runtime.ts +++ b/packages/capture-kit/src/app-log-pid-runtime.ts @@ -2,6 +2,7 @@ import type { DeviceInfo, Platform } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import type { AppLogProcessCommand, + AppLogProcessStart, AppLogProcessTransport, AppLogRuntimeHost, AppLogRuntimeOperations, @@ -54,7 +55,18 @@ export type PidScopedAppLogStartContext = PidScopedAppLogRuntimeContext & export type PidScopedAppLogProcessPlan = Readonly<{ resolvePid(signal?: AbortSignal): Promise; - command(pid: string): AppLogProcessCommand; + /** + * The command for one application PID. Async so a family can resolve the executable it names on the + * same per-call route it spawns with, rather than caching a resolution made when start began. + */ + command(pid: string): AppLogProcessCommand | Promise; + /** + * Routes this family's stream somewhere other than the runtime host's own process transport, and + * runs the `command` this plan mints there. A family whose command needs a toolchain environment + * the host does not name (a managed platform's setup host, which prepares its documented roots) + * names its own route. Availability still comes from the selected transport. + */ + start?: AppLogProcessStart; }>; type PidScopedAppLogEnvelopeInput = Readonly<{ @@ -94,8 +106,16 @@ export async function resolveFirstNumericAppLogPid( request: HostCommandRequest, signal?: AbortSignal, ): Promise { - const result = await host.commands.run(request, signal); - const pid = result.stdout.trim().split(/\s+/)[0] ?? ''; + return firstNumericAppLogPid((await host.commands.run(request, signal)).stdout); +} + +/** + * The first PID a device answers to an app lookup, or empty when the answer is not one. A family that + * runs the lookup on its own command route reads its answer through this so both routes judge a + * blank, a truncated, or an error-text answer the same way. + */ +export function firstNumericAppLogPid(stdout: string): string { + const pid = stdout.trim().split(/\s+/)[0] ?? ''; return /^\d+$/.test(pid) ? pid : ''; } @@ -236,17 +256,18 @@ async function startPidScopedAppLogs< const context = { host, device, signal, input, artifacts, transport } as const; options.validateStart?.(context); signal.throwIfAborted(); - const process = await options.process(context); + const plan = await options.process(context); signal.throwIfAborted(); const handle = await createPidScopedAppLogProcess({ host, backend: options.backend, outputPath: artifacts.outputPath, pidPath: artifacts.pidPath, - processStart: transport.start, + // The plan owns its route when its commands need an environment the runtime host does not name. + processStart: plan.start ?? transport.start, setupSignal: signal, - resolvePid: process.resolvePid, - command: process.command, + resolvePid: plan.resolvePid, + command: plan.command, cleanupFailureMessage: options.cleanupFailureMessage, }); const descriptor = options.descriptor({ artifacts, transport }); diff --git a/packages/capture-kit/src/index.ts b/packages/capture-kit/src/index.ts index afc77befd0..85b0183487 100644 --- a/packages/capture-kit/src/index.ts +++ b/packages/capture-kit/src/index.ts @@ -20,6 +20,7 @@ export { } from './app-log-process-recovery.ts'; export { createPidScopedAppLogRuntimeOwner, + firstNumericAppLogPid, resolveFirstNumericAppLogPid, } from './app-log-pid-runtime.ts'; export { appLogCommandSucceeded, bestEffortAppLogCheck } from './app-log-probe.ts'; diff --git a/packages/platform-harmonyos/src/__tests__/hdc.test.ts b/packages/platform-harmonyos/src/__tests__/hdc.test.ts index 767859cfd8..a8e211b384 100644 --- a/packages/platform-harmonyos/src/__tests__/hdc.test.ts +++ b/packages/platform-harmonyos/src/__tests__/hdc.test.ts @@ -199,3 +199,41 @@ test('the command runner dedupes a root already on PATH', async () => { assert.deepEqual(harmonyCommandPath(stub.commands[0]!), [root, '/usr/bin']); }); + +test('the command runner streams with the same toolchain environment it runs with', async () => { + // One root, one PATH preparation: a toolchain whose HDC needs a sibling executable on `PATH` has + // to serve the streamed `hilog` as well as it serves a one-shot command. + const root = createHarmonyToolchainRoot(); + const stub = createHarmonyHostStub({ env: { HDC_SDK_PATH: root, PATH: '/usr/bin' } }); + const commands = createHarmonyCommandRunner(stub.host); + + const stream = await commands.start( + await commands.resolveHdc(), + ['-t', 'target-1', 'shell', 'hilog', '-P', '456'], + { + output: { write: async () => {}, [Symbol.asyncDispose]: async () => {} }, + markerPath: '/sessions/s1/app-log.pid', + allowFailure: true, + }, + ); + + assert.equal(stub.streams[0]?.executable, path.join(root, 'hdc')); + assert.deepEqual(stub.streams[0]?.args, ['-t', 'target-1', 'shell', 'hilog', '-P', '456']); + assert.deepEqual(harmonyCommandPath(stub.streams[0]!), [root, '/usr/bin']); + assert.equal(stub.streams[0]?.markerPath, '/sessions/s1/app-log.pid'); + assert.equal(stub.streams[0]?.allowFailure, true); + 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 cc28c5f33d..53a8650061 100644 --- a/packages/platform-harmonyos/src/command-host.ts +++ b/packages/platform-harmonyos/src/command-host.ts @@ -1,5 +1,10 @@ import path from 'node:path'; -import type { PlatformHost } from 'agent-device/plugins'; +import { AppError } from '@agent-device/kernel/errors'; +import type { + PlatformBackgroundProcess, + PlatformHost, + PlatformOutputSink, +} from 'agent-device/plugins'; /** What the host answered a command: its streams and its exit code. */ export type HarmonyCommandResult = Awaited>; @@ -10,6 +15,16 @@ export type HarmonyRunOptions = Readonly<{ signal?: AbortSignal; }>; +/** What a streamed HDC command needs: where its output goes, and where its owner's proof lives. */ +export type HarmonyStreamOptions = Readonly<{ + /** Where the host-managed process's output is appended, opened and owned by the core. */ + output: PlatformOutputSink; + /** The app-log marker path the host publishes while the stream lives and clears when it ends. */ + markerPath?: string; + allowFailure?: boolean; + signal?: AbortSignal; +}>; + /** * The plugin's route to host commands, bound to the `PlatformHost` the core handed `setup()`. The * core owns executable resolution, the spawn environment, and the exec trace, so a `--debug` log @@ -23,7 +38,8 @@ export type HarmonyRunOptions = Readonly<{ * * Each command is launched with the documented HarmonyOS toolchain roots prepended to `PATH`, so this * family resolves the same HDC an interactive shell does while the core names no HarmonyOS - * configuration. + * configuration. A streamed command gets the same preparation, so a toolchain that needs a sibling + * executable on `PATH` serves `logs start` as well as it serves discovery and interaction. */ export type HarmonyCommandRunner = Readonly<{ /** `executable` is an absolute path from a configured root, or a name the host `PATH` resolves. */ @@ -32,10 +48,19 @@ export type HarmonyCommandRunner = Readonly<{ args: readonly string[], options?: HarmonyRunOptions, ): Promise; + /** + * Starts one command the core keeps running after this call returns — the family's `hilog` stream — + * through the setup host's managed process service, so the stream gets an ownership marker, a stop, + * and the same toolchain environment as {@link run}. + */ + start( + executable: string, + args: readonly string[], + options: HarmonyStreamOptions, + ): Promise; /** * HDC to spawn: an absolute path from a documented toolchain root when one carries it, else the - * bare `hdc` for the host `PATH` to resolve. Host-minted commands need the path, because the core - * builds their environment without this family's roots. + * bare `hdc` for the host `PATH` to resolve. */ resolveHdc(): Promise; /** True when a documented root carries an executable HDC, so no `PATH` lookup is needed. */ @@ -49,17 +74,42 @@ export type HarmonyCommandRunner = Readonly<{ export function createHarmonyCommandRunner(host: PlatformHost): HarmonyCommandRunner { const env = host.env; const isExecutable = (candidate: string) => host.isFileExecutable(candidate); + const spawnEnvironment = () => harmonySpawnEnvironment(env, isExecutable); return Object.freeze({ run: async (executable, args, options) => await host.runCommand(executable, [...args], { ...options, - env: await harmonySpawnEnvironment(env, isExecutable), + 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( + { + command: { + executable, + args: [...args], + env: await spawnEnvironment(), + ...(options.allowFailure === undefined ? {} : { allowFailure: options.allowFailure }), + }, + output: options.output, + ...(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/logs/runtime.test.ts b/packages/platform-harmonyos/src/logs/runtime.test.ts index f298ca1fa4..076b29fa69 100644 --- a/packages/platform-harmonyos/src/logs/runtime.test.ts +++ b/packages/platform-harmonyos/src/logs/runtime.test.ts @@ -1,11 +1,14 @@ -import type { - AppLogBackgroundProcess, - AppLogRuntimeHost, -} from '@agent-device/contracts/app-log-runtime'; +import type { AppLogRuntimeHost } from '@agent-device/contracts/app-log-runtime'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { expect, test, vi } from 'vitest'; -import { createHarmonyHostStub, createHarmonyToolchainRoot } from '../toolbox.fixtures.ts'; +import { AppError } from '@agent-device/kernel/errors'; +import { expect, test } from 'vitest'; +import path from 'node:path'; +import { + createHarmonyHostStub, + createHarmonyToolchainRoot, + harmonyCommandPath, +} from '../toolbox.fixtures.ts'; import { createHarmonyAppLogEnvelope, harmonyAppLogDescriptorCodec } from './descriptor.ts'; import { createHarmonyAppLogRuntime } from './runtime.ts'; @@ -23,6 +26,18 @@ const scope: PlatformRequestScope = { progress: { report: () => {} }, }; +const MISSING_HDC = 'hdc not found in PATH'; +const MISSING_HDC_HINT = + 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH or set HDC_SDK_PATH.'; + +/** The app-scoped `logs start` input every start test uses. */ +const startInput = { + sessionId: 'session', + appBundleId: 'com.example.harmony', + outputPath: '/tmp/app.log', + fence: { token: 'fence', generation: 1 }, +}; + test('rejects durable HarmonyOS descriptors without the canonical process marker', () => { expect( harmonyAppLogDescriptorCodec.decode({ @@ -39,21 +54,84 @@ test('starts HarmonyOS hilog with the resolved application pid', async () => { intent: { kind: 'ordinary' }, scope, }); - const started = await binding.operations.appLogStart?.({ - sessionId: 'session', - appBundleId: 'com.example.harmony', - outputPath: '/tmp/app.log', - fence: { token: 'fence', generation: 1 }, - }); - expect(fixture.backgroundCommands).toEqual([ - ['hdc', '-t', 'harmony-1', 'shell', 'hilog', '-P', '456'], + const started = await binding.operations.appLogStart?.(startInput); + + // The PID lookup is an HDC command: the one-shot route asked for `pidof`, and the stream is the + // managed background command the same host started. + expect(fixture.hdcCommands()).toEqual([ + ['-t', 'harmony-1', 'shell', 'pidof', 'com.example.harmony'], ]); + expect(fixture.streams).toHaveLength(1); + expect(fixture.streams[0]!.args).toEqual(['-t', 'harmony-1', 'shell', 'hilog', '-P', '456']); expect(await started?.pendingHandle.transfer().finish()).toMatchObject({ status: 'completed', result: { backend: 'harmonyos' }, }); }); +test('HarmonyOS logs run the PID lookup and the stream on the setup host, not the runtime host', async () => { + const root = createHarmonyToolchainRoot(); + const fixture = hostFixture({ env: { HDC_SDK_PATH: root, PATH: '/usr/bin' } }); + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ + device, + intent: { kind: 'ordinary' }, + scope, + }); + + const started = await binding.operations.appLogStart?.(startInput); + + // Both commands name the HDC the configured root carries, and both were handed a PATH that root + // leads. The core's own local process transport never starts this family's stream: it builds its + // spawn environment without the family's roots. + const [pidLookup] = fixture.hdcCommands(); + expect(pidLookup).toEqual(['-t', 'harmony-1', 'shell', 'pidof', 'com.example.harmony']); + expect(fixture.commandPaths()).toEqual([[root, '/usr/bin']]); + expect(fixture.streams).toHaveLength(1); + expect(fixture.streams[0]!.executable).toBe(path.join(root, 'hdc')); + expect(harmonyCommandPath(fixture.streams[0]!)).toEqual([root, '/usr/bin']); + expect(fixture.streams[0]!.markerPath).toBe('/tmp/app-log.pid'); + expect(fixture.runtimeHostStarts()).toBe(0); + expect(fixture.runtimeHostCommands()).toEqual([]); + await started?.pendingHandle.transfer().finish(); +}); + +test('HarmonyOS log stream answers the runtime host transport it did not use', async () => { + // Availability still comes from the selected transport: the plan replaces only its route. + const fixture = hostFixture(); + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ + device, + intent: { kind: 'ordinary' }, + scope, + }); + + expect(binding.facts.operations.appLogStart).toEqual({ available: true }); + const started = await binding.operations.appLogStart?.(startInput); + await started?.pendingHandle.transfer().finish(); + expect(fixture.runtimeHostStarts()).toBe(0); +}); + +test('rejects a missing HDC tool before opening output or starting a process', async () => { + const fixture = hostFixture({ + reject: (executable) => + new AppError('TOOL_MISSING', MISSING_HDC, { cmd: executable }, undefined), + }); + const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ + device, + intent: { kind: 'ordinary' }, + scope, + }); + + await expect(binding.operations.appLogStart?.(startInput)).rejects.toMatchObject({ + code: 'TOOL_MISSING', + message: MISSING_HDC, + details: { + hint: MISSING_HDC_HINT, + }, + }); + expect(fixture.outputOpens()).toBe(0); + expect(fixture.streams).toEqual([]); +}); + test('rejects cross-session start and recovery paths before host authority is used', async () => { const fixture = hostFixture(); const runtimeOwner = createHarmonyAppLogRuntime(fixture.host, fixture.toolbox); @@ -88,65 +166,14 @@ test('rejects cross-session start and recovery paths before host authority is us ).rejects.toMatchObject({ code: 'INVALID_ARGS' }); expect(fixture.markerReads()).toBe(0); expect(fixture.outputOpens()).toBe(0); + expect(fixture.hostCommands).toEqual([]); }); -test('rejects a missing HDC tool before opening output or starting a process', async () => { - const fixture = hostFixture({ whichHdc: async () => undefined }); - const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ - device, - intent: { kind: 'ordinary' }, - scope, - }); - - await expect( - binding.operations.appLogStart?.({ - sessionId: 'session', - appBundleId: 'com.example.harmony', - outputPath: '/tmp/app.log', - fence: { token: 'fence', generation: 1 }, - }), - ).rejects.toMatchObject({ - code: 'TOOL_MISSING', - message: 'hdc not found in PATH', - details: { - hint: 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.', - }, - }); - expect(fixture.outputOpens()).toBe(0); - expect(fixture.backgroundCommands).toEqual([]); -}); - -test('HarmonyOS logs name the HDC a configured toolchain root carries and skip the PATH lookup', async () => { - const root = createHarmonyToolchainRoot(); - const whichHdc = vi.fn(async () => 'hdc'); - const fixture = hostFixture({ whichHdc, env: { HDC_SDK_PATH: root, PATH: '/usr/bin' } }); - const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ - device, - intent: { kind: 'ordinary' }, - scope, - }); - - const started = await binding.operations.appLogStart?.({ - sessionId: 'session', - appBundleId: 'com.example.harmony', - outputPath: '/tmp/app.log', - fence: { token: 'fence', generation: 1 }, - }); - - // The plugin owns its documented roots, so it never asks the host to resolve HDC it already has. - expect(whichHdc).not.toHaveBeenCalled(); - expect(fixture.backgroundCommands).toEqual([ - [`${root}/hdc`, '-t', 'harmony-1', 'shell', 'hilog', '-P', '456'], - ]); - await started?.pendingHandle.transfer().finish(); -}); - -test('HarmonyOS log preflight answers an already-aborted request before any HDC lookup', async () => { +test('HarmonyOS log preflight answers an already-aborted request before any HDC command', async () => { const controller = new AbortController(); const reason = new Error('cancelled'); controller.abort(reason); - const whichHdc = vi.fn(async () => 'hdc'); - const fixture = hostFixture({ whichHdc }); + const fixture = hostFixture(); const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ device, intent: { kind: 'ordinary' }, @@ -161,19 +188,22 @@ test('HarmonyOS log preflight answers an already-aborted request before any HDC fence: { token: 'fence', generation: 1 }, }), ).rejects.toBe(reason); - expect(whichHdc).not.toHaveBeenCalled(); expect(fixture.outputOpens()).toBe(0); - expect(fixture.backgroundCommands).toEqual([]); + expect(fixture.hostCommands).toEqual([]); + expect(fixture.streams).toEqual([]); }); -test('HarmonyOS log preflight preserves cancellation when HDC lookup rejects differently', async () => { +test('HarmonyOS log commands carry the request signal so the host aborts them', async () => { + // The host owns the abort: the running `pidof` is asked with the request's own signal, and the + // stream is asked with a signal the request cancels while the start is still in flight, so a + // cancelled request cancels both rather than leaking a spawned `hilog`. const controller = new AbortController(); - const reason = new Error('cancelled'); - const transportError = new Error('tool lookup failed'); + let streamSignal: AbortSignal | undefined; + const held = deferred(); const fixture = hostFixture({ - whichHdc: async () => { - controller.abort(reason); - throw transportError; + holdStreamStart: async (signal) => { + streamSignal = signal; + await held.promise; }, }); const binding = await createHarmonyAppLogRuntime(fixture.host, fixture.toolbox).bind({ @@ -182,41 +212,66 @@ test('HarmonyOS log preflight preserves cancellation when HDC lookup rejects dif scope: { ...scope, signal: controller.signal }, }); - await expect( - binding.operations.appLogStart?.({ - sessionId: 'session', - appBundleId: 'com.example.harmony', - outputPath: '/tmp/app.log', - fence: { token: 'fence', generation: 1 }, - }), - ).rejects.toBe(reason); - expect(fixture.outputOpens()).toBe(0); - expect(fixture.backgroundCommands).toEqual([]); + const started = binding.operations.appLogStart?.(startInput); + await fixture.streamStarted(); + expect(fixture.hdcCommands()).toHaveLength(1); + expect(fixture.pidLookupSignal()).toBe(controller.signal); + expect(streamSignal?.aborted).toBe(false); + + controller.abort(new Error('cancelled')); + expect(streamSignal?.aborted).toBe(true); + held.resolve(); + await expect(started).rejects.toThrow('cancelled'); }); +function deferred(): Readonly<{ promise: Promise; resolve(): void }> { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + function hostFixture( - options: { - whichHdc?: AppLogRuntimeHost['commands']['which']; + options: Readonly<{ /** The environment the plugin's own setup host names, including its toolchain roots. */ env?: Readonly>; - } = {}, + /** Rejected one command, the way the host rejects a spawn it cannot start. */ + reject?: (executable: string, args: readonly string[]) => Error; + /** Held the managed stream start open. */ + holdStreamStart?: (signal: AbortSignal | undefined) => Promise; + }> = {}, ) { - const backgroundCommands: string[][] = []; + // Every command the plugin asked its setup host to run: the one-shot PID lookup and the streamed + // hilog, each with the environment the plugin built for it. The device answers its app lookup with + // one PID, which is what lets the stream begin. + let streamRequested: () => void = () => {}; + const streamRequestedOnce = new Promise((resolve) => { + streamRequested = resolve; + }); + const stub = createHarmonyHostStub({ + env: options.env, + reject: options.reject, + respond: (_executable, args) => (args.includes('pidof') ? { stdout: '456\n' } : {}), + ...(options.holdStreamStart === undefined + ? {} + : { + holdStreamStart: async (signal) => { + streamRequested(); + await options.holdStreamStart!(signal); + }, + }), + }); + let runtimeHostStartCount = 0; + const runtimeHostCommands: string[][] = []; let outputOpens = 0; let markerReads = 0; - let resolveWait: (() => void) | undefined; - const wait = new Promise<{ stdout: string; stderr: string; exitCode: number }>((resolve) => { - resolveWait = () => resolve({ stdout: '', stderr: '', exitCode: 0 }); - }); - const process: AppLogBackgroundProcess = { - wait, - terminate: async () => resolveWait?.(), - [Symbol.asyncDispose]: async () => {}, - }; - const startProcess: AppLogRuntimeHost['processes']['start'] = async ({ command }) => { - if (command.kind !== 'host') throw new Error('Expected a HarmonyOS host command'); - backgroundCommands.push([command.request.executable, ...command.request.args]); - return process; + const unusedStart: AppLogRuntimeHost['processes']['start'] = async ({ command }) => { + runtimeHostStartCount += 1; + if (command.kind === 'host') { + runtimeHostCommands.push([command.request.executable, ...command.request.args]); + } + throw new Error('The HarmonyOS app-log plan owns its process route'); }; const host: AppLogRuntimeHost = { appleTools: { @@ -230,8 +285,13 @@ function hostFixture( resolveSession: () => ({ outputPath: '/tmp/app.log', pidPath: '/tmp/app-log.pid' }), }, commands: { - which: options.whichHdc ?? (async () => 'hdc'), - run: async () => ({ stdout: '456\n', stderr: '', exitCode: 0 }), + which: async () => { + throw new Error('The HarmonyOS plugin resolves HDC on its own host'); + }, + run: async (request) => { + runtimeHostCommands.push([request.executable, ...request.args]); + return { stdout: '', stderr: '', exitCode: 0 }; + }, }, outputs: { readTail: async () => '', @@ -241,10 +301,12 @@ function hostFixture( }, }, processTransports: { - resolve: async () => ({ mode: 'local', start: startProcess }), + // The core's local transport: present, which is what makes `logs start` available, and never + // used to start this family's stream. + resolve: async () => ({ mode: 'local', start: unusedStart }), }, processes: { - start: startProcess, + start: unusedStart, readMarker: async () => { markerReads += 1; return { status: 'missing' }; @@ -255,17 +317,29 @@ function hostFixture( }, clock: { now: () => 10, sleep: waitForMonitorWake }, }; - // The plugin's toolbox is built from the host it was set up with, same as in composition. - const { toolbox } = createHarmonyHostStub({ env: options.env }); return { host, - toolbox, - backgroundCommands, + toolbox: stub.toolbox, + hostCommands: stub.commands, + streams: stub.streams, + /** The HDC argv of every one-shot command, with the family's own launcher dropped. */ + hdcCommands: () => stub.commands.map(({ args }) => [...args]), + /** The `PATH` entries the plugin handed each one-shot command, in order. */ + commandPaths: () => stub.commands.map((command) => harmonyCommandPath(command)), + pidLookupSignal: () => stub.commands[0]?.signal, + /** Settles once the plugin has asked the host to keep its stream running. */ + streamStarted: () => streamRequestedOnce, + runtimeHostStarts: () => runtimeHostStartCount, + runtimeHostCommands: () => runtimeHostCommands, markerReads: () => markerReads, outputOpens: () => outputOpens, }; } +/** + * The monitor polls while it waits, so its sleep stays pending until disposal stops it. Without an + * abort it would resolve on nothing and spin. + */ async function waitForMonitorWake(_milliseconds: number, signal?: AbortSignal): Promise { if (signal?.aborted) return; await new Promise((resolve) => { diff --git a/packages/platform-harmonyos/src/logs/runtime.ts b/packages/platform-harmonyos/src/logs/runtime.ts index 7ab507dc36..79d29cea20 100644 --- a/packages/platform-harmonyos/src/logs/runtime.ts +++ b/packages/platform-harmonyos/src/logs/runtime.ts @@ -1,9 +1,14 @@ import { deviceShellArgv } from '@agent-device/kernel/device-shell'; -import { AppError } from '@agent-device/kernel/errors'; -import type { AppLogRuntimeHost } from '@agent-device/contracts/app-log-runtime'; +import type { + AppLogBackgroundProcess, + AppLogBackgroundProcessRequest, + AppLogProcessCommand, + AppLogProcessStart, + AppLogRuntimeHost, +} from '@agent-device/contracts/app-log-runtime'; import { createPidScopedAppLogRuntimeOwner, - resolveFirstNumericAppLogPid, + firstNumericAppLogPid, } from '@agent-device/capture-kit'; import type { HarmonyToolbox } from '../toolbox.ts'; import { createHarmonyAppLogEnvelope, harmonyAppLogDescriptorCodec } from './descriptor.ts'; @@ -12,8 +17,11 @@ const START_UNAVAILABLE_HINT = 'The selected HarmonyOS transport cannot start a background hilog stream.'; /** - * HarmonyOS app logs. The `hdc` the two host-minted commands name is resolved by the plugin, because - * the core builds those commands' environment without this family's documented toolchain roots. + * HarmonyOS app logs. Both HDC commands this owner runs — the one-shot `pidof` poll and the streamed + * `hilog` — go through the command route the plugin built from the host its `setup` received, so the + * family's documented toolchain roots are prepared for the stream exactly as they are for discovery + * and interaction. The runtime host's own process transport spawns with the core's environment, + * which names none of this family's roots. */ export function createHarmonyAppLogRuntime(host: AppLogRuntimeHost, toolbox: HarmonyToolbox) { return createPidScopedAppLogRuntimeOwner(host, { @@ -30,35 +38,28 @@ export function createHarmonyAppLogRuntime(host: AppLogRuntimeHost, toolbox: Har ? [] : ['No app bundle is tracked in this session. Run open first for app-scoped logs.'], }), - process: async ({ host: runtimeHost, device, input, signal }) => { - const hdc = await resolveHarmonyLogsHdc(host, toolbox, signal); - return { - resolvePid: async (pidSignal) => - await resolveFirstNumericAppLogPid( - runtimeHost, - { - executable: hdc, - args: deviceShellArgv( - 'hdc', - 'shell', - ['pidof', input.appBundleId], - ['-t', device.id], - ), + process: async ({ device, input }) => ({ + resolvePid: async (signal) => + firstNumericAppLogPid( + ( + await toolbox.hdc.runShell(device, ['pidof', input.appBundleId], { allowFailure: true, timeoutMs: 5_000, - }, - pidSignal, - ), - command: (pid) => ({ - kind: 'host', - request: { - executable: hdc, - args: deviceShellArgv('hdc', 'shell', ['hilog', '-P', pid], ['-t', device.id]), - allowFailure: true, - }, - }), - }; - }, + ...(signal === undefined ? {} : { signal }), + }) + ).stdout, + ), + // Resolved per start, so a toolchain installed while the daemon runs is streamed with too. + command: async (pid) => ({ + kind: 'host', + request: { + executable: await toolbox.hdc.executable(), + args: deviceShellArgv('hdc', 'shell', ['hilog', '-P', pid], ['-t', device.id]), + allowFailure: true, + }, + }), + start: harmonyHilogProcessStart(toolbox), + }), descriptor: ({ artifacts }) => ({ transport: 'harmony-hilog', ...artifacts }) as const, envelope: ({ input, device, owner, descriptor }) => createHarmonyAppLogEnvelope({ @@ -72,43 +73,37 @@ export function createHarmonyAppLogRuntime(host: AppLogRuntimeHost, toolbox: Har } /** - * HDC for the host-minted hilog commands: the binary a documented toolchain root carries, else the - * host's own `PATH`. Both answers keep a cancellation a cancellation: an aborted request aborts the - * log stream rather than surfacing a probe failure. + * The stream's route: the setup host's managed process service, asked through the family's command + * runner so the spawn carries the `PATH` that runner prepares. The service owns the marker, the stop, + * and the cleanup, exactly as it does for a stream the core's own transport started. */ -async function resolveHarmonyLogsHdc( - host: AppLogRuntimeHost, +function harmonyHilogProcessStart(toolbox: HarmonyToolbox): AppLogProcessStart { + return async (request, signal) => + await startHarmonyHilog(toolbox, harmonyHostCommand(request.command), request, signal); +} + +async function startHarmonyHilog( toolbox: HarmonyToolbox, - signal: AbortSignal, -): Promise { - signal.throwIfAborted(); - const fromToolchain = await preserveHarmonyCancellation( - async () => await toolbox.commands.toolchainHdc(), - signal, - ); - if (fromToolchain) return fromToolchain; - signal.throwIfAborted(); - const fromPath = await preserveHarmonyCancellation( - async () => await host.commands.which('hdc'), - signal, - ); - signal.throwIfAborted(); - if (!fromPath) { - throw new AppError('TOOL_MISSING', 'hdc not found in PATH', { - hint: 'Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.', - }); - } - return fromPath; + command: AppLogHdcCommand, + request: AppLogBackgroundProcessRequest, + signal: AbortSignal | undefined, +): Promise { + return await toolbox.commands.start(command.executable, command.args, { + output: request.output, + ...(request.markerPath === undefined ? {} : { markerPath: request.markerPath }), + allowFailure: command.allowFailure ?? true, + ...(signal === undefined ? {} : { signal }), + }); } -async function preserveHarmonyCancellation( - operation: () => Promise, - signal: AbortSignal, -): Promise { - try { - return await operation(); - } catch (error) { - signal.throwIfAborted(); - throw error; - } +/** The HDC command an app-log plan mints: an executable plus the argv to run with it. */ +type AppLogHdcCommand = Extract['request']; + +/** + * The plan's command for this family. It mints host commands only, so an adb-scoped one here means + * the plan was built for another family. + */ +function harmonyHostCommand(command: AppLogProcessCommand): AppLogHdcCommand { + if (command.kind === 'host') return command.request; + throw new Error(`HarmonyOS app logs cannot stream a ${JSON.stringify(command.kind)} command`); } diff --git a/packages/platform-harmonyos/src/toolbox.fixtures.ts b/packages/platform-harmonyos/src/toolbox.fixtures.ts index 7ab580d03f..4407494332 100644 --- a/packages/platform-harmonyos/src/toolbox.fixtures.ts +++ b/packages/platform-harmonyos/src/toolbox.fixtures.ts @@ -17,11 +17,23 @@ export type HarmonyHostStubCommand = Readonly<{ signal: AbortSignal | undefined; }>; +/** One streamed command this stubbed host was asked to keep running. */ +export type HarmonyHostStubStream = Readonly<{ + executable: string; + args: readonly string[]; + env: HostEnvironment['env'] | undefined; + markerPath: string | undefined; + allowFailure: boolean | undefined; + signal: AbortSignal | undefined; +}>; + export type HarmonyHostStub = Readonly<{ toolbox: HarmonyToolbox; host: PlatformHost; /** Every command the plugin asked the host to run, in order. */ commands: HarmonyHostStubCommand[]; + /** Every streamed command the plugin asked the host to keep running, in order. */ + streams: HarmonyHostStubStream[]; /** Queues one answer for the next command; exit code 0 is the common case. */ answer(answer?: Partial & Readonly<{ stdout?: string }>): void; }>; @@ -47,10 +59,16 @@ export function createHarmonyHostStub( ) => Partial & Readonly<{ stdout?: string }>; /** Rejected one command, the way the host rejects a spawn it cannot start. */ reject?: (executable: string, args: readonly string[]) => Error; + /** + * Held the managed start open, the way a slow spawn does, so a test can cancel a request while + * its stream is still being started and see what the host was asked to abort. + */ + holdStreamStart?: (signal: AbortSignal | undefined) => Promise; }> = {}, ): HarmonyHostStub { const env = input.env ?? { PATH: '/usr/bin' }; const commands: HarmonyHostStubCommand[] = []; + const streams: HarmonyHostStubStream[] = []; const answers: HarmonyCommandResult[] = []; const host = Object.freeze({ env, @@ -93,11 +111,51 @@ export function createHarmonyHostStub( if (input.respond) return toResult(input.respond(executable, args)); return answers.shift() ?? NO_ANSWER; }, + // The managed process service, stubbed the same way the one-shot port is: the plugin names the + // command and the environment, and the recorded call is what a test asserts on. + startBackgroundCommand: async ( + request: { + command: { + executable: string; + args: readonly string[]; + env?: Readonly>; + allowFailure?: boolean; + }; + markerPath?: string; + }, + signal?: AbortSignal, + ) => { + streams.push({ + executable: request.command.executable, + args: request.command.args, + env: request.command.env, + markerPath: request.markerPath, + allowFailure: request.command.allowFailure, + signal, + }); + let resolveWait: (() => void) | undefined; + const wait = new Promise<{ + stdout: string; + stderr: string; + exitCode: number | null; + }>((resolve) => { + resolveWait = () => resolve({ stdout: '', stderr: '', exitCode: 0 }); + }); + const process = { + marker: { pid: 4_242, startTime: '100', command: request.command.executable }, + wait, + terminate: async () => resolveWait?.(), + [Symbol.asyncDispose]: async () => resolveWait?.(), + }; + if (input.holdStreamStart) await input.holdStreamStart(signal); + return process; + }, }) as unknown as PlatformHost; return Object.freeze({ toolbox: createHarmonyToolbox(host), host, commands, + streams, answer: (answer) => { answers.push(toResult(answer)); }, @@ -126,7 +184,9 @@ export function createHarmonyToolchainRoot(contents = '#!/bin/sh\necho stub\n'): } /** The `PATH` entries the plugin handed one command. */ -export function harmonyCommandPath(command: HarmonyHostStubCommand): readonly string[] { +export function harmonyCommandPath( + command: Readonly<{ env: HostEnvironment['env'] | undefined }>, +): readonly string[] { return (command.env?.PATH ?? '').split(path.delimiter).filter(Boolean); } diff --git a/packages/platform-harmonyos/test/package-smoke.mjs b/packages/platform-harmonyos/test/package-smoke.mjs index 0f2577b435..a0e06b225b 100644 --- a/packages/platform-harmonyos/test/package-smoke.mjs +++ b/packages/platform-harmonyos/test/package-smoke.mjs @@ -43,6 +43,13 @@ function hdcStubSource(logFile) { 'else if (joined.includes("bm dump -n"))', ' answer(JSON.stringify({ hapModuleInfos: [{ moduleName: "entry", mainElementName: "EntryAbility" }] }));', 'else if (joined.includes("aa start")) answer("start ability successfully.");', + // The app-log owner asks the device for the application's PID and then streams that PID's log. + // `hilog` never returns on a device, so the stub keeps its stream open the way the tool does. + 'else if (joined.includes("pidof")) answer("4242");', + 'else if (joined.includes("hilog")) {', + ' answer("01-01 00:00:00.000 4242 4242 I A00000: stub line");', + ' setInterval(() => {}, 1_000);', + '}', 'else if (joined.includes("dumpLayout")) answer("DumpLayout saved to:/data/local/tmp/layout.json");', 'else if (args[2] === "file" && args[3] === "recv") {', ' const destination = args[5];', @@ -206,6 +213,23 @@ test('packed core discovers harmonyos only after the managed platform is install assert.deepEqual([...fs.readFileSync(shot).subarray(0, 3)], [0xff, 0xd8, 0xff]); const pressed = runCliWith(toolchainEnv, 0, 'press', '100', '200', '--platform', 'harmonyos'); assert.equal(pressed.data.targetKind, 'point'); + // App logs, the third command family: `logs start` asks the device for the application PID and + // streams that PID's log through the host's managed process service. Both calls must reach the + // same toolchain-root HDC the rest of the family uses — the stream included, which is the part a + // plugin cannot spawn through the core's own local process transport. + const logs = runCliWith(toolchainEnv, 0, 'logs', 'start', '--platform', 'harmonyos'); + assert.equal(logs.data.started, true); + assert.ok(logs.data.path.endsWith('app.log'), `unexpected log path: ${logs.data.path}`); + // The stream is a background process, so its first line lands a moment after the reply. + let streamed = ''; + for (let attempt = 0; attempt < 100 && !streamed.includes('stub line'); attempt += 1) { + // Synchronous wait: this process must keep the daemon's parent alive without a timer. + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100); + streamed = fs.existsSync(logs.data.path) ? fs.readFileSync(logs.data.path, 'utf8') : ''; + } + assert.match(streamed, /stub line/); + const stopped = runCliWith(toolchainEnv, 0, 'logs', 'stop', '--platform', 'harmonyos'); + assert.equal(stopped.data.stopped, true); runCliWith(toolchainEnv, 0, 'close', '--platform', 'harmonyos'); const recorded = fs.readFileSync(hdcCalls, 'utf8').split('\n').filter(Boolean); @@ -230,6 +254,14 @@ test('packed core discovers harmonyos only after the managed platform is install invoked.some((line) => line.endsWith('shell uitest uiInput click 100 200')), `the press command never reached HDC through the documented root: ${invoked.join(' | ')}`, ); + assert.ok( + invoked.some((line) => /^ARGS: -t stub-target shell pidof com\.example\.app$/.test(line)), + `the log owner never asked the device for the application PID: ${invoked.join(' | ')}`, + ); + assert.ok( + invoked.some((line) => /^ARGS: -t stub-target shell hilog -P 4242$/.test(line)), + `the log stream never ran HDC through the documented root: ${invoked.join(' | ')}`, + ); assert.ok( invoked.every((line) => line === 'ARGS: list targets' || line.includes('-t stub-target')), 'every call after discovery names the discovered target', diff --git a/packages/plugins/src/contract.ts b/packages/plugins/src/contract.ts index c58a3b15b7..5562e66538 100644 --- a/packages/plugins/src/contract.ts +++ b/packages/plugins/src/contract.ts @@ -105,7 +105,14 @@ export type ProviderContribution> | PluginSetupResult; }>; -export type { PlatformContribution, PlatformHost, PlatformSetup } from './platform.ts'; +export type { + PlatformBackgroundCommand, + PlatformBackgroundProcess, + PlatformContribution, + PlatformHost, + PlatformOutputSink, + PlatformSetup, +} from './platform.ts'; /** One independently activated claim a plugin declares. New kinds need an explicit decision. */ export type Contribution = diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index 3b9025ddb6..95f56453a7 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -16,6 +16,36 @@ import type { DiagnosticEventInput, withDiagnosticTimer } from '@agent-device/ho import type { OwnedProcessRecordStore } from '@agent-device/host-kit/process'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; +/** + * One command the host keeps running after the call returns: a device log tail a plugin streams + * rather than a command it waits an answer from. `env` is the environment the caller prepared, so a + * family that resolves its toolchain from roots the core does not name spawns with the same `PATH` + * its one-shot commands use. The host owns the process table entry, the stop, and the marker. + */ +export type PlatformBackgroundCommand = Readonly<{ + executable: string; + args: readonly string[]; + env?: Readonly>; + allowFailure?: boolean; +}>; + +/** Where the host appends a background command's output. */ +export type PlatformOutputSink = AsyncDisposable & + Readonly<{ + write(chunk: string | Uint8Array): Promise; + }>; + +/** + * A background command the host started. `marker` is the published proof of ownership when the + * request named a `markerPath`; `terminate` stops the process the host started and settles `wait`. + */ +export type PlatformBackgroundProcess = AsyncDisposable & + Readonly<{ + marker?: Readonly<{ pid: number; startTime: string; command: string }>; + wait: Promise<{ stdout: string; stderr: string; exitCode: number | null; signal?: string }>; + terminate(): Promise; + }>; + /** Authority shared by web setup and daemon-owned web sessions. */ export type PlatformHost = HostEnvironment & Readonly<{ @@ -39,6 +69,21 @@ export type PlatformHost = HostEnvironment & * the probe uses the same host authority as the spawn it authorizes. */ isFileExecutable(path: string): Promise; + /** + * 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. + */ + startBackgroundCommand?( + request: Readonly<{ + command: PlatformBackgroundCommand; + output: PlatformOutputSink; + markerPath?: string; + }>, + signal?: AbortSignal, + ): Promise; emitDiagnostic(event: DiagnosticEventInput): void; withDiagnosticTimer: typeof withDiagnosticTimer; }>; diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index 488a3ff8e4..d44e00cda2 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -116,6 +116,7 @@ export async function composeDaemonRuntimeDeps( const platformHost = createPlatformPluginHost(host, baseDir, { ownedProcessRecords, openWebSessionNames, + sessionsDir, }); const providerComposition = providerCandidates === undefined diff --git a/src/platform-runtime/installed-platforms.ts b/src/platform-runtime/installed-platforms.ts index 454b8cfbc4..f95a8573d2 100644 --- a/src/platform-runtime/installed-platforms.ts +++ b/src/platform-runtime/installed-platforms.ts @@ -47,16 +47,16 @@ export async function startInstalledPlatforms( ); const resolved = await resolveProviderPlugins([...builtinPlatformCandidates(), ...candidates]); const assertSelectionCurrent = createPluginSelectionGuard(installed, host.env); + const daemonPaths = resolveDaemonPaths(stateDir, { env: host.env, cwd: host.cwd }); const registry = await startProviderRegistry( resolved, host, { ...PROVIDER_PLUGIN_POLICY, assertSelectionCurrent, - platformHost: createPlatformPluginHost( - host, - resolveDaemonPaths(stateDir, { env: host.env, cwd: host.cwd }).baseDir, - ), + platformHost: createPlatformPluginHost(host, daemonPaths.baseDir, { + sessionsDir: daemonPaths.sessionsDir, + }), }, 'platforms', ); diff --git a/src/platform-runtime/plugin-host.test.ts b/src/platform-runtime/plugin-host.test.ts index 7fb240f0f0..f7d9c13f65 100644 --- a/src/platform-runtime/plugin-host.test.ts +++ b/src/platform-runtime/plugin-host.test.ts @@ -21,3 +21,69 @@ test('the platform plugin host answers whether a path is an executable file', () expect(host.isFileExecutable(notAFile)).resolves.toBe(false), ]); }); + +// A plugin's streamed log is a durable resource, not a fire-and-forget spawn: the host publishes the +// ownership marker the core recovers after a restart, streams into the sink the caller opened, and +// clears the marker when the process ends. +test('the platform plugin host keeps a background command as a managed process', async () => { + const root = mkdtempForTestSync('plugin-host-background-'); + const sessionsDir = path.join(root, 'sessions', 's1'); + fs.mkdirSync(sessionsDir, { recursive: true }); + const script = path.join(root, 'stream.sh'); + // A stream that exits before its marker is written would prove nothing, so this one stays open + // until it is stopped, the way `hilog` does. + fs.writeFileSync(script, '#!/bin/sh\necho "$MARKER_WORD"\nwhile :; do sleep 0.1; done\n', { + mode: 0o755, + }); + const host = createPlatformPluginHost(createLiveTestHostEnvironment(), root); + const written: string[] = []; + const markerPath = path.join(sessionsDir, 'app-log.pid'); + + const process = await host.startBackgroundCommand!( + { + command: { + executable: script, + args: [], + env: { MARKER_WORD: 'hilog line' }, + allowFailure: true, + }, + output: { + write: async (chunk) => { + written.push(chunk.toString()); + }, + [Symbol.asyncDispose]: async () => {}, + }, + markerPath, + }, + new AbortController().signal, + ); + + expect(process.marker?.pid).toBeGreaterThan(0); + // The marker is the core's own record, so its recovery path reads it. + expect(JSON.parse(fs.readFileSync(markerPath, 'utf8'))).toMatchObject({ + pid: process.marker?.pid, + }); + + await process.terminate(); + expect((await process.wait).exitCode).not.toBe(0); + expect(written.join('')).toContain('hilog line'); + expect(fs.existsSync(markerPath)).toBe(false); +}); + +// The marker is confined to the daemon's sessions directory: a plugin cannot point the core's +// recovery scan at a file it does not own. +test('the platform plugin host refuses a background command marker outside its sessions directory', async () => { + const root = mkdtempForTestSync('plugin-host-marker-'); + const host = createPlatformPluginHost(createLiveTestHostEnvironment(), root); + + await expect( + host.startBackgroundCommand!( + { + command: { executable: '/bin/echo', args: ['x'] }, + output: { write: async () => {}, [Symbol.asyncDispose]: async () => {} }, + markerPath: path.join(root, 'app-log.pid'), + }, + new AbortController().signal, + ), + ).rejects.toThrow('sessions directory'); +}); diff --git a/src/platform-runtime/plugin-host.ts b/src/platform-runtime/plugin-host.ts index 95f18a139e..b8b1f8986c 100644 --- a/src/platform-runtime/plugin-host.ts +++ b/src/platform-runtime/plugin-host.ts @@ -1,16 +1,39 @@ import type { PlatformHost } from '@agent-device/plugins/contract'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +/** + * The host a platform plugin's `setup` receives. Alongside the one-shot command port and the + * executable probe, it answers a request to keep one of the plugin's commands running — a streamed + * device log — through the same managed app-log process service the core's own runtime host uses, so + * a plugin never spawns a process of its own and its stream gets the same ownership marker, stop, and + * cleanup. The command's own `env` is what the plugin prepared, so a family that resolves its tool + * chain from roots the core does not name streams with the same `PATH` it runs one-shot commands with. + * + * That process service belongs to the operation-host zone, which the daemon itself reaches only + * through a lazy seam. A plugin host is built when a process starts, so it loads the service with the + * first streamed command rather than statically, exactly as this file's command port does. + */ export function createPlatformPluginHost( host: HostEnvironment, stateDir: string, - resources?: Pick, + resources: Readonly<{ + openWebSessionNames?: () => readonly string[]; + ownedProcessRecords?: PlatformHost['ownedProcessRecords']; + /** The session root a managed process marker must stay inside; the state dir's by default. */ + sessionsDir?: string; + }> = {}, ): PlatformHost { + const { + sessionsDir = resolveDaemonPaths(stateDir, { env: host.env, cwd: host.cwd }).sessionsDir, + ...pluginResources + } = resources; + let processes: Awaited> | undefined; return Object.freeze({ ...host, stateDir, - ...resources, + ...pluginResources, emitDiagnostic, withDiagnosticTimer, runCommand: async (executable, args, options) => { @@ -21,5 +44,21 @@ export function createPlatformPluginHost( const { isExecutablePath } = await import('@agent-device/host-kit/command'); return await isExecutablePath(path); }, + startBackgroundCommand: async (request, signal) => { + processes ??= await loadManagedAppLogProcesses(sessionsDir, host.env); + return await processes.start( + { + command: { kind: 'host', request: request.command }, + output: request.output, + ...(request.markerPath === undefined ? {} : { markerPath: request.markerPath }), + }, + signal, + ); + }, } satisfies PlatformHost); } + +async function loadManagedAppLogProcesses(sessionsDir: string, env: HostEnvironment['env']) { + const { createManagedAppLogProcesses } = await import('../platform-runtime-app-log-process.ts'); + return createManagedAppLogProcesses(sessionsDir, env); +} diff --git a/src/sdk/plugins.ts b/src/sdk/plugins.ts index ee93baacd7..3493c0078b 100644 --- a/src/sdk/plugins.ts +++ b/src/sdk/plugins.ts @@ -15,8 +15,11 @@ export type { } from '@agent-device/plugins/host'; export type { Contribution, + PlatformBackgroundCommand, + PlatformBackgroundProcess, PlatformContribution, PlatformHost, + PlatformOutputSink, PlatformSetup, PluginConnection, PluginConnectionContext,