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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions packages/contracts/src/application-lifecycle-interaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
49 changes: 48 additions & 1 deletion packages/contracts/src/application-lifecycle-interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | undefined>;
/** Port reverse is the one non-direct operation a provider owner may still implement. */
configureProviderPortReverse?: ApplicationLifecycleRuntimeOperations['configureProviderPortReverse'];
}>;
Expand Down Expand Up @@ -318,6 +325,7 @@ async function openDirectApplication(
): Promise<OpenApplicationOutcome> {
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,
Expand Down Expand Up @@ -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<boolean> {
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 {
Expand Down Expand Up @@ -405,13 +450,15 @@ export function bindLocalDirectApplicationLifecycle(
host: Readonly<{ resolve: LocalApplicationLifecycleInteractorResolver }>;
device: DeviceInfo;
signal: AbortSignal;
readForegroundBundle?: DirectApplicationLifecycleParams['readForegroundBundle'];
}>,
): ApplicationLifecycleRuntimeOperations {
return bindDirectApplicationLifecycle({
owner: params.owner,
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,
Expand Down
7 changes: 7 additions & 0 deletions packages/contracts/src/application-lifecycle-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}>;

Expand Down
Original file line number Diff line number Diff line change
@@ -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> = {},
): 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<DaemonResponse | null> {
const bindDevice: Parameters<typeof handleSessionCommands>[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<DaemonResponse> => ({ 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);
});
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading