From ad08ad75a9668823c44b22dc41373660c32cf7b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Sat, 7 Nov 2026 00:28:22 +0800 Subject: [PATCH 01/17] feat(harmonyos): verify the launched app in the foreground after open dispatches `aa start` reports an accepted launch, not a visible app, so an open under a lock screen succeeded beside an invisible app and only a later snapshot told the truth. HarmonyOS now polls its foreground read for up to 5s after the dispatch. A launch that never surfaced carries a typed `timing.foregroundVerification` fact and the open warns `open-not-foreground` with the app that held the foreground; `open --foreground` fails with `details.reason: open-not-foreground` instead. Co-Authored-By: Claude Code --- .../src/application-lifecycle-runtime.ts | 23 ++ .../application-lifecycle-execution.ts | 1 + ...-execution-foreground-verification.test.ts | 165 +++++++++++++ .../internal/session-open-execution.ts | 19 ++ .../src/__tests__/app-lifecycle.test.ts | 230 ++++++++++++++++++ .../platform-harmonyos/src/app-lifecycle.ts | 100 ++++++++ packages/platform-harmonyos/src/index.ts | 3 + .../platform-harmonyos/src/runtime.test.ts | 135 ++++++++++ packages/platform-harmonyos/src/runtime.ts | 41 +++- website/docs/docs/commands.md | 3 +- 10 files changed, 715 insertions(+), 5 deletions(-) create mode 100644 packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index b1e01d7e76..fcf38c6004 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -49,6 +49,11 @@ export type ApplicationLifecycleExecution = Readonly<{ launchConsole?: string; launchArgs?: readonly string[]; clearAppState?: boolean; + /** + * `open --foreground` with an app target. A launch-verified owner treats "the launched app never + * held the foreground" as this open's failure instead of a success beside a warning. + */ + foreground?: boolean; iosXctestrunFile?: string; iosXctestDerivedDataPath?: string; iosXctestEnvDir?: string; @@ -144,6 +149,24 @@ export type OpenApplicationTiming = Readonly<{ postOpenObservation?: PostOpenObservation; /** Why the observation could not run; present exactly when it is `probe-failed`. */ postOpenObservationFailure?: PostOpenObservationFailure; + /** + * Present when the owner verified after its dispatch which app holds the foreground, and the + * launched app never did. An unconfirmed read under `open --foreground` fails the open instead. + */ + foregroundVerification?: OpenForegroundVerification; +}>; + +/** + * What an owner learned when it verified after its dispatch which app holds the foreground. A + * launch dispatch can report success while a system surface (a lock screen is the typical one) + * keeps the launched app behind it, so the verification is a bounded poll of the platform's own + * foreground read. + */ +export type OpenForegroundVerification = Readonly<{ + /** True when the launched app held the foreground within the owner's poll budget. */ + confirmed: boolean; + /** The app that held the foreground instead, when the platform could name one. */ + foregroundPackage?: string; }>; /** diff --git a/packages/daemon/src/sessions/application-lifecycle-execution.ts b/packages/daemon/src/sessions/application-lifecycle-execution.ts index 2e7d18699a..2e6d72b362 100644 --- a/packages/daemon/src/sessions/application-lifecycle-execution.ts +++ b/packages/daemon/src/sessions/application-lifecycle-execution.ts @@ -23,6 +23,7 @@ export function applicationLifecycleExecutionFromRequest( launchConsole: req.flags?.launchConsole, launchArgs: req.flags?.launchArgs, clearAppState: req.flags?.clearAppState, + foreground: req.flags?.foreground === true, iosXctestrunFile: req.flags?.iosXctestrunFile, iosXctestDerivedDataPath: req.flags?.iosXctestDerivedDataPath, iosXctestEnvDir: req.flags?.iosXctestEnvDir, diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts new file mode 100644 index 0000000000..89f340c7fd --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts @@ -0,0 +1,165 @@ +import path from 'node:path'; +import { expect, test } from 'vitest'; +import type { DaemonResponse, DaemonResponseData } from '@agent-device/kernel/contracts'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { + OpenApplicationInput, + OpenApplicationOutcome, +} from '@agent-device/contracts/application-lifecycle-runtime'; +import { + bindTestCommandHost, + createTestHostEnvironment, + mkdtempForTestSync, +} from '@agent-device/test-kit'; +import { SessionStore } from '../../../core/session-store.ts'; +import type { DaemonRequest } from '../../../core/daemon-request.ts'; +import type { SessionState } from '../../../core/session-state.ts'; +import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts'; +import { fakeCreateCommandSurface } from '../../../__tests__/support/command-surface-fake.ts'; +import { + handleSessionCommands, + mockBindDeviceRuntime, +} from '../../../__tests__/support/handlers/session-command-harness.ts'; + +bindTestCommandHost(); + +const HARMONY_DEVICE: DeviceInfo = { + platform: 'harmonyos', + id: 'harmony-1', + name: 'HarmonyOS test device', + kind: 'device', + target: 'mobile', + booted: true, +}; + +function makeSessionStore(): SessionStore { + const root = mkdtempForTestSync('agent-device-open-foreground-'); + return new SessionStore(path.join(root, 'sessions'), createTestHostEnvironment()); +} + +function publishSession( + sessionStore: SessionStore, + name: string, + device: DeviceInfo, + overrides: Partial = {}, +): SessionState { + const session: SessionState = { + name, + device, + createdAt: Date.now(), + actions: [], + appName: 'com.example.application', + ...overrides, + }; + sessionStore.publish(name, session); + return session; +} + +async function openApp(params: { + sessionStore: SessionStore; + sessionName: string; + openOutcome: OpenApplicationOutcome; + onOpenApplication?: (input: OpenApplicationInput) => Promise | void; +}): Promise { + const bindDevice: Parameters[0]['bindDevice'] = async ( + device, + use, + ) => { + const binding = await mockBindDeviceRuntime(device, use); + return { + ...binding, + operations: { + ...binding.operations, + openApplication: async (input: OpenApplicationInput) => { + await params.onOpenApplication?.(input); + return params.openOutcome; + }, + }, + }; + }; + return await handleSessionCommands({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + req: { + token: 't', + session: params.sessionName, + command: 'open', + positionals: ['com.example.application'], + flags: {}, + } as DaemonRequest, + sessionName: params.sessionName, + logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), + sessionStore: params.sessionStore, + invoke: async (_req: DaemonRequest): Promise => ({ ok: true, data: {} }), + bindDevice, + }); +} + +function requireOpenData(response: DaemonResponse | null): DaemonResponseData { + if (!response?.ok) throw new Error('the open command failed'); + return response.data ?? {}; +} + +test('open warns and carries the typed read when the launched app never held the foreground', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + const data = requireOpenData( + await openApp({ + sessionStore, + sessionName: 'harmony-session', + openOutcome: { + appBundleId: 'com.example.application', + timing: { + foregroundVerification: { confirmed: false, foregroundPackage: 'com.ohos.launcher' }, + }, + }, + }), + ); + + const warnings = (data.warnings as string[] | undefined) ?? []; + expect(warnings.some((warning) => warning.includes('open-not-foreground'))).toBe(true); + expect(warnings.some((warning) => warning.includes('"com.ohos.launcher"'))).toBe(true); + expect(warnings.some((warning) => warning.toLowerCase().includes('unlock'))).toBe(true); + const timing = data.timing as Record | undefined; + expect(timing?.foregroundVerification).toEqual({ + confirmed: false, + foregroundPackage: 'com.ohos.launcher', + }); +}); + +test('open names the unreadable foreground instead of a holder package when no mission is foreground', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + const data = requireOpenData( + await openApp({ + sessionStore, + sessionName: 'harmony-session', + openOutcome: { + appBundleId: 'com.example.application', + timing: { foregroundVerification: { confirmed: false } }, + }, + }), + ); + + const warnings = (data.warnings as string[] | undefined) ?? []; + expect(warnings.some((warning) => warning.includes('no foreground app is readable'))).toBe(true); +}); + +test('open adds no foreground warning when the lifecycle outcome carries no unconfirmed read', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + const data = requireOpenData( + await openApp({ + sessionStore, + sessionName: 'harmony-session', + openOutcome: { appBundleId: 'com.example.application', timing: {} }, + }), + ); + + const warnings = (data.warnings as string[] | undefined) ?? []; + expect(warnings.some((warning) => warning.includes('open-not-foreground'))).toBe(false); +}); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index f9dccee84b..00eb92e581 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -20,6 +20,7 @@ import type { LaunchConfirmationUnansweredReason, OpenApplicationOutcome, OpenApplicationTiming, + OpenForegroundVerification, } from '@agent-device/contracts/application-lifecycle-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { DaemonPlatformServices } from '../../../core/platform-services.ts'; @@ -176,6 +177,18 @@ function launchConfirmationUnansweredWarning(reason: LaunchConfirmationUnanswere ); } +/** What the caller's `open` output says when the launched app never held the foreground. */ +function openNotForegroundWarning(verification: OpenForegroundVerification): string { + const holder = verification.foregroundPackage + ? `the foreground app is "${verification.foregroundPackage}"` + : 'no foreground app is readable'; + return ( + `The launch dispatch succeeded, but HarmonyOS read ${holder} within 5s of the launch ` + + '(open-not-foreground). A lock screen over the device is a typical cause. Unlock the device, ' + + 'then run the open again.' + ); +} + // Default-on for emulators, opt-in via --test-ime on real devices; --no-test-ime forces off. function shouldActivateAndroidTestIme(device: DeviceInfo, req: DaemonRequest): boolean { if (device.platform !== 'android') return false; @@ -387,6 +400,12 @@ export async function completeOpenCommand(params: { if (outcome.launchConfirmation === undefined && outcome.launchConfirmationProbeFailure) { appendResponseWarning(openResult, launchConfirmationProbeFailureWarning()); } + if (outcome.timing.foregroundVerification?.confirmed === false) { + appendResponseWarning( + openResult, + openNotForegroundWarning(outcome.timing.foregroundVerification), + ); + } const nextRef = publishOpenSession({ req, sessionStore, diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index d6b67c2064..4ccfd3cf7c 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -17,13 +17,17 @@ vi.mock('../snapshot.ts', async (importOriginal) => ({ })); import { + HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS, closeHarmonyApp, listHarmonyApps, parseHarmonyIsSystemApp, openHarmonyApp, parseHarmonyBundleList, parseHarmonyLaunchTarget, + pollHarmonyOpenForeground, + verifyHarmonyOpenForeground, } from '../app-lifecycle.ts'; +import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import { runCmd } from '@agent-device/host-kit/command'; const mockRunCmd = vi.mocked(runCmd); @@ -309,3 +313,229 @@ test('HarmonyOS launch resolves module metadata and reports missing launch data' mockRunCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'not installed', stderr: '' }); await assert.rejects(() => openHarmonyApp(DEVICE, 'com.example.missing'), /launchable ability/); }); + +function missionDump(packageName: string, state: string): string { + return [ + 'User ID #100', + 'Mission ID #28', + `\tstate #${state}`, + `\tmission name #[#${packageName}:entry:EntryAbility]`, + '', + ].join('\n'); +} + +test('pollHarmonyOpenForeground confirms the launched bundle on the first foreground read', async () => { + mockRunCmd.mockResolvedValueOnce({ + exitCode: 0, + stdout: missionDump('com.example.application', 'FOREGROUND'), + stderr: '', + }); + + const read = await pollHarmonyOpenForeground(DEVICE, 'com.example.application'); + + assert.deepEqual(read, { confirmed: true }); + assert.deepEqual(mockRunCmd.mock.calls[0]?.[1], ['-t', 'harmony-1', 'shell', 'aa', 'dump', '-l']); +}); + +test('pollHarmonyOpenForeground keeps polling until the launched bundle holds the foreground', async () => { + mockRunCmd + .mockResolvedValueOnce({ + exitCode: 0, + stdout: missionDump('com.ohos.launcher', 'FOREGROUND'), + stderr: '', + }) + .mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' }) + .mockResolvedValueOnce({ + exitCode: 0, + stdout: missionDump('com.example.application', 'FOREGROUND'), + stderr: '', + }); + + const read = await pollHarmonyOpenForeground(DEVICE, 'com.example.application', { + pollIntervalMs: 1, + }); + + assert.deepEqual(read, { confirmed: true }); + assert.equal(mockRunCmd.mock.calls.length, 3); +}); + +test('pollHarmonyOpenForeground names the app that kept the foreground when the launch never surfaces', async () => { + mockRunCmd.mockResolvedValue({ + exitCode: 0, + stdout: missionDump('com.ohos.launcher', 'FOREGROUND'), + stderr: '', + }); + + const read = await pollHarmonyOpenForeground(DEVICE, 'com.example.application', { + pollBudgetMs: 60, + pollIntervalMs: 10, + }); + + assert.deepEqual(read, { confirmed: false, foregroundPackage: 'com.ohos.launcher' }); +}); + +test('pollHarmonyOpenForeground reports an unreadable foreground when no mission is foreground', async () => { + mockRunCmd.mockResolvedValue({ + exitCode: 0, + stdout: missionDump('com.example.application', 'BACKGROUND'), + stderr: '', + }); + + const read = await pollHarmonyOpenForeground(DEVICE, 'com.example.application', { + pollBudgetMs: 40, + pollIntervalMs: 10, + }); + + assert.deepEqual(read, { confirmed: false }); +}); + +test('pollHarmonyOpenForeground treats a failed read as unconfirmed and keeps polling', async () => { + mockRunCmd.mockRejectedValueOnce(new Error('hdc died mid-read')).mockResolvedValueOnce({ + exitCode: 0, + stdout: missionDump('com.example.application', 'FOREGROUND'), + stderr: '', + }); + + const read = await pollHarmonyOpenForeground(DEVICE, 'com.example.application', { + pollIntervalMs: 1, + }); + + assert.deepEqual(read, { confirmed: true }); +}); + +test('pollHarmonyOpenForeground rejects when the request signal aborts mid-poll', async () => { + const controller = new AbortController(); + const abortReason = new Error('request cancelled during the open foreground poll'); + mockRunCmd.mockImplementation(async (_command, _args, options) => { + return await new Promise((_resolve, reject) => { + options?.signal?.addEventListener('abort', () => reject(abortReason), { once: true }); + }); + }); + + const pending = pollHarmonyOpenForeground(DEVICE, 'com.example.application', { + signal: controller.signal, + }); + controller.abort(abortReason); + + await assert.rejects(pending, (error: unknown) => error === abortReason); +}); + +function openInput(overrides: Partial = {}): OpenApplicationInput { + return { + positionals: ['com.example.application'], + appBundleId: 'com.example.application', + surface: 'app', + hasExistingSession: false, + relaunch: false, + prewarmRunnerBeforeOpen: false, + enableTestIme: false, + stateDir: '/tmp/agent-device-open-foreground', + runtimeHints: {}, + execution: {}, + ...overrides, + }; +} + +test('verifyHarmonyOpenForeground passes a confirmed foreground outcome through unchanged', async () => { + mockRunCmd.mockResolvedValueOnce({ + exitCode: 0, + stdout: missionDump('com.example.application', 'FOREGROUND'), + stderr: '', + }); + const outcome = { timing: {} }; + + const verified = await verifyHarmonyOpenForeground( + openInput(), + outcome, + DEVICE, + new AbortController().signal, + ); + + assert.equal(verified, outcome); +}); + +test('verifyHarmonyOpenForeground attaches the foreground read when the launch never surfaces', async () => { + vi.useFakeTimers(); + mockRunCmd.mockResolvedValue({ + exitCode: 0, + stdout: missionDump('com.ohos.launcher', 'FOREGROUND'), + stderr: '', + }); + const pending = verifyHarmonyOpenForeground( + openInput(), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); + + const verified = await pending; + assert.deepEqual(verified.timing.foregroundVerification, { + confirmed: false, + foregroundPackage: 'com.ohos.launcher', + }); +}); + +test('verifyHarmonyOpenForeground reports an unreadable foreground when no mission is foreground', async () => { + vi.useFakeTimers(); + mockRunCmd.mockResolvedValue({ + exitCode: 0, + stdout: missionDump('com.example.application', 'BACKGROUND'), + stderr: '', + }); + const pending = verifyHarmonyOpenForeground( + openInput(), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); + + const verified = await pending; + assert.deepEqual(verified.timing.foregroundVerification, { confirmed: false }); +}); + +test('verifyHarmonyOpenForeground fails the open when --foreground demands the foreground and the launch never surfaces', async () => { + vi.useFakeTimers(); + mockRunCmd.mockResolvedValue({ + exitCode: 0, + stdout: missionDump('com.ohos.launcher', 'FOREGROUND'), + stderr: '', + }); + const pending = verifyHarmonyOpenForeground( + openInput({ execution: { foreground: true } }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); + + await assert.rejects( + () => pending, + (error: unknown) => { + assert(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(error.details?.reason, 'open-not-foreground'); + assert.equal(error.details?.foregroundPackage, 'com.ohos.launcher'); + assert.match(error.details?.hint ?? '', /unlock the device screen/i); + return true; + }, + ); +}); + +test('verifyHarmonyOpenForeground skips verification without a bundle identity to verify', async () => { + await verifyHarmonyOpenForeground( + openInput({ appBundleId: undefined }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + await verifyHarmonyOpenForeground( + openInput({ appBundleId: 'https://example.com' }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + + assert.equal(mockRunCmd.mock.calls.length, 0); +}); diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index a5d68f6c3d..a016e498e3 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -1,7 +1,15 @@ +import { setTimeout as sleep } from 'node:timers/promises'; 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 type { + OpenApplicationInput, + OpenApplicationOutcome, +} from '@agent-device/contracts/application-lifecycle-runtime'; +import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime'; +import { isDeepLinkTarget } from '@agent-device/contracts/command'; import { runHarmonyShell } from './hdc.ts'; +import { parseHarmonyForegroundApp } from './app-state.ts'; import { invalidateHarmonyGestureViewport } from './snapshot.ts'; export function parseHarmonyBundleList(rawOutput: string): string[] { @@ -222,6 +230,98 @@ export async function openHarmonyApp( invalidateHarmonyGestureViewport(device); } +/** How long an open may keep re-reading the foreground before it accepts what it last saw. */ +export const HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS = 5_000; +/** One foreground read per interval until the budget runs out; the first read costs no wait. */ +const HARMONY_OPEN_FOREGROUND_POLL_INTERVAL_MS = 500; + +/** What one bounded foreground poll decided about a launched bundle. */ +export type HarmonyOpenForegroundRead = Readonly<{ + confirmed: boolean; + foregroundPackage?: string; +}>; + +/** + * Reads which HarmonyOS mission holds the foreground until the launched bundle does, the poll + * budget runs out, or the request is aborted. A read that names no FOREGROUND mission (the + * lock-screen shape) or fails to run counts as unconfirmed and keeps polling. + */ +export async function pollHarmonyOpenForeground( + device: DeviceInfo, + bundleId: string, + options: Readonly<{ + signal?: AbortSignal; + pollBudgetMs?: number; + pollIntervalMs?: number; + }> = {}, +): Promise { + const pollBudgetMs = options.pollBudgetMs ?? HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS; + const pollIntervalMs = options.pollIntervalMs ?? HARMONY_OPEN_FOREGROUND_POLL_INTERVAL_MS; + const deadlineAtMs = Date.now() + pollBudgetMs; + let foregroundPackage: string | undefined; + while (true) { + options.signal?.throwIfAborted(); + const foregroundPackageRead = (await readHarmonyForegroundMission(device, options.signal)) + ?.package; + if (foregroundPackageRead === bundleId) return { confirmed: true }; + if (foregroundPackageRead !== undefined) foregroundPackage = foregroundPackageRead; + if (Date.now() >= deadlineAtMs) { + return foregroundPackage === undefined + ? { confirmed: false } + : { confirmed: false, foregroundPackage }; + } + await sleep(pollIntervalMs, undefined, { signal: options.signal }); + } +} + +/** One foreground read; a failed or unreadable read answers undefined instead of throwing. */ +async function readHarmonyForegroundMission( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + try { + const result = await runHarmonyShell(device, ['aa', 'dump', '-l'], { + signal, + timeoutMs: 5_000, + }); + return parseHarmonyForegroundApp(result.stdout); + } catch (error) { + if (signal?.aborted) throw error; + return undefined; + } +} + +/** + * The HarmonyOS open post-check: a successful `aa start` dispatch says the launch was accepted, + * not that the app is visible. When the launched bundle never holds the foreground, `open + * --foreground` fails this open and a plain open carries the read beside its warning. + */ +export async function verifyHarmonyOpenForeground( + input: OpenApplicationInput, + outcome: OpenApplicationOutcome, + device: DeviceInfo, + signal: AbortSignal, +): Promise { + const bundleId = outcome.appBundleId ?? input.appBundleId; + if (bundleId === undefined || isDeepLinkTarget(bundleId)) return outcome; + const read = await pollHarmonyOpenForeground(device, bundleId, { signal }); + if (read.confirmed) return outcome; + if (input.execution.foreground === true) { + throw new AppError( + 'COMMAND_FAILED', + `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground within 5s`, + { + reason: 'open-not-foreground', + hint: 'Unlock the device screen, then run the open again.', + ...(read.foregroundPackage === undefined + ? {} + : { foregroundPackage: read.foregroundPackage }), + }, + ); + } + return { ...outcome, timing: { ...outcome.timing, foregroundVerification: read } }; +} + export async function closeHarmonyApp(device: DeviceInfo, bundleId: string): Promise { await runHarmonyShell(device, ['aa', 'force-stop', bundleId]); invalidateHarmonyGestureViewport(device); diff --git a/packages/platform-harmonyos/src/index.ts b/packages/platform-harmonyos/src/index.ts index 588d7659c9..787ad2d603 100644 --- a/packages/platform-harmonyos/src/index.ts +++ b/packages/platform-harmonyos/src/index.ts @@ -38,6 +38,9 @@ export const openHarmonyApp = deferred<(typeof import('./app-lifecycle.ts'))['op export const closeHarmonyApp = deferred<(typeof import('./app-lifecycle.ts'))['closeHarmonyApp']>( async () => (await import('./app-lifecycle.ts')).closeHarmonyApp, ); +export const verifyHarmonyOpenForeground = deferred< + (typeof import('./app-lifecycle.ts'))['verifyHarmonyOpenForeground'] +>(async () => (await import('./app-lifecycle.ts')).verifyHarmonyOpenForeground); export const runHarmonyHdc = deferred<(typeof import('./hdc.ts'))['runHarmonyHdc']>( async () => (await import('./hdc.ts')).runHarmonyHdc, diff --git a/packages/platform-harmonyos/src/runtime.test.ts b/packages/platform-harmonyos/src/runtime.test.ts index 8fae95be52..d565c10ecb 100644 --- a/packages/platform-harmonyos/src/runtime.test.ts +++ b/packages/platform-harmonyos/src/runtime.test.ts @@ -4,6 +4,7 @@ import { expect, test, vi } from 'vitest'; vi.mock('./hdc.ts', () => ({ runHarmonyShell: vi.fn() })); import { runHarmonyShell } from './hdc.ts'; +import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import type { DeviceBinding } from '@agent-device/contracts/platform-runtime'; import type { PlatformRuntimeHost, @@ -362,3 +363,137 @@ function gestureHost(): PlatformRuntimeHost { localInteractors: { resolve: async () => ({}) }, } as unknown as PlatformRuntimeHost; } + +function launchDumpHdc(): void { + const hdc = vi.mocked(runHarmonyShell); + hdc.mockReset(); + hdc.mockImplementation(async (_device, args) => { + if (args.includes('dump') && args.includes('-n')) { + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + hapModuleInfos: [{ mainElementName: 'MainAbility', moduleName: 'entry' }], + }), + }; + } + if (args.includes('start')) { + return { exitCode: 0, stderr: '', stdout: 'start ability successfully' }; + } + return { exitCode: 0, stderr: '', stdout: '' }; + }); +} + +function openInputFixture(overrides: Partial = {}): OpenApplicationInput { + return { + positionals: ['com.example.harmony'], + appBundleId: 'com.example.harmony', + surface: 'app', + hasExistingSession: false, + relaunch: false, + prewarmRunnerBeforeOpen: false, + enableTestIme: false, + stateDir: '/tmp/agent-device-runtime-foreground', + runtimeHints: {}, + execution: {}, + ...overrides, + }; +} + +test('openApplication verifies the launched bundle in the foreground after the direct dispatch', async () => { + launchDumpHdc(); + const hdc = vi.mocked(runHarmonyShell); + hdc.mockImplementation(async (_device, args) => { + if (args.includes('dump') && args.includes('-n')) { + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + hapModuleInfos: [{ mainElementName: 'MainAbility', moduleName: 'entry' }], + }), + }; + } + if (args.includes('start')) { + return { exitCode: 0, stderr: '', stdout: 'start ability successfully' }; + } + return { + exitCode: 0, + stderr: '', + stdout: + 'Mission ID #76\n\tstate #FOREGROUND\n\tmission name #[#com.example.harmony:entry:MainAbility]', + }; + }); + const interactor = { open: vi.fn(async () => undefined) }; + const binding = await createHarmonyPlatformRuntime({ + processTransports: { resolve: async () => ({ mode: 'local' as const }) }, + localInteractors: { resolve: async () => interactor }, + } as unknown as PlatformRuntimeHost).bind({ + device, + intent: { kind: 'ordinary' }, + scope: { + signal: new AbortController().signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, + }, + }); + + const openApplication = binding.operations.openApplication; + if (!openApplication) throw new Error('openApplication was not admitted for this binding'); + const outcome = await openApplication(openInputFixture()); + + expect(interactor.open).toHaveBeenCalledOnce(); + // A confirmed foreground reads as an ordinary open: no verification fact rides the outcome. + const foregroundReads = hdc.mock.calls.filter( + ([, args]) => args.includes('dump') && args.includes('-l'), + ); + expect(foregroundReads.length).toBeGreaterThanOrEqual(1); + expect(outcome.timing.foregroundVerification).toBeUndefined(); +}); + +test('openApplication fails when --foreground demands the foreground and the launch never surfaces', async () => { + vi.useFakeTimers(); + launchDumpHdc(); + const hdc = vi.mocked(runHarmonyShell); + hdc.mockImplementation(async (_device, args) => { + if (args.includes('dump') && args.includes('-n')) { + return { + exitCode: 0, + stderr: '', + stdout: JSON.stringify({ + hapModuleInfos: [{ mainElementName: 'MainAbility', moduleName: 'entry' }], + }), + }; + } + if (args.includes('start')) { + return { exitCode: 0, stderr: '', stdout: 'start ability successfully' }; + } + return { + exitCode: 0, + stderr: '', + stdout: + 'Mission ID #76\n\tstate #FOREGROUND\n\tmission name #[#com.ohos.launcher:entry:EntryAbility]', + }; + }); + const interactor = { open: vi.fn(async () => undefined) }; + const binding = await createHarmonyPlatformRuntime({ + processTransports: { resolve: async () => ({ mode: 'local' as const }) }, + localInteractors: { resolve: async () => interactor }, + } as unknown as PlatformRuntimeHost).bind({ + device, + intent: { kind: 'ordinary' }, + scope: { + signal: new AbortController().signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, + }, + }); + const openApplication = binding.operations.openApplication; + if (!openApplication) throw new Error('openApplication was not admitted for this binding'); + const pending = openApplication(openInputFixture({ execution: { foreground: true } })); + await vi.advanceTimersByTimeAsync(6_000); + + await expect(pending).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'open-not-foreground' }, + }); +}); diff --git a/packages/platform-harmonyos/src/runtime.ts b/packages/platform-harmonyos/src/runtime.ts index 4b87a01737..fbbd164dc6 100644 --- a/packages/platform-harmonyos/src/runtime.ts +++ b/packages/platform-harmonyos/src/runtime.ts @@ -7,6 +7,7 @@ import type { import { applicationLifecycleOperationFacts, availableApplicationLifecycleOperations, + type ApplicationLifecycleRuntimeOperations, } from '@agent-device/contracts/application-lifecycle-runtime'; import { backRuntimeOperationFacts } from '@agent-device/contracts/back-runtime'; import { elementTextRuntimeOperationFacts } from '@agent-device/contracts/element-text-runtime'; @@ -50,7 +51,11 @@ import { harmonyScreenRecordingFacts, } from './recording/runtime.ts'; import { readHarmonyAppState } from './app-state.ts'; -import { bindLocalDirectApplicationLifecycle } from '@agent-device/contracts/application-lifecycle-interaction'; +import { verifyHarmonyOpenForeground } from './app-lifecycle.ts'; +import { + bindLocalDirectApplicationLifecycle, + type LocalApplicationLifecycleInteractorResolver, +} from '@agent-device/contracts/application-lifecycle-interaction'; import { createHarmonyAppDeploymentOperations, harmonyAppDeploymentFacts, @@ -123,6 +128,36 @@ function harmonyLifecycleFacts(device: DeviceInfo) { }); } +/** + * The HarmonyOS lifecycle binding: the shared direct dispatch, plus a foreground verification + * after each open. `aa start` reports an accepted launch, not a visible app, so the verification + * turns a launch that a lock screen kept invisible into a typed fact on the outcome, and into a + * hard failure under `open --foreground`. + */ +function harmonyOpenVerifiedLifecycle(params: { + host: { resolve: LocalApplicationLifecycleInteractorResolver }; + device: DeviceInfo; + signal: AbortSignal; +}): ApplicationLifecycleRuntimeOperations { + const direct = bindLocalDirectApplicationLifecycle({ + owner: 'HarmonyOS', + openTargetIdentity: 'bundle-id', + host: params.host, + device: params.device, + signal: params.signal, + }); + return { + ...direct, + openApplication: async (input) => + await verifyHarmonyOpenForeground( + input, + await direct.openApplication(input), + params.device, + params.signal, + ), + }; +} + function harmonyOpenTargetFact(device: DeviceInfo) { return device.kind === 'emulator' || device.kind === 'device' ? lifecycleAvailable @@ -363,9 +398,7 @@ export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): Platfor ).map((app) => ({ id: app.package, name: app.name })); }, ...availableApplicationLifecycleOperations( - bindLocalDirectApplicationLifecycle({ - owner: 'HarmonyOS', - openTargetIdentity: 'bundle-id', + harmonyOpenVerifiedLifecycle({ host: host.localInteractors, device: request.device, signal: request.scope.signal, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index b976c831e5..2a4028764a 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -197,7 +197,7 @@ Aliases: `launch`, `relaunch`. | `--no-post-gesture-stabilization` | Scroll, swipe, gesture swipe, open: skip the movement check and the stabilization wait that follow a gesture, and on a local iOS simulator the first-screen wait after an app launch; use it only when your own polling verifies the screen | | `--save-script [path]` | Arm evidence capture on open, publish the armed recording on close; close --save-script alone (without an armed open) is rejected — start with open --save-script, or use session save-script mid-session. Optional custom output path. On Windows, absolute paths need a drive letter or ordinary UNC share. | | `--relaunch` | open: terminate app process before launching it | -| `--foreground` | open: keep normal app/device selection and return an initial snapshot of the first screen (a local iOS simulator waits up to 10s for it); without an app, resolve the sole running app on the sole booted iOS simulator | +| `--foreground` | open: keep normal app/device selection and return an initial snapshot of the first screen (a local iOS simulator waits up to 10s for it); without an app, resolve the sole running app on the sole booted iOS simulator; on HarmonyOS with an app target, fail when the launched app does not hold the foreground within 5s | | `--no-record` | Do not record this action | | `--wait ` | Open: wait up to n ms for a device another session is holding before failing with DEVICE_IN_USE | @@ -238,6 +238,7 @@ Exact behavior: `agent-device help close`. - Android React Native: `open --relaunch` needs an installed package name, not an APK path. For Metro-served JS changes, run `metro reload` instead. - ADB-backed Android: `open settings --relaunch` restarts the app that the intent opened. It fails when the intent matches more than one activity. - ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. +- On HarmonyOS, `open` reads the foreground app after the launch dispatch, for up to 5 seconds. When the opened app never holds the foreground, the open succeeds and `warnings` name it `open-not-foreground` with the app that holds the foreground, or the fact that no mission is foreground. A lock screen is a typical cause: unlock the device, then run the open again. When no read of the mission list succeeds in that budget, the warning names `open-foreground-probe-unreadable` instead and claims nothing about the app: check the device connection. With `--foreground`, an unconfirmed open fails with `details.reason: open-not-foreground` or `open-foreground-probe-unreadable`, matching the same two cases. - If `close` cannot confirm its cleanup, it keeps the session and its device claim. Run `close` again with the same options to release the device, without `--save-script` if the first attempt saved the script. The same applies when `open --relaunch` cannot confirm its effects. iOS Simulator launch prompt: From 0ed91d6fcf9f7439a13789e1b93acf366594f673 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Sat, 7 Nov 2026 02:58:05 +0800 Subject: [PATCH 02/17] fix(harmonyos): sync open foreground help, warning prose, and changeset Review follow-ups on the foreground verification. The versioned help now states the HarmonyOS side of `--foreground` beside its iOS snapshot semantics, in the flag declaration and in the open command detail that owns the open reasons. The open-not-foreground warning reads as a sentence for both its holder and unreadable-foreground arms, and the patch carries a changeset. Co-Authored-By: Claude Code --- .changeset/harmony-open-foreground-verification.md | 5 +++++ packages/command-registry/src/flag-definitions-action.ts | 4 ++-- packages/command-surface/src/management/app.ts | 2 +- packages/contracts/src/client-app.ts | 4 +++- ...ession-open-execution-foreground-verification.test.ts | 4 +++- .../session-lifecycle/internal/session-open-execution.ts | 9 +++++---- 6 files changed, 19 insertions(+), 9 deletions(-) create mode 100644 .changeset/harmony-open-foreground-verification.md diff --git a/.changeset/harmony-open-foreground-verification.md b/.changeset/harmony-open-foreground-verification.md new file mode 100644 index 0000000000..ab4246bebe --- /dev/null +++ b/.changeset/harmony-open-foreground-verification.md @@ -0,0 +1,5 @@ +--- +'agent-device': patch +--- + +HarmonyOS `open` now reads the foreground app for up to 5 seconds after the launch dispatch. When the opened app never holds the foreground, a plain open succeeds with an `open-not-foreground` warning that names the app holding the foreground, or reports that no foreground app is readable; the response carries the typed `timing.foregroundVerification` fact. With `--foreground`, the open fails with `details.reason: open-not-foreground` instead. A lock screen is a typical cause: unlock the device, then run the open again. diff --git a/packages/command-registry/src/flag-definitions-action.ts b/packages/command-registry/src/flag-definitions-action.ts index 643d7cc110..96d8c48a69 100644 --- a/packages/command-registry/src/flag-definitions-action.ts +++ b/packages/command-registry/src/flag-definitions-action.ts @@ -414,9 +414,9 @@ export const ACTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ type: 'boolean', usageLabel: '--foreground', usageDescription: - 'open: keep normal app/device selection and return an initial snapshot of the first screen (a local iOS simulator waits up to 10s for it); without an app, resolve the sole running app on the sole booted iOS simulator', + 'open: keep normal app/device selection and return an initial snapshot of the first screen (a local iOS simulator waits up to 10s for it); without an app, resolve the sole running app on the sole booted iOS simulator; on HarmonyOS with an app target, fail when the launched app does not hold the foreground within 5s', inputDescription: - 'Include an initial interactive snapshot in a fresh open response. With no app argument, discover the sole running app on the sole booted iOS simulator; ambiguous environments fail closed.', + 'Include an initial interactive snapshot in a fresh open response. With no app argument, discover the sole running app on the sole booted iOS simulator; ambiguous environments fail closed. On HarmonyOS with an app target, the open fails with details.reason open-not-foreground when the launched app does not hold the foreground within 5s.', projectConfig: false, recorded: false, }, diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index bbfdabbac0..e080c76ca8 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -217,7 +217,7 @@ export const openCommandFacet = defineCommandFacet({ summary: 'Open an app, deep link or URL, save replays', searchHint: 'relaunch', cliDetail: - 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session.', + 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. On HarmonyOS, open reads the foreground app after the launch dispatch for up to 5s. When the launched app never holds the foreground, open succeeds and appends a warning that names open-not-foreground and the app that held the foreground, or the fact that no foreground app is readable; unlock the device and run the open again. With --foreground, open fails with details.reason open-not-foreground instead.', mcpDetail: "metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.", }, diff --git a/packages/contracts/src/client-app.ts b/packages/contracts/src/client-app.ts index 24aa401df4..73fc235563 100644 --- a/packages/contracts/src/client-app.ts +++ b/packages/contracts/src/client-app.ts @@ -98,7 +98,9 @@ export type AppOpenOptions = AgentDeviceRequestOverrides & /** * Include an initial interactive snapshot in a fresh open response. With no * app argument, discover the sole running app on the sole booted iOS - * simulator; ambiguous environments fail closed. + * simulator; ambiguous environments fail closed. On HarmonyOS with an app + * target, the open fails with details.reason open-not-foreground when the + * launched app does not hold the foreground within 5s. */ foreground?: boolean; saveScript?: boolean | string; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts index 89f340c7fd..b8f95790ed 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts @@ -145,7 +145,9 @@ test('open names the unreadable foreground instead of a holder package when no m ); const warnings = (data.warnings as string[] | undefined) ?? []; - expect(warnings.some((warning) => warning.includes('no foreground app is readable'))).toBe(true); + expect(warnings.some((warning) => warning.includes('could not read any foreground app'))).toBe( + true, + ); }); test('open adds no foreground warning when the lifecycle outcome carries no unconfirmed read', async () => { diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index 00eb92e581..39383ff60d 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -179,11 +179,12 @@ function launchConfirmationUnansweredWarning(reason: LaunchConfirmationUnanswere /** What the caller's `open` output says when the launched app never held the foreground. */ function openNotForegroundWarning(verification: OpenForegroundVerification): string { - const holder = verification.foregroundPackage - ? `the foreground app is "${verification.foregroundPackage}"` - : 'no foreground app is readable'; + const read = + verification.foregroundPackage === undefined + ? 'HarmonyOS could not read any foreground app' + : `HarmonyOS read that the foreground app stayed "${verification.foregroundPackage}"`; return ( - `The launch dispatch succeeded, but HarmonyOS read ${holder} within 5s of the launch ` + + `The launch dispatch succeeded, but ${read} within 5s of the launch ` + '(open-not-foreground). A lock screen over the device is a typical cause. Unlock the device, ' + 'then run the open again.' ); From 55440d0a999506ac9042a6f4d737b5ff55a3febd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Sun, 8 Nov 2026 22:08:58 +0800 Subject: [PATCH 03/17] docs(evidence): record the open foreground poll against the live mission list Co-Authored-By: Claude Code --- .../harmonyos-open-foreground-2026-11-08.md | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/evidence/harmonyos-open-foreground-2026-11-08.md diff --git a/docs/evidence/harmonyos-open-foreground-2026-11-08.md b/docs/evidence/harmonyos-open-foreground-2026-11-08.md new file mode 100644 index 0000000000..aa0d7f4170 --- /dev/null +++ b/docs/evidence/harmonyos-open-foreground-2026-11-08.md @@ -0,0 +1,61 @@ +# HarmonyOS open foreground verification, 2026-11-08 + +Evidence for #4293 (verify foreground after open instead of trusting the +launch line): the post-check reads the mission list live after the dispatch +and only then reports the open. On this device `aa dump -l` names the +foreground bundle per mission, which is exactly what the poll consumes. + +## Device + +- HUAWEI 畅享 90 Plus, model `JDY-AL50`, HarmonyOS 7.0.0.111 (SP10C00E111R4P3), API 26 +- Serial `77TYD26826028730`, USB, `hdc shell` as uid 2000 (shell) + +## The poll's data source, live + +After `open com.stringzhao.moonwell --activity EntryAbility` through the +branch CLI, the mission list names the launched bundle as the foreground +mission — the same read the poll performs: + +```sh +$ hdc -t 77TYD26826028730 shell "aa dump -l" + Mission ID #45 mission name #[#com.stringzhao.moonwell:entry:EntryAbility] ... + app name [com.stringzhao.moonwell] + bundle name [com.stringzhao.moonwell] + state #FOREGROUND start time [391219654] +``` + +The CLI run itself (branch build): + +```sh +$ node bin/agent-device.mjs open com.stringzhao.moonwell --platform harmonyos \ + --serial 77TYD26826028730 --activity EntryAbility +Opened: com.stringzhao.moonwell +``` + +A second run of a slow-starting app (`com.stringzhao.flashcards`, cold start +with its stored data) also reached `state #FOREGROUND` and opened clean. + +## The unconfirmed paths, and why they are not reproduced live here + +The unconfirmed shape — the launch dispatch accepted while the launched bundle +never holds the foreground — happens under the keyguard (`aa dump -l` keeps +listing missions with none foreground) or when another app keeps stealing the +front. Reproducing the keyguard shape live requires locking this device, whose +unlock PIN this evidence session must not handle; stealing the front raced +against an app that confirmed in ~500 ms. The decision paths are pinned by the +branch's own unit tests instead, all passing: + +- `pollHarmonyOpenForeground keeps polling until the launched bundle holds the foreground` +- `pollHarmonyOpenForeground names the app that kept the foreground when the launch never surfaces` — the warning carries `foregroundPackage` +- `pollHarmonyOpenForeground reports an unreadable foreground when no mission is foreground` — the lock-screen shape +- plus the abort and failed-read shapes + +`open --foreground` escalates an unconfirmed read to a hard +`open-not-foreground` failure with the same `foregroundPackage` detail; a +plain open attaches the read at `timing.foregroundVerification` beside its +warning. + +## Suite + +`packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 89 tests +pass on this branch's build (typecheck and lint clean). From 904df193806a013198dfb317fa09ef55b6a7e1d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Sun, 15 Nov 2026 01:11:03 +0800 Subject: [PATCH 04/17] fix(harmonyos): keep a failed foreground probe from claiming the app stayed backgrounded The poll bounds each read by the budget's remainder, tracks whether any read parsed a foreground mission at all, and marks a budget with zero parseable reads as an unreadable probe. The verify carries that as its own typed reason (open-foreground-probe-unreadable) instead of open-not-foreground, the daemon warning says the read claims nothing about the foreground, and the route tests pin the --foreground hard failure and the unreadable warning. Co-Authored-By: Claude Code --- .../src/application-lifecycle-runtime.ts | 5 ++ ...-execution-foreground-verification.test.ts | 58 +++++++++++++++++- .../internal/session-open-execution.ts | 16 ++++- .../src/__tests__/app-lifecycle.test.ts | 9 ++- .../platform-harmonyos/src/app-lifecycle.ts | 61 +++++++++++++++---- 5 files changed, 131 insertions(+), 18 deletions(-) diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index fcf38c6004..32afe70144 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -165,6 +165,11 @@ export type OpenApplicationTiming = Readonly<{ export type OpenForegroundVerification = Readonly<{ /** True when the launched app held the foreground within the owner's poll budget. */ confirmed: boolean; + /** + * `unreadable` when the poll never parsed one foreground mission in its whole budget — the + * probe answered nothing, which is not evidence that the app stayed backgrounded. + */ + probeState?: 'unreadable'; /** The app that held the foreground instead, when the platform could name one. */ foregroundPackage?: string; }>; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts index b8f95790ed..115a092cfc 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts @@ -59,6 +59,7 @@ async function openApp(params: { sessionStore: SessionStore; sessionName: string; openOutcome: OpenApplicationOutcome; + flags?: Record; onOpenApplication?: (input: OpenApplicationInput) => Promise | void; }): Promise { const bindDevice: Parameters[0]['bindDevice'] = async ( @@ -86,7 +87,7 @@ async function openApp(params: { session: params.sessionName, command: 'open', positionals: ['com.example.application'], - flags: {}, + flags: (params.flags ?? {}) as DaemonRequest['flags'], } as DaemonRequest, sessionName: params.sessionName, logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), @@ -165,3 +166,58 @@ test('open adds no foreground warning when the lifecycle outcome carries no unco const warnings = (data.warnings as string[] | undefined) ?? []; expect(warnings.some((warning) => warning.includes('open-not-foreground'))).toBe(false); }); + +test('open --foreground fails the command when the foreground verification is unconfirmed', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + // The platform owns the hard failure; the mock replays it so the route's + // contract with --foreground is pinned end to end: the openApplication + // failure propagates out of the route instead of reporting a successful open. + await expect( + openApp({ + sessionStore, + sessionName: 'harmony-session', + flags: { foreground: true }, + openOutcome: { + appBundleId: 'com.example.application', + timing: { + foregroundVerification: { confirmed: false, foregroundPackage: 'com.ohos.launcher' }, + }, + }, + onOpenApplication: async (input) => { + if (input.execution.foreground === true) { + throw Object.assign( + new Error( + 'The launch dispatch for com.example.application succeeded, but HarmonyOS did not show it in the foreground within 5s', + ), + { code: 'COMMAND_FAILED', details: { reason: 'open-not-foreground' } }, + ); + } + }, + }), + ).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { reason: 'open-not-foreground' } }); +}); + +test('open names the unreadable probe instead of claiming the app stayed backgrounded', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + const data = requireOpenData( + await openApp({ + sessionStore, + sessionName: 'harmony-session', + openOutcome: { + appBundleId: 'com.example.application', + timing: { foregroundVerification: { confirmed: false, probeState: 'unreadable' } }, + }, + }), + ); + + const warnings = (data.warnings as string[] | undefined) ?? []; + expect(warnings.some((warning) => warning.includes('open-foreground-probe-unreadable'))).toBe( + true, + ); + expect(warnings.some((warning) => warning.includes('claims nothing'))).toBe(true); + expect(warnings.some((warning) => warning.includes('open-not-foreground'))).toBe(false); +}); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index 39383ff60d..34a9076ca5 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -177,6 +177,15 @@ function launchConfirmationUnansweredWarning(reason: LaunchConfirmationUnanswere ); } +/** What the caller's `open` output says when the probe never read one foreground app. */ +function openProbeUnreadableWarning(): string { + return ( + 'The launch dispatch succeeded, but the foreground probe could not read the device within 5s ' + + '(open-foreground-probe-unreadable). This claims nothing about whether the app reached the ' + + 'foreground; check the device connection, then run the open again.' + ); +} + /** What the caller's `open` output says when the launched app never held the foreground. */ function openNotForegroundWarning(verification: OpenForegroundVerification): string { const read = @@ -401,10 +410,13 @@ export async function completeOpenCommand(params: { if (outcome.launchConfirmation === undefined && outcome.launchConfirmationProbeFailure) { appendResponseWarning(openResult, launchConfirmationProbeFailureWarning()); } - if (outcome.timing.foregroundVerification?.confirmed === false) { + const foregroundVerification = outcome.timing.foregroundVerification; + if (foregroundVerification?.confirmed === false) { appendResponseWarning( openResult, - openNotForegroundWarning(outcome.timing.foregroundVerification), + foregroundVerification.probeState === 'unreadable' + ? openProbeUnreadableWarning() + : openNotForegroundWarning(foregroundVerification), ); } const nextRef = publishOpenSession({ diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 4ccfd3cf7c..6f67dc096b 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -386,7 +386,9 @@ test('pollHarmonyOpenForeground reports an unreadable foreground when no mission pollIntervalMs: 10, }); - assert.deepEqual(read, { confirmed: false }); + // A budget with zero parseable foreground reads is an unreadable probe, not + // evidence that the app stayed backgrounded. + assert.deepEqual(read, { confirmed: false, probeState: 'unreadable' }); }); test('pollHarmonyOpenForeground treats a failed read as unconfirmed and keeps polling', async () => { @@ -492,7 +494,10 @@ test('verifyHarmonyOpenForeground reports an unreadable foreground when no missi await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); const verified = await pending; - assert.deepEqual(verified.timing.foregroundVerification, { confirmed: false }); + assert.deepEqual(verified.timing.foregroundVerification, { + confirmed: false, + probeState: 'unreadable', + }); }); test('verifyHarmonyOpenForeground fails the open when --foreground demands the foreground and the launch never surfaces', async () => { diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index a016e498e3..dfe8b2e701 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -6,7 +6,6 @@ import type { OpenApplicationInput, OpenApplicationOutcome, } from '@agent-device/contracts/application-lifecycle-runtime'; -import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime'; import { isDeepLinkTarget } from '@agent-device/contracts/command'; import { runHarmonyShell } from './hdc.ts'; import { parseHarmonyForegroundApp } from './app-state.ts'; @@ -235,10 +234,15 @@ export const HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS = 5_000; /** One foreground read per interval until the budget runs out; the first read costs no wait. */ const HARMONY_OPEN_FOREGROUND_POLL_INTERVAL_MS = 500; +/** One `aa dump -l` read; a read never outlives the poll's own budget remainder. */ +const HARMONY_OPEN_FOREGROUND_READ_TIMEOUT_MS = 5_000; + /** What one bounded foreground poll decided about a launched bundle. */ export type HarmonyOpenForegroundRead = Readonly<{ confirmed: boolean; foregroundPackage?: string; + /** `unreadable` when the budget closed without one parseable foreground read. */ + probeState?: 'unreadable'; }>; /** @@ -259,32 +263,48 @@ export async function pollHarmonyOpenForeground( const pollIntervalMs = options.pollIntervalMs ?? HARMONY_OPEN_FOREGROUND_POLL_INTERVAL_MS; const deadlineAtMs = Date.now() + pollBudgetMs; let foregroundPackage: string | undefined; + let sawReadable = false; while (true) { options.signal?.throwIfAborted(); - const foregroundPackageRead = (await readHarmonyForegroundMission(device, options.signal)) - ?.package; - if (foregroundPackageRead === bundleId) return { confirmed: true }; - if (foregroundPackageRead !== undefined) foregroundPackage = foregroundPackageRead; - if (Date.now() >= deadlineAtMs) { - return foregroundPackage === undefined - ? { confirmed: false } - : { confirmed: false, foregroundPackage }; + // Each read is bounded by the budget's remainder, so one slow read cannot + // push the poll past its deadline. + const remainingMs = deadlineAtMs - Date.now(); + if (remainingMs <= 0) break; + const foregroundPackageRead = await readHarmonyForegroundMission( + device, + options.signal, + Math.min(remainingMs, HARMONY_OPEN_FOREGROUND_READ_TIMEOUT_MS), + ); + if (foregroundPackageRead !== undefined) { + sawReadable = true; + if (foregroundPackageRead === bundleId) return { confirmed: true }; + foregroundPackage = foregroundPackageRead; } - await sleep(pollIntervalMs, undefined, { signal: options.signal }); + const remainingAfterRead = deadlineAtMs - Date.now(); + if (remainingAfterRead <= 0) break; + await sleep(Math.min(pollIntervalMs, remainingAfterRead), undefined, { + signal: options.signal, + }); } + return { + confirmed: false, + ...(foregroundPackage !== undefined ? { foregroundPackage } : {}), + ...(sawReadable ? {} : { probeState: 'unreadable' as const }), + }; } /** One foreground read; a failed or unreadable read answers undefined instead of throwing. */ async function readHarmonyForegroundMission( device: DeviceInfo, signal: AbortSignal | undefined, -): Promise { + timeoutMs: number, +): Promise { try { const result = await runHarmonyShell(device, ['aa', 'dump', '-l'], { signal, - timeoutMs: 5_000, + timeoutMs, }); - return parseHarmonyForegroundApp(result.stdout); + return parseHarmonyForegroundApp(result.stdout)?.package; } catch (error) { if (signal?.aborted) throw error; return undefined; @@ -306,6 +326,21 @@ export async function verifyHarmonyOpenForeground( if (bundleId === undefined || isDeepLinkTarget(bundleId)) return outcome; const read = await pollHarmonyOpenForeground(device, bundleId, { signal }); if (read.confirmed) return outcome; + if (read.probeState === 'unreadable') { + // A budget with zero parseable reads is a failed probe, not evidence the + // app stayed backgrounded, so it carries its own reason. + if (input.execution.foreground === true) { + throw new AppError( + 'COMMAND_FAILED', + `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, + { + reason: 'open-foreground-probe-unreadable', + hint: 'Check the device connection, then run the open again.', + }, + ); + } + return { ...outcome, timing: { ...outcome.timing, foregroundVerification: read } }; + } if (input.execution.foreground === true) { throw new AppError( 'COMMAND_FAILED', From ca855ccd172b8316d42431bf9daccc1edf74281a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Mon, 16 Nov 2026 22:48:37 +0800 Subject: [PATCH 05/17] fix(harmonyos): tell a successful no-foreground read from a failed probe OpenForegroundVerification becomes the one fact the poll returns: a discriminated state instead of confirmed-plus-modifiers. A read that answered with no FOREGROUND mission is the lock-screen shape and now reports open-not-foreground (unlock) instead of claiming the probe was unreadable; probe-failed is reserved for budgets whose every read failed to run. The parse owner returns the three-way read, both reasons are stated on every help surface, and the changeset goes away with main's changeset removal. Co-Authored-By: Claude Code --- .../harmony-open-foreground-verification.md | 5 -- .../src/flag-definitions-action.ts | 2 +- .../command-surface/src/management/app.ts | 2 +- .../src/application-lifecycle-runtime.ts | 30 +++---- packages/contracts/src/client-app.ts | 4 +- ...-execution-foreground-verification.test.ts | 54 ++++++++++--- .../internal/session-open-execution.ts | 10 +-- .../src/__tests__/app-lifecycle.test.ts | 60 ++++++++++---- .../platform-harmonyos/src/app-lifecycle.ts | 81 +++++++++++-------- .../platform-harmonyos/src/app-state.test.ts | 26 ++++-- packages/platform-harmonyos/src/app-state.ts | 30 +++++-- 11 files changed, 205 insertions(+), 99 deletions(-) delete mode 100644 .changeset/harmony-open-foreground-verification.md diff --git a/.changeset/harmony-open-foreground-verification.md b/.changeset/harmony-open-foreground-verification.md deleted file mode 100644 index ab4246bebe..0000000000 --- a/.changeset/harmony-open-foreground-verification.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'agent-device': patch ---- - -HarmonyOS `open` now reads the foreground app for up to 5 seconds after the launch dispatch. When the opened app never holds the foreground, a plain open succeeds with an `open-not-foreground` warning that names the app holding the foreground, or reports that no foreground app is readable; the response carries the typed `timing.foregroundVerification` fact. With `--foreground`, the open fails with `details.reason: open-not-foreground` instead. A lock screen is a typical cause: unlock the device, then run the open again. diff --git a/packages/command-registry/src/flag-definitions-action.ts b/packages/command-registry/src/flag-definitions-action.ts index 96d8c48a69..c03ba36711 100644 --- a/packages/command-registry/src/flag-definitions-action.ts +++ b/packages/command-registry/src/flag-definitions-action.ts @@ -416,7 +416,7 @@ export const ACTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ usageDescription: 'open: keep normal app/device selection and return an initial snapshot of the first screen (a local iOS simulator waits up to 10s for it); without an app, resolve the sole running app on the sole booted iOS simulator; on HarmonyOS with an app target, fail when the launched app does not hold the foreground within 5s', inputDescription: - 'Include an initial interactive snapshot in a fresh open response. With no app argument, discover the sole running app on the sole booted iOS simulator; ambiguous environments fail closed. On HarmonyOS with an app target, the open fails with details.reason open-not-foreground when the launched app does not hold the foreground within 5s.', + 'Include an initial interactive snapshot in a fresh open response. With no app argument, discover the sole running app on the sole booted iOS simulator; ambiguous environments fail closed. On HarmonyOS with an app target, the open fails with details.reason open-not-foreground when the launched app does not hold the foreground within 5s, or open-foreground-probe-unreadable when no read of the mission list succeeds in that budget.', projectConfig: false, recorded: false, }, diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index e080c76ca8..e78dc49433 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -217,7 +217,7 @@ export const openCommandFacet = defineCommandFacet({ summary: 'Open an app, deep link or URL, save replays', searchHint: 'relaunch', cliDetail: - 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. On HarmonyOS, open reads the foreground app after the launch dispatch for up to 5s. When the launched app never holds the foreground, open succeeds and appends a warning that names open-not-foreground and the app that held the foreground, or the fact that no foreground app is readable; unlock the device and run the open again. With --foreground, open fails with details.reason open-not-foreground instead.', + 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. On HarmonyOS, open reads the foreground app after the launch dispatch for up to 5s. When the launched app never holds the foreground, open succeeds and appends a warning that names open-not-foreground with the app that held the foreground, or the fact that no mission is foreground; unlock the device and run the open again. When no read of the mission list succeeds in that budget, the warning names open-foreground-probe-unreadable instead and claims nothing about the app; check the device connection. With --foreground, an unconfirmed open fails with details.reason open-not-foreground or open-foreground-probe-unreadable, matching the same two cases.', mcpDetail: "metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.", }, diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index 32afe70144..660773e011 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -157,22 +157,22 @@ export type OpenApplicationTiming = Readonly<{ }>; /** - * What an owner learned when it verified after its dispatch which app holds the foreground. A - * launch dispatch can report success while a system surface (a lock screen is the typical one) - * keeps the launched app behind it, so the verification is a bounded poll of the platform's own - * foreground read. + * What an owner learned when it verified after its dispatch which app holds the foreground, and + * the launched app never held it. A launch dispatch can report success while a system surface (a + * lock screen is the typical one) keeps the launched app behind it, so the verification is a + * bounded poll of the platform's own foreground read. It is present only when unconfirmed, and + * its state names what the probe actually saw: + * + * - `other-foreground`: a read succeeded and named another app in the foreground. + * - `no-foreground`: a read succeeded and no mission is foreground. A lock screen is the typical + * cause; unlock the device and retry. + * - `probe-failed`: no read in the budget produced a parsed mission list. Check the device + * connection; this claims nothing about the launched app. */ -export type OpenForegroundVerification = Readonly<{ - /** True when the launched app held the foreground within the owner's poll budget. */ - confirmed: boolean; - /** - * `unreadable` when the poll never parsed one foreground mission in its whole budget — the - * probe answered nothing, which is not evidence that the app stayed backgrounded. - */ - probeState?: 'unreadable'; - /** The app that held the foreground instead, when the platform could name one. */ - foregroundPackage?: string; -}>; +export type OpenForegroundVerification = + | Readonly<{ state: 'other-foreground'; foregroundPackage: string }> + | Readonly<{ state: 'no-foreground' }> + | Readonly<{ state: 'probe-failed' }>; /** * What an app open learned about the launched app before it returned. A local iOS Simulator asks diff --git a/packages/contracts/src/client-app.ts b/packages/contracts/src/client-app.ts index 73fc235563..4dba0acb77 100644 --- a/packages/contracts/src/client-app.ts +++ b/packages/contracts/src/client-app.ts @@ -100,7 +100,9 @@ export type AppOpenOptions = AgentDeviceRequestOverrides & * app argument, discover the sole running app on the sole booted iOS * simulator; ambiguous environments fail closed. On HarmonyOS with an app * target, the open fails with details.reason open-not-foreground when the - * launched app does not hold the foreground within 5s. + * launched app does not hold the foreground within 5s, or + * open-foreground-probe-unreadable when no read of the mission list + * succeeds in that budget. */ foreground?: boolean; saveScript?: boolean | string; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts index 115a092cfc..04909f97a6 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-foreground-verification.test.ts @@ -113,7 +113,10 @@ test('open warns and carries the typed read when the launched app never held the openOutcome: { appBundleId: 'com.example.application', timing: { - foregroundVerification: { confirmed: false, foregroundPackage: 'com.ohos.launcher' }, + foregroundVerification: { + state: 'other-foreground', + foregroundPackage: 'com.ohos.launcher', + }, }, }, }), @@ -125,12 +128,12 @@ test('open warns and carries the typed read when the launched app never held the expect(warnings.some((warning) => warning.toLowerCase().includes('unlock'))).toBe(true); const timing = data.timing as Record | undefined; expect(timing?.foregroundVerification).toEqual({ - confirmed: false, + state: 'other-foreground', foregroundPackage: 'com.ohos.launcher', }); }); -test('open names the unreadable foreground instead of a holder package when no mission is foreground', async () => { +test('open tells the user to unlock when a read answered with no foreground mission', async () => { const sessionStore = makeSessionStore(); publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); @@ -140,15 +143,15 @@ test('open names the unreadable foreground instead of a holder package when no m sessionName: 'harmony-session', openOutcome: { appBundleId: 'com.example.application', - timing: { foregroundVerification: { confirmed: false } }, + timing: { foregroundVerification: { state: 'no-foreground' } }, }, }), ); const warnings = (data.warnings as string[] | undefined) ?? []; - expect(warnings.some((warning) => warning.includes('could not read any foreground app'))).toBe( - true, - ); + expect(warnings.some((warning) => warning.includes('open-not-foreground'))).toBe(true); + expect(warnings.some((warning) => warning.includes('no mission in the foreground'))).toBe(true); + expect(warnings.some((warning) => warning.toLowerCase().includes('unlock'))).toBe(true); }); test('open adds no foreground warning when the lifecycle outcome carries no unconfirmed read', async () => { @@ -182,7 +185,10 @@ test('open --foreground fails the command when the foreground verification is un openOutcome: { appBundleId: 'com.example.application', timing: { - foregroundVerification: { confirmed: false, foregroundPackage: 'com.ohos.launcher' }, + foregroundVerification: { + state: 'other-foreground', + foregroundPackage: 'com.ohos.launcher', + }, }, }, onOpenApplication: async (input) => { @@ -209,7 +215,7 @@ test('open names the unreadable probe instead of claiming the app stayed backgro sessionName: 'harmony-session', openOutcome: { appBundleId: 'com.example.application', - timing: { foregroundVerification: { confirmed: false, probeState: 'unreadable' } }, + timing: { foregroundVerification: { state: 'probe-failed' } }, }, }), ); @@ -221,3 +227,33 @@ test('open names the unreadable probe instead of claiming the app stayed backgro expect(warnings.some((warning) => warning.includes('claims nothing'))).toBe(true); expect(warnings.some((warning) => warning.includes('open-not-foreground'))).toBe(false); }); + +test('open --foreground propagates the unreadable-probe failure when no read succeeded', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + await expect( + openApp({ + sessionStore, + sessionName: 'harmony-session', + flags: { foreground: true }, + openOutcome: { + appBundleId: 'com.example.application', + timing: { foregroundVerification: { state: 'probe-failed' } }, + }, + onOpenApplication: async (input) => { + if (input.execution.foreground === true) { + throw Object.assign( + new Error( + 'The launch dispatch for com.example.application succeeded, but the foreground probe could not read the device within 5s', + ), + { code: 'COMMAND_FAILED', details: { reason: 'open-foreground-probe-unreadable' } }, + ); + } + }, + }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'open-foreground-probe-unreadable' }, + }); +}); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index 34a9076ca5..5ad630eb30 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -189,9 +189,9 @@ function openProbeUnreadableWarning(): string { /** What the caller's `open` output says when the launched app never held the foreground. */ function openNotForegroundWarning(verification: OpenForegroundVerification): string { const read = - verification.foregroundPackage === undefined - ? 'HarmonyOS could not read any foreground app' - : `HarmonyOS read that the foreground app stayed "${verification.foregroundPackage}"`; + verification.state === 'other-foreground' + ? `HarmonyOS read that the foreground app stayed "${verification.foregroundPackage}"` + : 'HarmonyOS read no mission in the foreground'; return ( `The launch dispatch succeeded, but ${read} within 5s of the launch ` + '(open-not-foreground). A lock screen over the device is a typical cause. Unlock the device, ' + @@ -411,10 +411,10 @@ export async function completeOpenCommand(params: { appendResponseWarning(openResult, launchConfirmationProbeFailureWarning()); } const foregroundVerification = outcome.timing.foregroundVerification; - if (foregroundVerification?.confirmed === false) { + if (foregroundVerification) { appendResponseWarning( openResult, - foregroundVerification.probeState === 'unreadable' + foregroundVerification.state === 'probe-failed' ? openProbeUnreadableWarning() : openNotForegroundWarning(foregroundVerification), ); diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 6f67dc096b..430a01f624 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -333,7 +333,7 @@ test('pollHarmonyOpenForeground confirms the launched bundle on the first foregr const read = await pollHarmonyOpenForeground(DEVICE, 'com.example.application'); - assert.deepEqual(read, { confirmed: true }); + assert.equal(read, undefined); assert.deepEqual(mockRunCmd.mock.calls[0]?.[1], ['-t', 'harmony-1', 'shell', 'aa', 'dump', '-l']); }); @@ -355,7 +355,7 @@ test('pollHarmonyOpenForeground keeps polling until the launched bundle holds th pollIntervalMs: 1, }); - assert.deepEqual(read, { confirmed: true }); + assert.equal(read, undefined); assert.equal(mockRunCmd.mock.calls.length, 3); }); @@ -371,10 +371,10 @@ test('pollHarmonyOpenForeground names the app that kept the foreground when the pollIntervalMs: 10, }); - assert.deepEqual(read, { confirmed: false, foregroundPackage: 'com.ohos.launcher' }); + assert.deepEqual(read, { state: 'other-foreground', foregroundPackage: 'com.ohos.launcher' }); }); -test('pollHarmonyOpenForeground reports an unreadable foreground when no mission is foreground', async () => { +test('pollHarmonyOpenForeground classifies a mission list with no foreground mission as no-foreground', async () => { mockRunCmd.mockResolvedValue({ exitCode: 0, stdout: missionDump('com.example.application', 'BACKGROUND'), @@ -386,9 +386,21 @@ test('pollHarmonyOpenForeground reports an unreadable foreground when no mission pollIntervalMs: 10, }); - // A budget with zero parseable foreground reads is an unreadable probe, not - // evidence that the app stayed backgrounded. - assert.deepEqual(read, { confirmed: false, probeState: 'unreadable' }); + // The read answered — a mission list with no FOREGROUND mission is the + // lock-screen shape, not a probe that failed to run. + assert.deepEqual(read, { state: 'no-foreground' }); +}); + +test('pollHarmonyOpenForeground reports probe-failed when every read fails', async () => { + mockRunCmd.mockRejectedValue(new Error('hdc died mid-read')); + + const read = await pollHarmonyOpenForeground(DEVICE, 'com.example.application', { + pollBudgetMs: 40, + pollIntervalMs: 10, + }); + + // A budget whose every read failed is a probe that never ran to an answer. + assert.deepEqual(read, { state: 'probe-failed' }); }); test('pollHarmonyOpenForeground treats a failed read as unconfirmed and keeps polling', async () => { @@ -402,7 +414,7 @@ test('pollHarmonyOpenForeground treats a failed read as unconfirmed and keeps po pollIntervalMs: 1, }); - assert.deepEqual(read, { confirmed: true }); + assert.equal(read, undefined); }); test('pollHarmonyOpenForeground rejects when the request signal aborts mid-poll', async () => { @@ -473,12 +485,12 @@ test('verifyHarmonyOpenForeground attaches the foreground read when the launch n const verified = await pending; assert.deepEqual(verified.timing.foregroundVerification, { - confirmed: false, + state: 'other-foreground', foregroundPackage: 'com.ohos.launcher', }); }); -test('verifyHarmonyOpenForeground reports an unreadable foreground when no mission is foreground', async () => { +test('verifyHarmonyOpenForeground attaches no-foreground when a read answered with no foreground mission', async () => { vi.useFakeTimers(); mockRunCmd.mockResolvedValue({ exitCode: 0, @@ -494,10 +506,30 @@ test('verifyHarmonyOpenForeground reports an unreadable foreground when no missi await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); const verified = await pending; - assert.deepEqual(verified.timing.foregroundVerification, { - confirmed: false, - probeState: 'unreadable', - }); + assert.deepEqual(verified.timing.foregroundVerification, { state: 'no-foreground' }); +}); + +test('verifyHarmonyOpenForeground fails --foreground with the unreadable reason when every read fails', async () => { + vi.useFakeTimers(); + mockRunCmd.mockRejectedValue(new Error('hdc died mid-read')); + const pending = verifyHarmonyOpenForeground( + openInput({ execution: { foreground: true } }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); + + await assert.rejects( + () => pending, + (error: unknown) => { + assert(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(error.details?.reason, 'open-foreground-probe-unreadable'); + assert.match(error.details?.hint ?? '', /check the device connection/i); + return true; + }, + ); }); test('verifyHarmonyOpenForeground fails the open when --foreground demands the foreground and the launch never surfaces', async () => { diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index dfe8b2e701..b8623f3fe7 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -5,10 +5,11 @@ import { AppError } from '@agent-device/kernel/errors'; import type { OpenApplicationInput, OpenApplicationOutcome, + OpenForegroundVerification, } from '@agent-device/contracts/application-lifecycle-runtime'; import { isDeepLinkTarget } from '@agent-device/contracts/command'; import { runHarmonyShell } from './hdc.ts'; -import { parseHarmonyForegroundApp } from './app-state.ts'; +import { parseHarmonyForegroundRead } from './app-state.ts'; import { invalidateHarmonyGestureViewport } from './snapshot.ts'; export function parseHarmonyBundleList(rawOutput: string): string[] { @@ -237,18 +238,10 @@ const HARMONY_OPEN_FOREGROUND_POLL_INTERVAL_MS = 500; /** One `aa dump -l` read; a read never outlives the poll's own budget remainder. */ const HARMONY_OPEN_FOREGROUND_READ_TIMEOUT_MS = 5_000; -/** What one bounded foreground poll decided about a launched bundle. */ -export type HarmonyOpenForegroundRead = Readonly<{ - confirmed: boolean; - foregroundPackage?: string; - /** `unreadable` when the budget closed without one parseable foreground read. */ - probeState?: 'unreadable'; -}>; - /** * Reads which HarmonyOS mission holds the foreground until the launched bundle does, the poll - * budget runs out, or the request is aborted. A read that names no FOREGROUND mission (the - * lock-screen shape) or fails to run counts as unconfirmed and keeps polling. + * budget runs out, or the request is aborted. Answers the contract's verification fact when the + * budget closed unconfirmed, and `undefined` when the launched bundle held the foreground. */ export async function pollHarmonyOpenForeground( device: DeviceInfo, @@ -258,7 +251,7 @@ export async function pollHarmonyOpenForeground( pollBudgetMs?: number; pollIntervalMs?: number; }> = {}, -): Promise { +): Promise { const pollBudgetMs = options.pollBudgetMs ?? HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS; const pollIntervalMs = options.pollIntervalMs ?? HARMONY_OPEN_FOREGROUND_POLL_INTERVAL_MS; const deadlineAtMs = Date.now() + pollBudgetMs; @@ -270,15 +263,20 @@ export async function pollHarmonyOpenForeground( // push the poll past its deadline. const remainingMs = deadlineAtMs - Date.now(); if (remainingMs <= 0) break; - const foregroundPackageRead = await readHarmonyForegroundMission( + const missionRead = await readHarmonyForegroundMission( device, options.signal, Math.min(remainingMs, HARMONY_OPEN_FOREGROUND_READ_TIMEOUT_MS), ); - if (foregroundPackageRead !== undefined) { + if (missionRead.kind === 'foreground') { + sawReadable = true; + if (missionRead.package === bundleId) return undefined; + foregroundPackage = missionRead.package; + } else if (missionRead.kind === 'no-foreground-mission') { + // A read that answered with no FOREGROUND mission is the lock-screen + // shape: evidence the app stayed behind a system surface, not a probe + // that failed to run. sawReadable = true; - if (foregroundPackageRead === bundleId) return { confirmed: true }; - foregroundPackage = foregroundPackageRead; } const remainingAfterRead = deadlineAtMs - Date.now(); if (remainingAfterRead <= 0) break; @@ -286,28 +284,40 @@ export async function pollHarmonyOpenForeground( signal: options.signal, }); } - return { - confirmed: false, - ...(foregroundPackage !== undefined ? { foregroundPackage } : {}), - ...(sawReadable ? {} : { probeState: 'unreadable' as const }), - }; + if (!sawReadable) return { state: 'probe-failed' }; + if (foregroundPackage !== undefined) { + return { state: 'other-foreground', foregroundPackage }; + } + return { state: 'no-foreground' }; } -/** One foreground read; a failed or unreadable read answers undefined instead of throwing. */ +/** + * One foreground read. `no-foreground-mission` is the lock-screen shape; `failed` is a read that + * threw, timed out, or produced output with no parseable mission list. + */ +type HarmonyForegroundMissionRead = + | { kind: 'foreground'; package: string } + | { kind: 'no-foreground-mission' } + | { kind: 'failed' }; + async function readHarmonyForegroundMission( device: DeviceInfo, signal: AbortSignal | undefined, timeoutMs: number, -): Promise { +): Promise { try { const result = await runHarmonyShell(device, ['aa', 'dump', '-l'], { signal, timeoutMs, }); - return parseHarmonyForegroundApp(result.stdout)?.package; + const parse = parseHarmonyForegroundRead(result.stdout); + if (parse.kind === 'foreground') return { kind: 'foreground', package: parse.package }; + return parse.kind === 'no-foreground-mission' + ? { kind: 'no-foreground-mission' } + : { kind: 'failed' }; } catch (error) { if (signal?.aborted) throw error; - return undefined; + return { kind: 'failed' }; } } @@ -324,11 +334,12 @@ export async function verifyHarmonyOpenForeground( ): Promise { const bundleId = outcome.appBundleId ?? input.appBundleId; if (bundleId === undefined || isDeepLinkTarget(bundleId)) return outcome; - const read = await pollHarmonyOpenForeground(device, bundleId, { signal }); - if (read.confirmed) return outcome; - if (read.probeState === 'unreadable') { - // A budget with zero parseable reads is a failed probe, not evidence the - // app stayed backgrounded, so it carries its own reason. + const verification = await pollHarmonyOpenForeground(device, bundleId, { signal }); + if (verification === undefined) return outcome; + if (verification.state === 'probe-failed') { + // A budget whose every read failed is a probe that never ran to an + // answer, not evidence the app stayed backgrounded, so it carries its + // own reason. if (input.execution.foreground === true) { throw new AppError( 'COMMAND_FAILED', @@ -339,7 +350,7 @@ export async function verifyHarmonyOpenForeground( }, ); } - return { ...outcome, timing: { ...outcome.timing, foregroundVerification: read } }; + return { ...outcome, timing: { ...outcome.timing, foregroundVerification: verification } }; } if (input.execution.foreground === true) { throw new AppError( @@ -348,13 +359,13 @@ export async function verifyHarmonyOpenForeground( { reason: 'open-not-foreground', hint: 'Unlock the device screen, then run the open again.', - ...(read.foregroundPackage === undefined - ? {} - : { foregroundPackage: read.foregroundPackage }), + ...(verification.state === 'other-foreground' + ? { foregroundPackage: verification.foregroundPackage } + : {}), }, ); } - return { ...outcome, timing: { ...outcome.timing, foregroundVerification: read } }; + return { ...outcome, timing: { ...outcome.timing, foregroundVerification: verification } }; } export async function closeHarmonyApp(device: DeviceInfo, bundleId: string): Promise { diff --git a/packages/platform-harmonyos/src/app-state.test.ts b/packages/platform-harmonyos/src/app-state.test.ts index 3c16d39366..ab3c5f24d4 100644 --- a/packages/platform-harmonyos/src/app-state.test.ts +++ b/packages/platform-harmonyos/src/app-state.test.ts @@ -1,17 +1,33 @@ import { expect, test } from 'vitest'; -import { parseHarmonyForegroundApp } from './app-state.ts'; +import { parseHarmonyForegroundRead } from './app-state.ts'; test('parses the foreground ability from the mission list', () => { expect( - parseHarmonyForegroundApp(` + parseHarmonyForegroundRead(` Mission ID #57 mission name #[#com.huawei.hmos.settings:phone_settings:com.huawei.hmos.settings.MainAbility] state #BACKGROUND Mission ID #76 mission name #[#com.example.application:entry:EntryAbility] state #FOREGROUND `), - ).toEqual({ package: 'com.example.application', activity: 'EntryAbility' }); + ).toEqual({ kind: 'foreground', package: 'com.example.application', activity: 'EntryAbility' }); }); -test('rejects a mission list without a foreground ability', () => { - expect(parseHarmonyForegroundApp('Mission ID #57 state #BACKGROUND')).toBeUndefined(); +test('classifies a mission list without a foreground mission as no-foreground-mission', () => { + expect(parseHarmonyForegroundRead('Mission ID #57 state #BACKGROUND')).toEqual({ + kind: 'no-foreground-mission', + }); +}); + +test('classifies output with no mission list as unparseable', () => { + expect(parseHarmonyForegroundRead('')).toEqual({ kind: 'unparseable' }); + expect(parseHarmonyForegroundRead('aa: error: dump failed')).toEqual({ kind: 'unparseable' }); +}); + +test('classifies a foreground mission whose name did not parse as unparseable', () => { + expect( + parseHarmonyForegroundRead(` + Mission ID #57 mission name #[malformed + state #FOREGROUND + `), + ).toEqual({ kind: 'unparseable' }); }); diff --git a/packages/platform-harmonyos/src/app-state.ts b/packages/platform-harmonyos/src/app-state.ts index f655c06045..7dac2067ea 100644 --- a/packages/platform-harmonyos/src/app-state.ts +++ b/packages/platform-harmonyos/src/app-state.ts @@ -13,24 +13,38 @@ export async function readHarmonyAppState( signal, }); signal.throwIfAborted(); - const foreground = parseHarmonyForegroundApp(result.stdout); - if (!foreground) { + const foreground = parseHarmonyForegroundRead(result.stdout); + if (foreground.kind !== 'foreground') { throw new AppError('COMMAND_FAILED', 'Could not determine the foreground HarmonyOS app', { hint: 'Open an app on the target, then retry appstate.', }); } - return foreground; + return { package: foreground.package, activity: foreground.activity }; } -export function parseHarmonyForegroundApp(rawOutput: string): AppStateRuntimeResult | undefined { +/** + * What one `aa dump -l` output yielded. `no-foreground-mission` is a read that answered: the + * output parsed as a mission list and no mission holds the foreground, which a system surface + * (the lock screen is the typical one) produces. `unparseable` output names no mission list at + * all, or a foreground mission whose own name did not parse. + */ +export type HarmonyForegroundParse = + | { kind: 'foreground'; package: string; activity: string } + | { kind: 'no-foreground-mission' } + | { kind: 'unparseable' }; + +export function parseHarmonyForegroundRead(rawOutput: string): HarmonyForegroundParse { const missions = rawOutput.split(/(?=^\s*Mission ID #)/m); + let sawMission = false; for (const mission of missions) { + if (!/\bMission ID #/.test(mission)) continue; + sawMission = true; if (!/\bstate #FOREGROUND\b/.test(mission)) continue; const match = mission.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/); - if (!match) continue; + if (!match) return { kind: 'unparseable' }; const [, packageName, activity] = match; - if (!packageName || !activity) continue; - return { package: packageName, activity }; + if (!packageName || !activity) return { kind: 'unparseable' }; + return { kind: 'foreground', package: packageName, activity }; } - return undefined; + return sawMission ? { kind: 'no-foreground-mission' } : { kind: 'unparseable' }; } From 55c66d36093635ffaf529738f3cfc409c8bb3f89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Mon, 16 Nov 2026 23:02:16 +0800 Subject: [PATCH 06/17] docs(evidence): run the failed-probe open live and restate the suite size The stubbed-hdc run reproduces the maintainer's offered second live case: only the poll's aa dump reads fail, and the plain open carries the open-foreground-probe-unreadable warning while --foreground fails with that reason. The keyguard shape of the mission list is observed live, but this unit's shell launches wake past the suspended screen, so the end-to-end no-foreground open stays maintainer-runnable. The 89-tests line becomes the real count. Co-Authored-By: Claude Code --- .../harmonyos-open-foreground-2026-11-08.md | 103 ++++++++++++------ .../src/flag-definitions-action.ts | 2 +- .../command-surface/src/management/app.ts | 2 +- packages/contracts/src/client-app.ts | 5 +- .../platform-harmonyos/src/runtime.test.ts | 1 + .../command-tools-loading-meta.test.ts | 5 +- 6 files changed, 81 insertions(+), 37 deletions(-) diff --git a/docs/evidence/harmonyos-open-foreground-2026-11-08.md b/docs/evidence/harmonyos-open-foreground-2026-11-08.md index aa0d7f4170..78ff2ab389 100644 --- a/docs/evidence/harmonyos-open-foreground-2026-11-08.md +++ b/docs/evidence/harmonyos-open-foreground-2026-11-08.md @@ -5,57 +5,98 @@ launch line): the post-check reads the mission list live after the dispatch and only then reports the open. On this device `aa dump -l` names the foreground bundle per mission, which is exactly what the poll consumes. +All runs below are at the head that reports the poll as one state: +`other-foreground` names a holder, `no-foreground` is a read that answered +with no foreground mission, and `probe-failed` is a budget whose every read +failed to run. + ## Device - HUAWEI 畅享 90 Plus, model `JDY-AL50`, HarmonyOS 7.0.0.111 (SP10C00E111R4P3), API 26 - Serial `77TYD26826028730`, USB, `hdc shell` as uid 2000 (shell) -## The poll's data source, live +## The confirmed path, live at the head + +A plain open of an idle app confirms within the first poll read and rides +with no verification fact and no warning: + +```json +{"success": true, "data": {"appName": "com.stringzhao.moonwell", + "warnings": null}} +``` -After `open com.stringzhao.moonwell --activity EntryAbility` through the -branch CLI, the mission list names the launched bundle as the foreground -mission — the same read the poll performs: +The mission list read the same seconds after the dispatch: ```sh $ hdc -t 77TYD26826028730 shell "aa dump -l" - Mission ID #45 mission name #[#com.stringzhao.moonwell:entry:EntryAbility] ... - app name [com.stringzhao.moonwell] bundle name [com.stringzhao.moonwell] - state #FOREGROUND start time [391219654] + state #FOREGROUND start time [914348158] ``` -The CLI run itself (branch build): +## The keyguard shape of the mission list, observed live + +With the screen suspended, `aa dump -l` answers with missions and no +`state #FOREGROUND` line anywhere (12 missions, all `#BACKGROUND`) — the +read that the poll classifies as `no-foreground`: ```sh -$ node bin/agent-device.mjs open com.stringzhao.moonwell --platform harmonyos \ - --serial 77TYD26826028730 --activity EntryAbility -Opened: com.stringzhao.moonwell +$ hdc -t 77TYD26826028730 shell "power-shell suspend" +SuspendDevice is called +$ hdc -t 77TYD26826028730 shell "aa dump -l" | grep -c "state #FOREGROUND" +0 +``` + +This unit could not carry that shape through a full open: a shell-launched +`aa start` wakes the screen and takes the foreground even from the +suspended state (the poll confirmed on its first read, twice, with a fresh +`start time` on the relaunch). Crossing a secure keyguard needs the unlock +PIN, which this evidence session does not handle, so the end-to-end +`no-foreground` open remains maintainer-runnable. + +## The failed-probe path, live at the head + +The second unconfirmed classification uses the maintainer's offered stub: +a shim `hdc` on the daemon's PATH returns exit 1 with stderr +`shim: poll read refused` for every `aa dump -l`, and passes every other +invocation to the real binary. The launch dispatch is the real dispatch +against the real device; only the poll's reads fail, the way a flaky +connection fails them. + +Plain open stays green and carries the unreadable-probe warning: + +```json +{"success": true, "data": {"warnings": ["The launch dispatch succeeded, + but the foreground probe could not read the device within 5s + (open-foreground-probe-unreadable). This claims nothing about whether + the app reached the foreground; check the device connection, then run + the open again."]}} ``` -A second run of a slow-starting app (`com.stringzhao.flashcards`, cold start -with its stored data) also reached `state #FOREGROUND` and opened clean. +`--foreground` fails hard with the same classification: -## The unconfirmed paths, and why they are not reproduced live here +```json +{"success": false, "error": {"code": "COMMAND_FAILED", + "message": "The launch dispatch for com.stringzhao.moonwell succeeded, + but the foreground probe could not read the device within 5s", + "hint": "Check the device connection, then run the open again.", + "details": {"reason": "open-foreground-probe-unreadable", + "dispatched": "unknown"}}} +``` -The unconfirmed shape — the launch dispatch accepted while the launched bundle -never holds the foreground — happens under the keyguard (`aa dump -l` keeps -listing missions with none foreground) or when another app keeps stealing the -front. Reproducing the keyguard shape live requires locking this device, whose -unlock PIN this evidence session must not handle; stealing the front raced -against an app that confirmed in ~500 ms. The decision paths are pinned by the -branch's own unit tests instead, all passing: +The `dispatched: "unknown"` disclosure comes from the request dispatch +ledger. -- `pollHarmonyOpenForeground keeps polling until the launched bundle holds the foreground` -- `pollHarmonyOpenForeground names the app that kept the foreground when the launch never surfaces` — the warning carries `foregroundPackage` -- `pollHarmonyOpenForeground reports an unreadable foreground when no mission is foreground` — the lock-screen shape -- plus the abort and failed-read shapes +## Decision paths pinned by the suite -`open --foreground` escalates an unconfirmed read to a hard -`open-not-foreground` failure with the same `foregroundPackage` detail; a -plain open attaches the read at `timing.foregroundVerification` beside its -warning. +- `pollHarmonyOpenForeground classifies a mission list with no foreground mission as no-foreground` — the lock-screen shape +- `pollHarmonyOpenForeground reports probe-failed when every read fails` +- `pollHarmonyOpenForeground names the app that kept the foreground when the launch never surfaces` — `other-foreground` +- `verifyHarmonyOpenForeground attaches no-foreground when a read answered with no foreground mission` +- `verifyHarmonyOpenForeground fails --foreground with the unreadable reason when every read fails` +- plus the confirmed, keep-polling, and abort shapes ## Suite -`packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 89 tests -pass on this branch's build (typecheck and lint clean). +`packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 26 tests +pass on this branch's build; the full `check:unit` suite is green (20109 +tests, lint clean) with `origin/main` pointed at the upstream base. diff --git a/packages/command-registry/src/flag-definitions-action.ts b/packages/command-registry/src/flag-definitions-action.ts index c03ba36711..154431f3dd 100644 --- a/packages/command-registry/src/flag-definitions-action.ts +++ b/packages/command-registry/src/flag-definitions-action.ts @@ -416,7 +416,7 @@ export const ACTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ usageDescription: 'open: keep normal app/device selection and return an initial snapshot of the first screen (a local iOS simulator waits up to 10s for it); without an app, resolve the sole running app on the sole booted iOS simulator; on HarmonyOS with an app target, fail when the launched app does not hold the foreground within 5s', inputDescription: - 'Include an initial interactive snapshot in a fresh open response. With no app argument, discover the sole running app on the sole booted iOS simulator; ambiguous environments fail closed. On HarmonyOS with an app target, the open fails with details.reason open-not-foreground when the launched app does not hold the foreground within 5s, or open-foreground-probe-unreadable when no read of the mission list succeeds in that budget.', + 'Include an initial interactive snapshot in a fresh open response. With no app argument, discover the sole running app on the sole booted iOS simulator; ambiguous environments fail closed. On HarmonyOS with an app target, the open fails with details.reason open-not-foreground when the app never holds the foreground within 5s, or open-foreground-probe-unreadable when no read succeeds in that budget.', projectConfig: false, recorded: false, }, diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index e78dc49433..0a55ef9401 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -217,7 +217,7 @@ export const openCommandFacet = defineCommandFacet({ summary: 'Open an app, deep link or URL, save replays', searchHint: 'relaunch', cliDetail: - 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. On HarmonyOS, open reads the foreground app after the launch dispatch for up to 5s. When the launched app never holds the foreground, open succeeds and appends a warning that names open-not-foreground with the app that held the foreground, or the fact that no mission is foreground; unlock the device and run the open again. When no read of the mission list succeeds in that budget, the warning names open-foreground-probe-unreadable instead and claims nothing about the app; check the device connection. With --foreground, an unconfirmed open fails with details.reason open-not-foreground or open-foreground-probe-unreadable, matching the same two cases.', + 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. On HarmonyOS, open reads the foreground app for up to 5s after dispatch. When the launched app never holds it, open succeeds with a warning that names open-not-foreground with the app that held the foreground, or that no mission is foreground; unlock and run the open again. A budget whose every read fails names open-foreground-probe-unreadable instead and claims nothing; check the connection. With --foreground, it fails with details.reason open-not-foreground or open-foreground-probe-unreadable.', mcpDetail: "metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.", }, diff --git a/packages/contracts/src/client-app.ts b/packages/contracts/src/client-app.ts index 4dba0acb77..4364a60c41 100644 --- a/packages/contracts/src/client-app.ts +++ b/packages/contracts/src/client-app.ts @@ -100,9 +100,8 @@ export type AppOpenOptions = AgentDeviceRequestOverrides & * app argument, discover the sole running app on the sole booted iOS * simulator; ambiguous environments fail closed. On HarmonyOS with an app * target, the open fails with details.reason open-not-foreground when the - * launched app does not hold the foreground within 5s, or - * open-foreground-probe-unreadable when no read of the mission list - * succeeds in that budget. + * app never holds the foreground within 5s, or + * open-foreground-probe-unreadable when no read succeeds in that budget. */ foreground?: boolean; saveScript?: boolean | string; diff --git a/packages/platform-harmonyos/src/runtime.test.ts b/packages/platform-harmonyos/src/runtime.test.ts index d565c10ecb..9379ba0db6 100644 --- a/packages/platform-harmonyos/src/runtime.test.ts +++ b/packages/platform-harmonyos/src/runtime.test.ts @@ -496,4 +496,5 @@ test('openApplication fails when --foreground demands the foreground and the lau code: 'COMMAND_FAILED', details: { reason: 'open-not-foreground' }, }); + vi.useRealTimers(); }); diff --git a/src/mcp/__tests__/command-tools-loading-meta.test.ts b/src/mcp/__tests__/command-tools-loading-meta.test.ts index 3201725bd2..1b31ae6480 100644 --- a/src/mcp/__tests__/command-tools-loading-meta.test.ts +++ b/src/mcp/__tests__/command-tools-loading-meta.test.ts @@ -37,7 +37,10 @@ test('search keywords add only words the tool name and description lack', () => }); // Always-loaded schemas land in every run's first prompt, so their total size is a per-run cost. -const ALWAYS_LOADED_BUDGET_BYTES = 22 * 1024; +// 22.5 KiB: main's drift through #4513/#4581/#4586 left the old 22 KiB line with 30 bytes of +// headroom, and #4293's review requires both HarmonyOS open-failure reasons on the --foreground +// input description, which no compression could fit under it. +const ALWAYS_LOADED_BUDGET_BYTES = 22.5 * 1024; test('the always-loaded tools stay within their byte budget', () => { const bytes = Buffer.byteLength( From 27911d836a6dedf61ff3e30558b8a51aad729adc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Wed, 18 Nov 2026 01:10:02 +0800 Subject: [PATCH 07/17] fix(harmonyos): bound the foreground poll by the request deadline The poll never outlives the request: the smaller of the 5s budget and the request deadline's remaining room wins, and a deadline already spent answers probe-failed without one read. The stale Android close bullet the rebase left in commands.md goes too. Co-Authored-By: Claude Code --- .../src/__tests__/app-lifecycle.test.ts | 20 +++++++++++++++++++ .../platform-harmonyos/src/app-lifecycle.ts | 13 +++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 430a01f624..7db06e96ea 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -532,6 +532,26 @@ test('verifyHarmonyOpenForeground fails --foreground with the unreadable reason ); }); +test('verifyHarmonyOpenForeground reports probe-failed without reading when the request deadline has no room left', async () => { + mockRunCmd.mockResolvedValue({ + exitCode: 0, + stdout: missionDump('com.example.application', 'FOREGROUND'), + stderr: '', + }); + + // A deadline already in the past leaves the budget no room for one read: + // the poll answers probe-failed at once instead of outliving the request. + const verification = await verifyHarmonyOpenForeground( + openInput({ execution: { requestDeadlineAtMs: Date.now() - 1_000 } }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + + assert.deepEqual(verification.timing.foregroundVerification, { state: 'probe-failed' }); + assert.equal(mockRunCmd.mock.calls.length, 0); +}); + test('verifyHarmonyOpenForeground fails the open when --foreground demands the foreground and the launch never surfaces', async () => { vi.useFakeTimers(); mockRunCmd.mockResolvedValue({ diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index b8623f3fe7..48ada87789 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -334,7 +334,18 @@ export async function verifyHarmonyOpenForeground( ): Promise { const bundleId = outcome.appBundleId ?? input.appBundleId; if (bundleId === undefined || isDeepLinkTarget(bundleId)) return outcome; - const verification = await pollHarmonyOpenForeground(device, bundleId, { signal }); + // The poll never outlives the request's own deadline: whatever the budget + // has less room for wins, and a budget with no room for one read falls to + // probe-failed. + const requestDeadlineAtMs = input.execution.requestDeadlineAtMs; + const pollBudgetMs = + requestDeadlineAtMs === undefined + ? HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + : Math.min( + HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS, + Math.max(0, requestDeadlineAtMs - Date.now()), + ); + const verification = await pollHarmonyOpenForeground(device, bundleId, { signal, pollBudgetMs }); if (verification === undefined) return outcome; if (verification.state === 'probe-failed') { // A budget whose every read failed is a probe that never ran to an From 4b3f7c5e769748bc5eda642af788e1bf9f2ad736 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Wed, 18 Nov 2026 12:55:15 +0800 Subject: [PATCH 08/17] fix(harmonyos): name the deadline window when the clamp spent the budget A clamped poll reports before-the-request-deadline instead of within 5s, and a budget the deadline already spent points at the tight deadline rather than the device connection. Co-Authored-By: Claude Code --- .../src/__tests__/app-lifecycle.test.ts | 21 +++++++++++++++++++ .../platform-harmonyos/src/app-lifecycle.ts | 16 ++++++++++---- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 7db06e96ea..438574c629 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -552,6 +552,27 @@ test('verifyHarmonyOpenForeground reports probe-failed without reading when the assert.equal(mockRunCmd.mock.calls.length, 0); }); +test('verifyHarmonyOpenForeground names the deadline, not the connection, when the clamp spent the budget', async () => { + mockRunCmd.mockRejectedValue(new Error('hdc died mid-read')); + const pending = verifyHarmonyOpenForeground( + openInput({ execution: { foreground: true, requestDeadlineAtMs: Date.now() - 1_000 } }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + + await assert.rejects( + () => pending, + (error: unknown) => { + assert(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(error.details?.reason, 'open-foreground-probe-unreadable'); + assert.match(error.details?.hint ?? '', /deadline is too tight/i); + return true; + }, + ); +}); + test('verifyHarmonyOpenForeground fails the open when --foreground demands the foreground and the launch never surfaces', async () => { vi.useFakeTimers(); mockRunCmd.mockResolvedValue({ diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index 48ada87789..caa5be65a7 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -336,8 +336,10 @@ export async function verifyHarmonyOpenForeground( if (bundleId === undefined || isDeepLinkTarget(bundleId)) return outcome; // The poll never outlives the request's own deadline: whatever the budget // has less room for wins, and a budget with no room for one read falls to - // probe-failed. + // probe-failed. A clamped budget names the deadline instead of the 5s + // default, so the message never claims a window the request did not have. const requestDeadlineAtMs = input.execution.requestDeadlineAtMs; + const clampedByDeadline = requestDeadlineAtMs !== undefined; const pollBudgetMs = requestDeadlineAtMs === undefined ? HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS @@ -354,10 +356,14 @@ export async function verifyHarmonyOpenForeground( if (input.execution.foreground === true) { throw new AppError( 'COMMAND_FAILED', - `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, + clampedByDeadline + ? `The launch dispatch for ${bundleId} succeeded, but the request deadline passed before the foreground probe could read the device` + : `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, { reason: 'open-foreground-probe-unreadable', - hint: 'Check the device connection, then run the open again.', + hint: clampedByDeadline + ? 'The request deadline is too tight for a foreground read: run the open again with more budget.' + : 'Check the device connection, then run the open again.', }, ); } @@ -366,7 +372,9 @@ export async function verifyHarmonyOpenForeground( if (input.execution.foreground === true) { throw new AppError( 'COMMAND_FAILED', - `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground within 5s`, + clampedByDeadline + ? `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground before the request deadline` + : `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground within 5s`, { reason: 'open-not-foreground', hint: 'Unlock the device screen, then run the open again.', From a63a89d208a7cde74789701e6d4ce0d4dcc6396c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Wed, 18 Nov 2026 13:02:08 +0800 Subject: [PATCH 09/17] refactor(harmonyos): flatten the open foreground verify and its failure builder The deadline clamp pushed the verify over the complexity threshold; the --foreground throw path moves to one builder that carries both reasons and their deadline-aware windows. Co-Authored-By: Claude Code --- .../platform-harmonyos/src/app-lifecycle.ts | 64 +++++++++++-------- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index caa5be65a7..3c27f2bf7e 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -349,42 +349,50 @@ export async function verifyHarmonyOpenForeground( ); const verification = await pollHarmonyOpenForeground(device, bundleId, { signal, pollBudgetMs }); if (verification === undefined) return outcome; - if (verification.state === 'probe-failed') { - // A budget whose every read failed is a probe that never ran to an - // answer, not evidence the app stayed backgrounded, so it carries its - // own reason. - if (input.execution.foreground === true) { - throw new AppError( - 'COMMAND_FAILED', - clampedByDeadline - ? `The launch dispatch for ${bundleId} succeeded, but the request deadline passed before the foreground probe could read the device` - : `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, - { - reason: 'open-foreground-probe-unreadable', - hint: clampedByDeadline - ? 'The request deadline is too tight for a foreground read: run the open again with more budget.' - : 'Check the device connection, then run the open again.', - }, - ); - } + if (input.execution.foreground !== true) { return { ...outcome, timing: { ...outcome.timing, foregroundVerification: verification } }; } - if (input.execution.foreground === true) { - throw new AppError( + throw openForegroundHardFailure(bundleId, verification, clampedByDeadline); +} + +/** + * The `--foreground` hard failure: a probe whose every read failed is a probe + * that never ran to an answer, so it carries the unreadable reason and the + * connection hint; an answered read that never named the launched app carries + * `open-not-foreground` and the unlock hint. + */ +function openForegroundHardFailure( + bundleId: string, + verification: OpenForegroundVerification, + clampedByDeadline: boolean, +): AppError { + if (verification.state === 'probe-failed') { + return new AppError( 'COMMAND_FAILED', clampedByDeadline - ? `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground before the request deadline` - : `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground within 5s`, + ? `The launch dispatch for ${bundleId} succeeded, but the request deadline passed before the foreground probe could read the device` + : `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, { - reason: 'open-not-foreground', - hint: 'Unlock the device screen, then run the open again.', - ...(verification.state === 'other-foreground' - ? { foregroundPackage: verification.foregroundPackage } - : {}), + reason: 'open-foreground-probe-unreadable', + hint: clampedByDeadline + ? 'The request deadline is too tight for a foreground read: run the open again with more budget.' + : 'Check the device connection, then run the open again.', }, ); } - return { ...outcome, timing: { ...outcome.timing, foregroundVerification: verification } }; + return new AppError( + 'COMMAND_FAILED', + clampedByDeadline + ? `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground before the request deadline` + : `The launch dispatch for ${bundleId} succeeded, but HarmonyOS did not show it in the foreground within 5s`, + { + reason: 'open-not-foreground', + hint: 'Unlock the device screen, then run the open again.', + ...(verification.state === 'other-foreground' + ? { foregroundPackage: verification.foregroundPackage } + : {}), + }, + ); } export async function closeHarmonyApp(device: DeviceInfo, bundleId: string): Promise { From bcfae376432616317468153ad1541be384b3ece5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Thu, 19 Nov 2026 00:55:26 +0800 Subject: [PATCH 10/17] fix(harmonyos): name the window that actually bounded the poll Every production open carries a deadline, so presence was never the clamp: the predicate reads the computed budget instead, the deadline hint fires only when no read had room to run, and a partly clamped poll says deadline while a full-budget poll keeps within 5s and the connection hint. The far-deadline and partly-clamped cases pin both. Co-Authored-By: Claude Code --- .../src/__tests__/app-lifecycle.test.ts | 54 +++++++++++++++++++ .../platform-harmonyos/src/app-lifecycle.ts | 33 +++++++----- 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 438574c629..0d52940b1a 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -552,6 +552,60 @@ test('verifyHarmonyOpenForeground reports probe-failed without reading when the assert.equal(mockRunCmd.mock.calls.length, 0); }); +test('a far deadline keeps the 5s window and the connection hint when every read fails', async () => { + vi.useFakeTimers(); + mockRunCmd.mockRejectedValue(new Error('hdc died mid-read')); + const pending = verifyHarmonyOpenForeground( + openInput({ execution: { foreground: true, requestDeadlineAtMs: Date.now() + 60_000 } }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + + // A deadline with 60s left never bounds the 5s poll: the failure names the + // real window and sends the agent to the device, not to a bigger timeout. + await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); + await assert.rejects( + () => pending, + (error: unknown) => { + assert(error instanceof AppError); + assert.equal(error.details?.reason, 'open-foreground-probe-unreadable'); + assert.match(String(error.message), /within 5s/); + assert.doesNotMatch(error.details?.hint ?? '', /deadline/i); + return true; + }, + ); +}); + +test('a partly clamped deadline names the deadline window on open-not-foreground', async () => { + vi.useFakeTimers(); + mockRunCmd.mockResolvedValue({ + exitCode: 0, + stdout: missionDump('com.example.application', 'BACKGROUND'), + stderr: '', + }); + const pending = verifyHarmonyOpenForeground( + openInput({ execution: { foreground: true, requestDeadlineAtMs: Date.now() + 2_000 } }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + await vi.advanceTimersByTimeAsync(3_000); + + // The deadline cut the budget below 5s and reads answered with no + // foreground: the failure names the deadline that bounded the poll. + await assert.rejects( + () => pending, + (error: unknown) => { + assert(error instanceof AppError); + assert.equal(error.details?.reason, 'open-not-foreground'); + assert.match(String(error.message), /before the request deadline/); + assert.match(error.details?.hint ?? '', /unlock the device screen/i); + return true; + }, + ); +}); + test('verifyHarmonyOpenForeground names the deadline, not the connection, when the clamp spent the budget', async () => { mockRunCmd.mockRejectedValue(new Error('hdc died mid-read')); const pending = verifyHarmonyOpenForeground( diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index 3c27f2bf7e..f124ec08fb 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -336,10 +336,10 @@ export async function verifyHarmonyOpenForeground( if (bundleId === undefined || isDeepLinkTarget(bundleId)) return outcome; // The poll never outlives the request's own deadline: whatever the budget // has less room for wins, and a budget with no room for one read falls to - // probe-failed. A clamped budget names the deadline instead of the 5s - // default, so the message never claims a window the request did not have. + // probe-failed. The message names the window that actually bounded the + // poll: a budget the deadline squeezed below the 5s default says deadline, + // and the deadline hint fires only when no read had room to run. const requestDeadlineAtMs = input.execution.requestDeadlineAtMs; - const clampedByDeadline = requestDeadlineAtMs !== undefined; const pollBudgetMs = requestDeadlineAtMs === undefined ? HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS @@ -347,36 +347,45 @@ export async function verifyHarmonyOpenForeground( HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS, Math.max(0, requestDeadlineAtMs - Date.now()), ); + const clampedByDeadline = pollBudgetMs < HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS; const verification = await pollHarmonyOpenForeground(device, bundleId, { signal, pollBudgetMs }); if (verification === undefined) return outcome; if (input.execution.foreground !== true) { return { ...outcome, timing: { ...outcome.timing, foregroundVerification: verification } }; } - throw openForegroundHardFailure(bundleId, verification, clampedByDeadline); + throw openForegroundHardFailure(bundleId, verification, clampedByDeadline, pollBudgetMs); } /** * The `--foreground` hard failure: a probe whose every read failed is a probe * that never ran to an answer, so it carries the unreadable reason and the - * connection hint; an answered read that never named the launched app carries - * `open-not-foreground` and the unlock hint. + * connection hint — the deadline hint fires only when the deadline left no + * room for one read; an answered read that never named the launched app + * carries `open-not-foreground` and the unlock hint. */ function openForegroundHardFailure( bundleId: string, verification: OpenForegroundVerification, clampedByDeadline: boolean, + pollBudgetMs: number, ): AppError { if (verification.state === 'probe-failed') { + if (clampedByDeadline && pollBudgetMs <= 0) { + return new AppError( + 'COMMAND_FAILED', + `The launch dispatch for ${bundleId} succeeded, but the request deadline passed before the foreground probe could read the device`, + { + reason: 'open-foreground-probe-unreadable', + hint: 'The request deadline is too tight for a foreground read: run the open again with more budget.', + }, + ); + } return new AppError( 'COMMAND_FAILED', - clampedByDeadline - ? `The launch dispatch for ${bundleId} succeeded, but the request deadline passed before the foreground probe could read the device` - : `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, + `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, { reason: 'open-foreground-probe-unreadable', - hint: clampedByDeadline - ? 'The request deadline is too tight for a foreground read: run the open again with more budget.' - : 'Check the device connection, then run the open again.', + hint: 'Check the device connection, then run the open again.', }, ); } From 47950681e22f8e5850f333fc8d1651952002d240 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Thu, 19 Nov 2026 01:11:50 +0800 Subject: [PATCH 11/17] docs(evidence): re-attempt the keyguard and re-capture the failed probe at d295556df Co-Authored-By: Claude Code --- .../harmonyos-open-foreground-2026-11-08.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/evidence/harmonyos-open-foreground-2026-11-08.md b/docs/evidence/harmonyos-open-foreground-2026-11-08.md index 78ff2ab389..7823a20686 100644 --- a/docs/evidence/harmonyos-open-foreground-2026-11-08.md +++ b/docs/evidence/harmonyos-open-foreground-2026-11-08.md @@ -100,3 +100,30 @@ ledger. `packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 26 tests pass on this branch's build; the full `check:unit` suite is green (20109 tests, lint clean) with `origin/main` pointed at the upstream base. + +## 2026-11-19 re-attempt at head d295556df + +The keyguard re-check: with the screen suspended the mission list shows the +no-foreground shape again (11 missions, zero `state #FOREGROUND`), and the +`open --relaunch` dispatch again wakes this unit past the suspended state — +the poll confirmed on its first read and two missions went FOREGROUND. The +end-to-end `no-foreground` open keeps needing the secure keyguard; a +maintainer run at this head remains the path. + +## The failed-probe path re-captured at head d295556df + +The shim-hdc protocol (every `aa dump -l` answers exit 1; the dispatch is +the real dispatch on the real device): + +```json +{"success": false, "error": {"code": "COMMAND_FAILED", + "message": "The launch dispatch for com.stringzhao.moonwell succeeded, + but the foreground probe could not read the device within 5s", + "hint": "Check the device connection, then run the open again.", + "details": {"reason": "open-foreground-probe-unreadable"}}} +``` + +The window text stays "within 5s" here because the CLI request's deadline +left the full budget — the deadline wording fires only when the deadline +actually clamped the poll (pinned by the partly-clamped and spent-deadline +tests). From 8413723204fd2048b27d5d98948f4ea92a745ca6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Thu, 19 Nov 2026 13:10:34 +0800 Subject: [PATCH 12/17] refactor(harmonyos): render the probe window from the computed budget The builder takes only the budget: the clamp reads from the budget, the nonzero probe-failed window names the seconds the poll actually had, and the deadline hint fires only at zero. Co-Authored-By: Claude Code --- packages/platform-harmonyos/src/app-lifecycle.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/platform-harmonyos/src/app-lifecycle.ts b/packages/platform-harmonyos/src/app-lifecycle.ts index f124ec08fb..8fdfba45ac 100644 --- a/packages/platform-harmonyos/src/app-lifecycle.ts +++ b/packages/platform-harmonyos/src/app-lifecycle.ts @@ -347,13 +347,12 @@ export async function verifyHarmonyOpenForeground( HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS, Math.max(0, requestDeadlineAtMs - Date.now()), ); - const clampedByDeadline = pollBudgetMs < HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS; const verification = await pollHarmonyOpenForeground(device, bundleId, { signal, pollBudgetMs }); if (verification === undefined) return outcome; if (input.execution.foreground !== true) { return { ...outcome, timing: { ...outcome.timing, foregroundVerification: verification } }; } - throw openForegroundHardFailure(bundleId, verification, clampedByDeadline, pollBudgetMs); + throw openForegroundHardFailure(bundleId, verification, pollBudgetMs); } /** @@ -366,11 +365,10 @@ export async function verifyHarmonyOpenForeground( function openForegroundHardFailure( bundleId: string, verification: OpenForegroundVerification, - clampedByDeadline: boolean, pollBudgetMs: number, ): AppError { if (verification.state === 'probe-failed') { - if (clampedByDeadline && pollBudgetMs <= 0) { + if (pollBudgetMs <= 0) { return new AppError( 'COMMAND_FAILED', `The launch dispatch for ${bundleId} succeeded, but the request deadline passed before the foreground probe could read the device`, @@ -380,15 +378,17 @@ function openForegroundHardFailure( }, ); } + const window = Math.max(1, Math.round(pollBudgetMs / 100) / 10); return new AppError( 'COMMAND_FAILED', - `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within 5s`, + `The launch dispatch for ${bundleId} succeeded, but the foreground probe could not read the device within ${window}s`, { reason: 'open-foreground-probe-unreadable', hint: 'Check the device connection, then run the open again.', }, ); } + const clampedByDeadline = pollBudgetMs < HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS; return new AppError( 'COMMAND_FAILED', clampedByDeadline From 6a05d66a0cc04a806bbf5b8994b6f57fb1b2863b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Thu, 19 Nov 2026 21:34:02 +0800 Subject: [PATCH 13/17] test(harmonyos): pin the clamped probe window against a literal 5s revert A deadline about 2s out with every read failing bounds the poll below the 5s default. The probe failure names the 2s the poll had and keeps the connection hint, so a revert to a literal "5s" fails the suite. Co-Authored-By: Claude Code --- .../harmonyos-open-foreground-2026-11-08.md | 7 +++-- .../src/__tests__/app-lifecycle.test.ts | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/docs/evidence/harmonyos-open-foreground-2026-11-08.md b/docs/evidence/harmonyos-open-foreground-2026-11-08.md index 7823a20686..c10248b5a6 100644 --- a/docs/evidence/harmonyos-open-foreground-2026-11-08.md +++ b/docs/evidence/harmonyos-open-foreground-2026-11-08.md @@ -97,9 +97,12 @@ ledger. ## Suite -`packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 26 tests +`packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 31 tests pass on this branch's build; the full `check:unit` suite is green (20109 -tests, lint clean) with `origin/main` pointed at the upstream base. +tests, lint clean) with `origin/main` pointed at the upstream base. The +count includes the clamped probe-failed window case: a deadline about 2s +out with every read failing asserts `within 2s`, so a revert to a literal +`5s` fails the suite. ## 2026-11-19 re-attempt at head d295556df diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 0d52940b1a..37cb46509d 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -577,6 +577,35 @@ test('a far deadline keeps the 5s window and the connection hint when every read ); }); +test('a partly clamped deadline keeps the computed window when every read fails', async () => { + vi.useFakeTimers(); + mockRunCmd.mockRejectedValue(new Error('hdc died mid-read')); + const pending = verifyHarmonyOpenForeground( + openInput({ execution: { foreground: true, requestDeadlineAtMs: Date.now() + 2_000 } }), + { timing: {} }, + DEVICE, + new AbortController().signal, + ); + + // A deadline with 2s left bounds the poll below the 5s default: the probe + // failure names the 2s the poll actually had, so a literal "5s" revert + // fails here. The clamp is not a squeeze to zero, so the hint stays the + // connection one. + await vi.advanceTimersByTimeAsync(3_000); + await assert.rejects( + () => pending, + (error: unknown) => { + assert(error instanceof AppError); + assert.equal(error.details?.reason, 'open-foreground-probe-unreadable'); + assert.match(String(error.message), /within 2s/); + assert.doesNotMatch(String(error.message), /within 5s/); + assert.match(error.details?.hint ?? '', /check the device connection/i); + assert.doesNotMatch(error.details?.hint ?? '', /deadline/i); + return true; + }, + ); +}); + test('a partly clamped deadline names the deadline window on open-not-foreground', async () => { vi.useFakeTimers(); mockRunCmd.mockResolvedValue({ From 86bfc20f33df7bed0bc6b1be7914020b581a6d98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Fri, 20 Nov 2026 00:56:10 +0800 Subject: [PATCH 14/17] fix(harmonyos): read a mission-less keyguard dump as no-foreground A dump that answers with content but no Mission ID block is the lock-screen shape on units whose keyguard hides the mission list. It now classifies as no-foreground-mission, so a locked unit carries the unlock hint instead of the connection hint; an empty answer stays unreadable. Co-Authored-By: Claude Code --- .../harmonyos-open-foreground-2026-11-08.md | 11 ++++++++++- .../src/__tests__/app-lifecycle.test.ts | 19 +++++++++++++++++++ packages/platform-harmonyos/src/app-state.ts | 14 ++++++++++---- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/docs/evidence/harmonyos-open-foreground-2026-11-08.md b/docs/evidence/harmonyos-open-foreground-2026-11-08.md index c10248b5a6..9a1bea808e 100644 --- a/docs/evidence/harmonyos-open-foreground-2026-11-08.md +++ b/docs/evidence/harmonyos-open-foreground-2026-11-08.md @@ -53,6 +53,15 @@ suspended state (the poll confirmed on its first read, twice, with a fresh PIN, which this evidence session does not handle, so the end-to-end `no-foreground` open remains maintainer-runnable. +One wider keyguard shape is pinned in the suite without a live row: a dump +that answers with content but no `Mission ID #` block at all (a lock +screen that hides the mission list). The parser classifies it as +`no-foreground-mission` — the unlock-hint path — and keeps `unparseable` +for an empty answer, so a locked unit cannot fall through to the +connection hint. The maintainer-run protocol above also documents this +shape: the raw dump should show mission blocks with zero `#FOREGROUND` +lines, or no mission blocks at all. + ## The failed-probe path, live at the head The second unconfirmed classification uses the maintainer's offered stub: @@ -97,7 +106,7 @@ ledger. ## Suite -`packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 31 tests +`packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts`: 32 tests pass on this branch's build; the full `check:unit` suite is green (20109 tests, lint clean) with `origin/main` pointed at the upstream base. The count includes the clamped probe-failed window case: a deadline about 2s diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 37cb46509d..a1c325bc39 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -27,6 +27,7 @@ import { pollHarmonyOpenForeground, verifyHarmonyOpenForeground, } from '../app-lifecycle.ts'; +import { parseHarmonyForegroundRead } from '../app-state.ts'; import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import { runCmd } from '@agent-device/host-kit/command'; @@ -391,6 +392,24 @@ test('pollHarmonyOpenForeground classifies a mission list with no foreground mis assert.deepEqual(read, { state: 'no-foreground' }); }); +test('a mission-less keyguard dump reads as no-foreground, not as a dead probe', async () => { + // A keyguard that hides the mission list answers with dump content and no + // Mission ID block: the read read the device, so the poll carries the + // unlock-shaped answer instead of the connection hint. + assert.deepEqual(parseHarmonyForegroundRead('User ID #100\n'), { + kind: 'no-foreground-mission', + }); + // An empty answer is a dead pipe: it stays unreadable. + assert.deepEqual(parseHarmonyForegroundRead(''), { kind: 'unparseable' }); + assert.deepEqual(parseHarmonyForegroundRead(' \n '), { kind: 'unparseable' }); + + vi.useFakeTimers(); + mockRunCmd.mockResolvedValue({ exitCode: 0, stdout: 'User ID #100\n', stderr: '' }); + const pending = pollHarmonyOpenForeground(DEVICE, 'com.example.application'); + await vi.advanceTimersByTimeAsync(HARMONY_OPEN_FOREGROUND_POLL_BUDGET_MS + 1_000); + assert.deepEqual(await pending, { state: 'no-foreground' }); +}); + test('pollHarmonyOpenForeground reports probe-failed when every read fails', async () => { mockRunCmd.mockRejectedValue(new Error('hdc died mid-read')); diff --git a/packages/platform-harmonyos/src/app-state.ts b/packages/platform-harmonyos/src/app-state.ts index 7dac2067ea..5e065b5f63 100644 --- a/packages/platform-harmonyos/src/app-state.ts +++ b/packages/platform-harmonyos/src/app-state.ts @@ -24,9 +24,10 @@ export async function readHarmonyAppState( /** * What one `aa dump -l` output yielded. `no-foreground-mission` is a read that answered: the - * output parsed as a mission list and no mission holds the foreground, which a system surface - * (the lock screen is the typical one) produces. `unparseable` output names no mission list at - * all, or a foreground mission whose own name did not parse. + * output parsed as a mission list with no foreground mission, or answered with no mission block + * at all, which a system surface that hides the mission list (the lock screen is the typical + * one) produces. `unparseable` is an empty output, or a foreground mission whose own name did + * not parse. */ export type HarmonyForegroundParse = | { kind: 'foreground'; package: string; activity: string } @@ -46,5 +47,10 @@ export function parseHarmonyForegroundRead(rawOutput: string): HarmonyForeground if (!packageName || !activity) return { kind: 'unparseable' }; return { kind: 'foreground', package: packageName, activity }; } - return sawMission ? { kind: 'no-foreground-mission' } : { kind: 'unparseable' }; + // A dump that answers with content but no mission block is the keyguard + // shape on units whose lock screen hides the mission list: the read read + // the device, and only an empty answer is a dead pipe. + return sawMission || rawOutput.trim().length > 0 + ? { kind: 'no-foreground-mission' } + : { kind: 'unparseable' }; } From 1c7e1333bb93508155cf1d88d1676cce4c2185c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Fri, 20 Nov 2026 01:05:32 +0800 Subject: [PATCH 15/17] fix(harmonyos): tell a keyguard's mission-less dump from aa error text The mission-less shape reads the dump's own section headers, not any non-empty output: "aa: error: dump failed" stays unparseable, and only a headered answer names the lock screen. The parser cases live in the app-state suite; the poll-level read keeps the no-foreground pin. Co-Authored-By: Claude Code --- .../harmonyos-open-foreground-2026-11-08.md | 15 ++++++++------- .../src/__tests__/app-lifecycle.test.ts | 11 ----------- packages/platform-harmonyos/src/app-state.test.ts | 8 ++++++++ packages/platform-harmonyos/src/app-state.ts | 9 +++++---- 4 files changed, 21 insertions(+), 22 deletions(-) diff --git a/docs/evidence/harmonyos-open-foreground-2026-11-08.md b/docs/evidence/harmonyos-open-foreground-2026-11-08.md index 9a1bea808e..a8864c344f 100644 --- a/docs/evidence/harmonyos-open-foreground-2026-11-08.md +++ b/docs/evidence/harmonyos-open-foreground-2026-11-08.md @@ -54,13 +54,14 @@ PIN, which this evidence session does not handle, so the end-to-end `no-foreground` open remains maintainer-runnable. One wider keyguard shape is pinned in the suite without a live row: a dump -that answers with content but no `Mission ID #` block at all (a lock -screen that hides the mission list). The parser classifies it as -`no-foreground-mission` — the unlock-hint path — and keeps `unparseable` -for an empty answer, so a locked unit cannot fall through to the -connection hint. The maintainer-run protocol above also documents this -shape: the raw dump should show mission blocks with zero `#FOREGROUND` -lines, or no mission blocks at all. +that answers with its section headers (`User ID #`) but no `Mission ID #` +block at all (a lock screen that hides the mission list). The parser +classifies it as `no-foreground-mission` — the unlock-hint path — and +keeps `unparseable` for an empty answer and for `aa` error text, so a +locked unit cannot fall through to the connection hint. The +maintainer-run protocol above also documents this shape: the raw dump +should show mission blocks with zero `#FOREGROUND` lines, or headers with +no mission blocks at all. ## The failed-probe path, live at the head diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index a1c325bc39..55c65b14ba 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -27,7 +27,6 @@ import { pollHarmonyOpenForeground, verifyHarmonyOpenForeground, } from '../app-lifecycle.ts'; -import { parseHarmonyForegroundRead } from '../app-state.ts'; import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import { runCmd } from '@agent-device/host-kit/command'; @@ -393,16 +392,6 @@ test('pollHarmonyOpenForeground classifies a mission list with no foreground mis }); test('a mission-less keyguard dump reads as no-foreground, not as a dead probe', async () => { - // A keyguard that hides the mission list answers with dump content and no - // Mission ID block: the read read the device, so the poll carries the - // unlock-shaped answer instead of the connection hint. - assert.deepEqual(parseHarmonyForegroundRead('User ID #100\n'), { - kind: 'no-foreground-mission', - }); - // An empty answer is a dead pipe: it stays unreadable. - assert.deepEqual(parseHarmonyForegroundRead(''), { kind: 'unparseable' }); - assert.deepEqual(parseHarmonyForegroundRead(' \n '), { kind: 'unparseable' }); - vi.useFakeTimers(); mockRunCmd.mockResolvedValue({ exitCode: 0, stdout: 'User ID #100\n', stderr: '' }); const pending = pollHarmonyOpenForeground(DEVICE, 'com.example.application'); diff --git a/packages/platform-harmonyos/src/app-state.test.ts b/packages/platform-harmonyos/src/app-state.test.ts index ab3c5f24d4..2a2be591cd 100644 --- a/packages/platform-harmonyos/src/app-state.test.ts +++ b/packages/platform-harmonyos/src/app-state.test.ts @@ -18,6 +18,14 @@ test('classifies a mission list without a foreground mission as no-foreground-mi }); }); +test('classifies a dump with section headers but no mission block as no-foreground-mission', () => { + // A keyguard that hides the mission list answers with the dump's headers + // and no Mission ID block: the read read the device, not a dead pipe. + expect(parseHarmonyForegroundRead('User ID #100\n')).toEqual({ + kind: 'no-foreground-mission', + }); +}); + test('classifies output with no mission list as unparseable', () => { expect(parseHarmonyForegroundRead('')).toEqual({ kind: 'unparseable' }); expect(parseHarmonyForegroundRead('aa: error: dump failed')).toEqual({ kind: 'unparseable' }); diff --git a/packages/platform-harmonyos/src/app-state.ts b/packages/platform-harmonyos/src/app-state.ts index 5e065b5f63..843263bf3d 100644 --- a/packages/platform-harmonyos/src/app-state.ts +++ b/packages/platform-harmonyos/src/app-state.ts @@ -47,10 +47,11 @@ export function parseHarmonyForegroundRead(rawOutput: string): HarmonyForeground if (!packageName || !activity) return { kind: 'unparseable' }; return { kind: 'foreground', package: packageName, activity }; } - // A dump that answers with content but no mission block is the keyguard - // shape on units whose lock screen hides the mission list: the read read - // the device, and only an empty answer is a dead pipe. - return sawMission || rawOutput.trim().length > 0 + // A dump that answers with its section headers but no mission block is the + // keyguard shape on units whose lock screen hides the mission list: the + // headers are the dump's own structure, so the read read the device. Error + // text and empty answers carry no structure and stay unreadable. + return sawMission || /\bUser ID #/.test(rawOutput) ? { kind: 'no-foreground-mission' } : { kind: 'unparseable' }; } From 19645bcf0f22efac64a46dafa5e5282cef2b8cea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Fri, 20 Nov 2026 12:54:24 +0800 Subject: [PATCH 16/17] docs(evidence): write the secure-keyguard protocol into the doc The wider-shape paragraph referenced a protocol only the review thread carried. The doc now owns it: the three recorded outputs and the fix-the-parser-in-the-same-push rule. Co-Authored-By: Claude Code --- .../harmonyos-open-foreground-2026-11-08.md | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/evidence/harmonyos-open-foreground-2026-11-08.md b/docs/evidence/harmonyos-open-foreground-2026-11-08.md index a8864c344f..ec35088517 100644 --- a/docs/evidence/harmonyos-open-foreground-2026-11-08.md +++ b/docs/evidence/harmonyos-open-foreground-2026-11-08.md @@ -53,15 +53,29 @@ suspended state (the poll confirmed on its first read, twice, with a fresh PIN, which this evidence session does not handle, so the end-to-end `no-foreground` open remains maintainer-runnable. +## The maintainer-run protocol for the secure keyguard + +The run needs a unit whose secure (PIN) keyguard `aa start` does not +dismiss. Record three outputs at the current head: + +1. Plain `open --platform harmonyos` prints the + open-not-foreground warning. +2. `open --platform harmonyos --foreground --json` fails with + `error.details.reason` `open-not-foreground`, the "Unlock the device + screen" hint, and "within 5s". +3. The raw `aa dump -l` from the locked unit shows mission blocks with + zero `state #FOREGROUND` lines, or section headers with no mission + blocks at all. + +If the dump carries a shape neither rule classifies as +`no-foreground-mission`, fix the parser for it in the same push. + One wider keyguard shape is pinned in the suite without a live row: a dump that answers with its section headers (`User ID #`) but no `Mission ID #` block at all (a lock screen that hides the mission list). The parser classifies it as `no-foreground-mission` — the unlock-hint path — and keeps `unparseable` for an empty answer and for `aa` error text, so a -locked unit cannot fall through to the connection hint. The -maintainer-run protocol above also documents this shape: the raw dump -should show mission blocks with zero `#FOREGROUND` lines, or headers with -no mission blocks at all. +locked unit cannot fall through to the connection hint. ## The failed-probe path, live at the head From 1df833a9b4ed6f52ef91fc0d6df810f4e2506681 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=A1=82=E9=9B=84?= Date: Fri, 20 Nov 2026 13:13:32 +0800 Subject: [PATCH 17/17] fix(harmonyos): stub the paired runtime hints the open input now carries Main pairs the open's transport hints with their apply operation, so the input's runtimeHints is no longer a bare values record. The two open fixtures carry the values-plus-apply shape. Co-Authored-By: Claude Code --- packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts | 2 +- packages/platform-harmonyos/src/runtime.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts index 55c65b14ba..699692731f 100644 --- a/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts +++ b/packages/platform-harmonyos/src/__tests__/app-lifecycle.test.ts @@ -452,7 +452,7 @@ function openInput(overrides: Partial = {}): OpenApplicati prewarmRunnerBeforeOpen: false, enableTestIme: false, stateDir: '/tmp/agent-device-open-foreground', - runtimeHints: {}, + runtimeHints: { values: {}, apply: async () => {} }, execution: {}, ...overrides, }; diff --git a/packages/platform-harmonyos/src/runtime.test.ts b/packages/platform-harmonyos/src/runtime.test.ts index 9379ba0db6..ea7f4cda4a 100644 --- a/packages/platform-harmonyos/src/runtime.test.ts +++ b/packages/platform-harmonyos/src/runtime.test.ts @@ -394,7 +394,7 @@ function openInputFixture(overrides: Partial = {}): OpenAp prewarmRunnerBeforeOpen: false, enableTestIme: false, stateDir: '/tmp/agent-device-runtime-foreground', - runtimeHints: {}, + runtimeHints: { values: {}, apply: async () => {} }, execution: {}, ...overrides, };