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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/command-surface/src/management/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,9 @@ 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 <path> 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+<slug> 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 <App>?" 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 <ms> 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.',
'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console <path> 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. A later open without these flags applies the hints and launch URL again only when it opens the same app; it opens another app without them. 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+<slug> 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 <App>?" 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 <ms> 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.",
"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 later open without hints applies them again only when it opens the same app; it opens another app without them. A fresh open without Metro hints clears an older same-name binding; close also clears it.",
},
metadata: openCommandMetadata,
run: (client, input) => client.apps.open(toAppOpenOptions(input)),
Expand Down
13 changes: 10 additions & 3 deletions packages/daemon/src/core/session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,14 @@ export type RetainedExecutionHost = Readonly<{
lease: NonNullable<SessionState['lease']>;
}>;

// `appId` is the app an open applied the hints to; it stays absent until an open applies them.
export type StoredRuntimeHints = Readonly<{ hints: SessionRuntimeHints; appId?: string }>;

export class SessionStore {
private readonly sessions = new Map<string, SessionEntry>();
private readonly retainedExecutionHosts = new Map<string, RetainedExecutionHost>();
private acceptingSessions = true;
private readonly runtimeHints = new Map<string, SessionRuntimeHints>();
private readonly runtimeHints = new Map<string, StoredRuntimeHints>();
private readonly sessionsDir: string;
private readonly scriptWriter: SessionScriptWriter;

Expand Down Expand Up @@ -230,11 +233,15 @@ export class SessionStore {
}

getRuntimeHints(name: string): SessionRuntimeHints | undefined {
return this.runtimeHints.get(name)?.hints;
}

getStoredRuntimeHints(name: string): StoredRuntimeHints | undefined {
return this.runtimeHints.get(name);
}

setRuntimeHints(address: string, hints: SessionRuntimeHints | undefined): void {
if (hints) this.runtimeHints.set(address, hints);
setRuntimeHints(address: string, hints: SessionRuntimeHints | undefined, appId?: string): void {
if (hints) this.runtimeHints.set(address, { hints, appId });
else this.runtimeHints.delete(address);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ test('daemon lifecycle finalization admits facts once, binds once, and disposes
scope: scope(),
session,
stateDir: '/state',
runtimeHints: { metroHost: '10.0.2.2', metroPort: '8081' },
runtimeHints: { values: { metroHost: '10.0.2.2', metroPort: '8081' } },
});

expect(runtime.inspectFacts).toHaveBeenCalledTimes(1);
Expand All @@ -200,7 +200,7 @@ test('a daemon that stays alive finalizes without the shutdown deferral', async
scope: scope(),
session,
stateDir: '/state',
runtimeHints: {},
runtimeHints: { values: {} },
daemonLeaving: false,
});

Expand Down Expand Up @@ -272,7 +272,7 @@ test.each([
scope: scope(),
session: providerSession,
stateDir: '/state',
runtimeHints: {},
runtimeHints: { values: {} },
});

expect(inspectFacts).toHaveBeenCalledExactlyOnceWith(providerDevice);
Expand All @@ -297,7 +297,7 @@ test('daemon lifecycle finalization rejects a false fact before binding', async
scope: scope(),
session,
stateDir: '/state',
runtimeHints: {},
runtimeHints: { values: {} },
}),
).rejects.toMatchObject({
code: 'UNSUPPORTED_OPERATION',
Expand Down Expand Up @@ -329,7 +329,7 @@ test('daemon lifecycle finalization admits its distinct runtime-hint cleanup bef
scope: scope(),
session: sessionWithApplication,
stateDir: '/state',
runtimeHints,
runtimeHints: { appId: 'com.example.app', values: runtimeHints },
});

expect(runtime.inspectFacts).toHaveBeenCalledTimes(1);
Expand Down Expand Up @@ -358,7 +358,7 @@ test('daemon lifecycle finalization rejects a false runtime-hint cleanup fact be
scope: scope(),
session: sessionWithApplication,
stateDir: '/state',
runtimeHints: { metroHost: '10.0.2.2' },
runtimeHints: { appId: 'com.example.app', values: { metroHost: '10.0.2.2' } },
}),
).rejects.toMatchObject({
code: 'UNSUPPORTED_OPERATION',
Expand Down Expand Up @@ -388,7 +388,7 @@ test('daemon lifecycle finalization keeps an operation failure primary over bind
scope: scope(events),
session,
stateDir: '/state',
runtimeHints: {},
runtimeHints: { values: {} },
}),
).rejects.toBe(operationFailure);

Expand Down
27 changes: 8 additions & 19 deletions packages/daemon/src/server/application-lifecycle-recovery.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
type RuntimeHintValues,
hasRuntimeTransportHintValues,
} from '@agent-device/contracts/application-lifecycle-runtime';
import type { RuntimeHintsApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime';
import {
finalizeApplicationCloseRuntimeUse,
finalizeApplicationCloseWithRuntimeHintClearUse,
Expand All @@ -17,6 +14,7 @@ import type { PlatformRequestScope } from '@agent-device/contracts/platform-runt
import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations';
import { AppError, errorMessage } from '@agent-device/kernel/errors';
import type { SessionState } from '../core/session-state.ts';
import { requiresRuntimeHintsClear } from '../sessions/session-runtime.ts';
import type {
BindDeviceRuntime,
InspectDeviceRuntimeFacts,
Expand All @@ -27,7 +25,7 @@ type SessionFinalization = Readonly<{
bind: BindDeviceRuntime;
session: SessionState;
stateDir: string;
runtimeHints: RuntimeHintValues;
runtimeHints: RuntimeHintsApplicationInput;
daemonShutdown?: boolean;
}>;

Expand All @@ -41,7 +39,7 @@ async function finalizeSessionApplicationLifecycle(params: SessionFinalization):
...finalizationInput(session, stateDir),
...(params.daemonShutdown ? { daemonShutdown: true } : {}),
};
if (!requiresRuntimeHintCleanup(session, runtimeHints)) {
if (!requiresRuntimeHintsClear(runtimeHints)) {
const use = finalizeApplicationCloseRuntimeUse;
assertLifecycleFacts(await inspectFacts(session.device), use.required, session);
await (await bind(session.device, use)).operations.finalizeApplicationClose(input);
Expand All @@ -51,18 +49,15 @@ async function finalizeSessionApplicationLifecycle(params: SessionFinalization):
assertLifecycleFacts(await inspectFacts(session.device), use.required, session);
const runtime = await bind(session.device, use);
await runtime.operations.finalizeApplicationClose(input);
await runtime.operations.clearRuntimeHints({
appId: session.appBundleId,
values: runtimeHints,
});
await runtime.operations.clearRuntimeHints(runtimeHints);
}

export async function finalizeBoundSessionApplicationLifecycle(params: {
inspectFacts: InspectDeviceRuntimeFacts;
bindDevice: BindDeviceRuntime;
session: SessionState;
stateDir: string;
runtimeHints: RuntimeHintValues;
runtimeHints: RuntimeHintsApplicationInput;
}): Promise<void> {
await finalizeSessionApplicationLifecycle({ ...params, bind: params.bindDevice });
}
Expand All @@ -83,7 +78,8 @@ export async function finalizeDaemonSessionApplicationLifecycle(params: {
scope: PlatformRequestScope;
session: SessionState;
stateDir: string;
runtimeHints: RuntimeHintValues;
/** The stored hints to clear and the app they are bound to, else the session's app. */
runtimeHints: RuntimeHintsApplicationInput;
daemonLeaving?: boolean;
}): Promise<void> {
const { gateway, scope, session, stateDir, runtimeHints } = params;
Expand Down Expand Up @@ -148,10 +144,3 @@ function finalizationInput(session: SessionState, stateDir: string) {
stateDir,
};
}

function requiresRuntimeHintCleanup(
session: SessionState,
runtimeHints: RuntimeHintValues,
): boolean {
return session.appBundleId !== undefined && hasRuntimeTransportHintValues(runtimeHints);
}
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,11 @@ test.each([false, true])(
const address = 'cwd:shutdown-hints:default';
const ref = sessionStore.publish(address, makeIosSession('default'));
const publicRef = sessionStore.publish('default', makeIosSession('default'));
sessionStore.setRuntimeHints(address, { metroHost: 'scoped.example', metroPort: 8082 });
sessionStore.setRuntimeHints(
address,
{ metroHost: 'scoped.example', metroPort: 8082 },
'com.example.bound',
);
sessionStore.setRuntimeHints('default', { metroHost: 'public.example', metroPort: 8083 });
let successor;
if (retired) {
Expand All @@ -458,10 +462,10 @@ test.each([false, true])(
platformCleanup: platformResourceCleanupFixture(),
});

expect(finalizeApplicationLifecycle).toHaveBeenCalledWith(
ref.session,
retired ? {} : { metroHost: 'scoped.example', metroPort: '8082' },
);
expect(finalizeApplicationLifecycle).toHaveBeenCalledWith(ref.session, {
appId: retired ? undefined : 'com.example.bound',
values: retired ? {} : { metroHost: 'scoped.example', metroPort: '8082' },
});
expect(sessionStore.resolveCurrent(publicRef)).toBe(publicRef.session);
expect(sessionStore.getRuntimeHints('default')).toEqual({
metroHost: 'public.example',
Expand Down
7 changes: 5 additions & 2 deletions packages/daemon/src/server/http/daemon-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import type { LeaseEndReason } from '../../sessions/lease-lifecycle.ts';
import { teardownSessionResources } from '../../sessions/session-teardown.ts';
import { resolveDaemonSessionTeardownTimeoutMs } from '../../sessions/session-teardown-budget.ts';
import { finalizeDaemonSessionApplicationLifecycle } from '../application-lifecycle-recovery.ts';
import { runtimeHintValues } from '../../sessions/session-runtime.ts';
import { runtimeHintsClearInput } from '../../sessions/session-runtime.ts';
import {
closeDaemonServers,
teardownDaemonSessionForShutdown,
Expand Down Expand Up @@ -416,7 +416,10 @@ async function startDaemonRuntimeOnHost(
const settleIdleExpiredSession = async (ref: SessionRef): Promise<void> => {
const session = sessionStore.resolveCurrent(ref) ?? ref.session;
const sessionName = ref.address;
const runtimeHints = runtimeHintValues(sessionStore.getRuntimeHints(sessionName));
const runtimeHints = runtimeHintsClearInput(
sessionStore.getStoredRuntimeHints(sessionName),
session.appBundleId,
);
await teardownSessionResources({
appLog: 'run',
ref,
Expand Down
Loading
Loading