diff --git a/packages/contracts/src/application-lifecycle-interaction.test.ts b/packages/contracts/src/application-lifecycle-interaction.test.ts index b0bb5b3c6d..131ae08c18 100644 --- a/packages/contracts/src/application-lifecycle-interaction.test.ts +++ b/packages/contracts/src/application-lifecycle-interaction.test.ts @@ -155,6 +155,134 @@ test('an owner whose open restarts the app receives the relaunch as terminateRun ]); }); +test('a foreground read naming the open target marks the outcome and still dispatches', async () => { + const calls: string[] = []; + const reads: string[] = []; + const lifecycle = bindLocalDirectApplicationLifecycle({ + owner: 'Linux', + openTargetIdentity: 'bundle-id', + host: { resolve: async () => lifecycleRecordingInteractor(calls) }, + device: LINUX_DEVICE, + signal: new AbortController().signal, + readForegroundBundle: async () => { + reads.push('com.example.app'); + return 'com.example.app'; + }, + }); + + const outcome = await lifecycle.openApplication(openInput()); + + expect(outcome).toMatchObject({ alreadyForeground: true }); + expect(reads).toEqual(['com.example.app']); + // The read only informs the caller: the dispatch keeps its idempotent semantics. + expect(calls).toEqual(['open com.example.app terminate=undefined']); +}); + +test('a foreground read naming another app claims nothing about the open', async () => { + const calls: string[] = []; + const lifecycle = bindLocalDirectApplicationLifecycle({ + owner: 'Linux', + openTargetIdentity: 'bundle-id', + host: { resolve: async () => lifecycleRecordingInteractor(calls) }, + device: LINUX_DEVICE, + signal: new AbortController().signal, + readForegroundBundle: async () => 'com.other.app', + }); + + const outcome = await lifecycle.openApplication(openInput()); + + expect(outcome.alreadyForeground).toBeUndefined(); + expect(calls).toEqual(['open com.example.app terminate=undefined']); +}); + +test('a failing foreground read does not fail the open', async () => { + const calls: string[] = []; + const lifecycle = bindLocalDirectApplicationLifecycle({ + owner: 'Linux', + openTargetIdentity: 'bundle-id', + host: { resolve: async () => lifecycleRecordingInteractor(calls) }, + device: LINUX_DEVICE, + signal: new AbortController().signal, + readForegroundBundle: async () => { + throw new Error('hdc read failed'); + }, + }); + + const outcome = await lifecycle.openApplication(openInput()); + + expect(outcome.alreadyForeground).toBeUndefined(); + expect(calls).toEqual(['open com.example.app terminate=undefined']); +}); + +test('a relaunch open does not consult the foreground read', async () => { + const calls: string[] = []; + let reads = 0; + const lifecycle = bindLocalDirectApplicationLifecycle({ + owner: 'Linux', + openTargetIdentity: 'bundle-id', + host: { resolve: async () => lifecycleRecordingInteractor(calls) }, + device: LINUX_DEVICE, + signal: new AbortController().signal, + readForegroundBundle: async () => { + reads += 1; + return 'com.example.app'; + }, + }); + + await lifecycle.openApplication(openInput({ relaunch: true })); + + expect(reads).toBe(0); + expect(calls).toEqual(['close com.example.app', 'open com.example.app terminate=undefined']); +}); + +test('a clear-app-state or --activity open does not consult the foreground read', async () => { + const calls: string[] = []; + let reads = 0; + const lifecycle = bindLocalDirectApplicationLifecycle({ + owner: 'Linux', + openTargetIdentity: 'bundle-id', + host: { resolve: async () => lifecycleRecordingInteractor(calls) }, + device: LINUX_DEVICE, + signal: new AbortController().signal, + readForegroundBundle: async () => { + reads += 1; + return 'com.example.app'; + }, + }); + + // Each open stops or replaces the running app, so a pre-dispatch read of the same bundle + // would claim a re-activation the open itself is about to end (#4860 review). + await lifecycle.openApplication(openInput({ execution: { clearAppState: true } })); + await lifecycle.openApplication(openInput({ execution: { activity: 'EntryAbility' } })); + + expect(reads).toBe(0); + expect(calls).toEqual([ + 'open com.example.app terminate=undefined', + 'open com.example.app terminate=undefined', + ]); +}); + +test('a URL pair open does not consult the foreground read', async () => { + let reads = 0; + const lifecycle = bindLocalDirectApplicationLifecycle({ + owner: 'Linux', + openTargetIdentity: 'bundle-id', + host: { resolve: async () => lifecycleRecordingInteractor([]) }, + device: LINUX_DEVICE, + signal: new AbortController().signal, + readForegroundBundle: async () => { + reads += 1; + return 'com.example.app'; + }, + }); + + await lifecycle.openApplication( + openInput({ positionals: ['com.example.app', 'example://home'] }), + ); + + expect(reads).toBe(0); +}); + test.each([ { name: 'more than two positionals', diff --git a/packages/contracts/src/application-lifecycle-interaction.ts b/packages/contracts/src/application-lifecycle-interaction.ts index ef1abca297..2e9beab6fd 100644 --- a/packages/contracts/src/application-lifecycle-interaction.ts +++ b/packages/contracts/src/application-lifecycle-interaction.ts @@ -274,6 +274,13 @@ export type DirectApplicationLifecycleParams = Readonly<{ * interactor's open receives `terminateRunningApp` and owns the restart. */ closeBeforeRelaunch: boolean; + /** + * Reads which bundle holds the foreground before the dispatch, or `undefined` when no read + * answers. Owners whose native launch of an already-foreground app is a passthrough wire their + * platform's read here, so the open can say that it re-activated instead of restarted. The read + * is advisory: its failure never fails the open it informs. + */ + readForegroundBundle?: (signal: AbortSignal) => Promise; /** Port reverse is the one non-direct operation a provider owner may still implement. */ configureProviderPortReverse?: ApplicationLifecycleRuntimeOperations['configureProviderPortReverse']; }>; @@ -318,6 +325,7 @@ async function openDirectApplication( ): Promise { const { binding } = params; const interactor = await binding.resolveInteractor(input.execution, input.appBundleId); + const alreadyForeground = await resolveAlreadyForeground(params, input); if (params.closeBeforeRelaunch && input.relaunch && input.target !== undefined) { await invokeApplicationClose({ device: binding.device, @@ -348,7 +356,44 @@ async function openDirectApplication( }, }); } - return { appBundleId: input.appBundleId, timing: {} }; + return { + appBundleId: input.appBundleId, + timing: {}, + ...(alreadyForeground ? { alreadyForeground: true as const } : {}), + }; +} + +/** The plain app target a foreground read can compare against, when the open has one. */ +function probeableOpenTarget(input: OpenApplicationInput): string | undefined { + // An open that stops or replaces the running app re-activates nothing: --clear-app-state + // force-stops and cleans first, and --activity can start a different ability than the one + // running, so the read has no same-app fact to compare (#4860 review). + if (input.execution.clearAppState || input.execution.activity) return undefined; + if (input.positionals.length !== 1) return undefined; + const target = input.positionals[0]; + return target !== undefined && !isDeepLinkTarget(target) ? target : undefined; +} + +/** + * Whether the open's app target already held the foreground, read before the dispatch through the + * owner's probe. Only a plain app target answers: a relaunch intends a restart, --clear-app-state + * and --activity can each replace the running app, and a URL pair or a deep link has no foreground + * fact to compare. A read that fails or names another app claims nothing, so it cannot fail the + * open. + */ +async function resolveAlreadyForeground( + params: DirectApplicationLifecycleParams, + input: OpenApplicationInput, +): Promise { + const { readForegroundBundle, binding } = params; + if (!readForegroundBundle || input.relaunch) return false; + const target = probeableOpenTarget(input); + if (!target) return false; + try { + return (await readForegroundBundle(binding.signal)) === target; + } catch { + return false; + } } export function followUpRuntimeLaunchUrl(input: OpenApplicationInput): string | undefined { @@ -405,6 +450,7 @@ export function bindLocalDirectApplicationLifecycle( host: Readonly<{ resolve: LocalApplicationLifecycleInteractorResolver }>; device: DeviceInfo; signal: AbortSignal; + readForegroundBundle?: DirectApplicationLifecycleParams['readForegroundBundle']; }>, ): ApplicationLifecycleRuntimeOperations { return bindDirectApplicationLifecycle({ @@ -412,6 +458,7 @@ export function bindLocalDirectApplicationLifecycle( openTargetIdentity: params.openTargetIdentity, // No local direct owner (Linux, web, HarmonyOS, Vega) replaces a running app on open. closeBeforeRelaunch: true, + readForegroundBundle: params.readForegroundBundle, binding: bindLocalApplicationLifecycleInteractor({ device: params.device, signal: params.signal, diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index b1e01d7e76..90c23b8e83 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -233,6 +233,13 @@ export type LaunchConfirmationAbsent = Readonly<{ type OpenApplicationOutcomeBase = Readonly<{ appBundleId?: string; + /** + * The app target already held the foreground when the open dispatched, so the platform's launch + * is a re-activation of the running app, not a restart. The open keeps its idempotent semantics; + * `open --relaunch` stays the caller's restart path. Present only when an owner read the + * foreground before its dispatch; an unreadable read claims nothing. + */ + alreadyForeground?: true; timing: OpenApplicationTiming; }>; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-already-foreground.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-already-foreground.test.ts new file mode 100644 index 0000000000..5b9a61642a --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-already-foreground.test.ts @@ -0,0 +1,136 @@ +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-already-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 reopenApp(params: { + sessionStore: SessionStore; + sessionName: string; + openOutcome: OpenApplicationOutcome; +}): Promise { + const bindDevice: Parameters[0]['bindDevice'] = async ( + device, + use, + ) => { + const binding = await mockBindDeviceRuntime(device, use); + return { + ...binding, + operations: { + ...binding.operations, + openApplication: async (_input: OpenApplicationInput) => 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['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 says the app was already foreground when the platform reports the passthrough', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + const data = requireOpenData( + await reopenApp({ + sessionStore, + sessionName: 'harmony-session', + openOutcome: { + appBundleId: 'com.example.application', + alreadyForeground: true, + timing: {}, + }, + }), + ); + + const warnings = (data.warnings as string[] | undefined) ?? []; + expect(warnings).toContain( + 'App was already foreground; open re-activated it without restarting. Use --relaunch to restart.', + ); +}); + +test('open adds no already-foreground note when the outcome carries no foreground fact', async () => { + const sessionStore = makeSessionStore(); + publishSession(sessionStore, 'harmony-session', HARMONY_DEVICE); + + const data = requireOpenData( + await reopenApp({ + sessionStore, + sessionName: 'harmony-session', + openOutcome: { appBundleId: 'com.example.application', timing: {} }, + }), + ); + + const warnings = (data.warnings as string[] | undefined) ?? []; + expect(warnings.some((warning) => warning.includes('already 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..4f3b07c05f 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 @@ -176,6 +176,11 @@ function launchConfirmationUnansweredWarning(reason: LaunchConfirmationUnanswere ); } +/** What the caller's `open` output says when the app already held the foreground at open time. */ +function alreadyForegroundWarning(): string { + return 'App was already foreground; open re-activated it without restarting. Use --relaunch to restart.'; +} + // 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 +392,9 @@ export async function completeOpenCommand(params: { if (outcome.launchConfirmation === undefined && outcome.launchConfirmationProbeFailure) { appendResponseWarning(openResult, launchConfirmationProbeFailureWarning()); } + if (outcome.alreadyForeground) { + appendResponseWarning(openResult, alreadyForegroundWarning()); + } const nextRef = publishOpenSession({ req, sessionStore, diff --git a/packages/platform-harmonyos/src/app-state.test.ts b/packages/platform-harmonyos/src/app-state.test.ts index 3c16d39366..df29c5fa6d 100644 --- a/packages/platform-harmonyos/src/app-state.test.ts +++ b/packages/platform-harmonyos/src/app-state.test.ts @@ -1,5 +1,19 @@ -import { expect, test } from 'vitest'; -import { parseHarmonyForegroundApp } from './app-state.ts'; +import { expect, test, vi } from 'vitest'; + +vi.mock('./hdc.ts', () => ({ runHarmonyShell: vi.fn() })); + +import { runHarmonyShell } from './hdc.ts'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { parseHarmonyForegroundApp, probeHarmonyForegroundBundle } from './app-state.ts'; + +const DEVICE: DeviceInfo = { + platform: 'harmonyos', + id: 'harmony-1', + name: 'HarmonyOS test device', + kind: 'device', + target: 'mobile', + booted: true, +}; test('parses the foreground ability from the mission list', () => { expect( @@ -15,3 +29,40 @@ test('parses the foreground ability from the mission list', () => { test('rejects a mission list without a foreground ability', () => { expect(parseHarmonyForegroundApp('Mission ID #57 state #BACKGROUND')).toBeUndefined(); }); + +test('the open-time probe names the foreground bundle', async () => { + const hdc = vi.mocked(runHarmonyShell); + hdc.mockResolvedValue({ + stdout: + 'Mission ID #76 mission name #[#com.example.application:entry:EntryAbility]\n' + + ' state #FOREGROUND', + exitCode: 0, + stderr: '', + }); + + await expect(probeHarmonyForegroundBundle(DEVICE, new AbortController().signal)).resolves.toBe( + 'com.example.application', + ); +}); + +test('the open-time probe claims nothing when no mission is foreground', async () => { + const hdc = vi.mocked(runHarmonyShell); + hdc.mockResolvedValue({ + stdout: 'Mission ID #57 state #BACKGROUND', + exitCode: 0, + stderr: '', + }); + + await expect( + probeHarmonyForegroundBundle(DEVICE, new AbortController().signal), + ).resolves.toBeUndefined(); +}); + +test('the open-time probe claims nothing when the device read fails', async () => { + const hdc = vi.mocked(runHarmonyShell); + hdc.mockRejectedValue(new Error('device offline')); + + await expect( + probeHarmonyForegroundBundle(DEVICE, new AbortController().signal), + ).resolves.toBeUndefined(); +}); diff --git a/packages/platform-harmonyos/src/app-state.ts b/packages/platform-harmonyos/src/app-state.ts index f655c06045..510e6f40fb 100644 --- a/packages/platform-harmonyos/src/app-state.ts +++ b/packages/platform-harmonyos/src/app-state.ts @@ -34,3 +34,24 @@ export function parseHarmonyForegroundApp(rawOutput: string): AppStateRuntimeRes } return undefined; } + +/** + * Reads which bundle holds the foreground at open time, or `undefined` when no read answers. The + * open-time probe is advisory: an unreadable read claims nothing and never fails the open it + * informs. + */ +export async function probeHarmonyForegroundBundle( + device: DeviceInfo, + signal: AbortSignal, +): Promise { + try { + const { runHarmonyShell } = await import('./hdc.ts'); + const result = await runHarmonyShell(device, ['aa', 'dump', '-l'], { + timeoutMs: 15_000, + signal, + }); + return parseHarmonyForegroundApp(result.stdout)?.package; + } catch { + return undefined; + } +} diff --git a/packages/platform-harmonyos/src/runtime.ts b/packages/platform-harmonyos/src/runtime.ts index 4b87a01737..e985129bce 100644 --- a/packages/platform-harmonyos/src/runtime.ts +++ b/packages/platform-harmonyos/src/runtime.ts @@ -49,7 +49,7 @@ import { createHarmonyScreenRecordingOperations, harmonyScreenRecordingFacts, } from './recording/runtime.ts'; -import { readHarmonyAppState } from './app-state.ts'; +import { probeHarmonyForegroundBundle, readHarmonyAppState } from './app-state.ts'; import { bindLocalDirectApplicationLifecycle } from '@agent-device/contracts/application-lifecycle-interaction'; import { createHarmonyAppDeploymentOperations, @@ -369,6 +369,8 @@ export function createHarmonyPlatformRuntime(host: PlatformRuntimeHost): Platfor host: host.localInteractors, device: request.device, signal: request.scope.signal, + readForegroundBundle: (signal) => + probeHarmonyForegroundBundle(request.device, signal), }), facts.operations, ),