diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 92b4bd5905..d5d0e17209 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -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 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+ 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.', + '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. 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. An open that passes hints for another app also removes the earlier hints from the app an earlier open applied them to. 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 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.", + "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. An open that passes hints for another app also removes the earlier hints from the app an earlier open applied them to. 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)), diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index 660773e011..9622133a2e 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -260,6 +260,7 @@ export type LaunchConfirmationAbsent = Readonly<{ }>; type OpenApplicationOutcomeBase = Readonly<{ + /** The app the open reached. The daemon reads it only when the input carried no `appBundleId`. */ appBundleId?: string; timing: OpenApplicationTiming; }>; diff --git a/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts b/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts index a185f48055..0d1f9b6590 100644 --- a/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts +++ b/packages/daemon/src/core/__tests__/session-store-lifetime.test.ts @@ -73,7 +73,7 @@ test('address reuse with the same record still starts a different lifetime', () assert.throws(() => store.update(old, { appName: 'Stale' }), ended); assert.equal(store.retire(old), false); assert.equal(store.get(ADDRESS), session); - assert.equal(store.getRuntimeHints(ADDRESS)?.metroPort, 8082); + assert.equal(store.getRuntimeHints(ADDRESS)?.hints?.metroPort, 8082); assert.equal(store.retire(successor), true); assert.equal(store.getRuntimeHints(ADDRESS), undefined); }); diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 3e4fef40c0..4c62e42398 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -232,11 +232,7 @@ export class SessionStore { return Array.from(this.sessions, ([address, entry]) => this.captureRef(address, entry)); } - getRuntimeHints(name: string): SessionRuntimeHints | undefined { - return this.runtimeHints.get(name)?.hints; - } - - getStoredRuntimeHints(name: string): StoredRuntimeHints | undefined { + getRuntimeHints(name: string): StoredRuntimeHints | undefined { return this.runtimeHints.get(name); } diff --git a/packages/daemon/src/server/http/daemon-runtime-lifecycle-shutdown.test.ts b/packages/daemon/src/server/http/daemon-runtime-lifecycle-shutdown.test.ts index 8cf9ccf470..44fa998c79 100644 --- a/packages/daemon/src/server/http/daemon-runtime-lifecycle-shutdown.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-lifecycle-shutdown.test.ts @@ -467,13 +467,13 @@ test.each([false, true])( values: retired ? {} : { metroHost: 'scoped.example', metroPort: '8082' }, }); expect(sessionStore.resolveCurrent(publicRef)).toBe(publicRef.session); - expect(sessionStore.getRuntimeHints('default')).toEqual({ + expect(sessionStore.getRuntimeHints('default')?.hints).toEqual({ metroHost: 'public.example', metroPort: 8083, }); if (successor) { expect(sessionStore.resolveCurrent(successor)).toBe(successor.session); - expect(sessionStore.getRuntimeHints(address)).toEqual({ + expect(sessionStore.getRuntimeHints(address)?.hints).toEqual({ metroHost: 'successor.example', metroPort: 8084, }); diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index af14d90092..4d6e1579eb 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -420,7 +420,7 @@ async function startDaemonRuntimeOnHost( const session = sessionStore.resolveCurrent(ref) ?? ref.session; const sessionName = ref.address; const runtimeHints = runtimeHintsClearInput( - sessionStore.getStoredRuntimeHints(sessionName), + sessionStore.getRuntimeHints(sessionName), session.appBundleId, ); await teardownSessionResources({ diff --git a/packages/daemon/src/server/http/daemon-session-idle-expiry.test.ts b/packages/daemon/src/server/http/daemon-session-idle-expiry.test.ts index ce53c757e2..71478ffbab 100644 --- a/packages/daemon/src/server/http/daemon-session-idle-expiry.test.ts +++ b/packages/daemon/src/server/http/daemon-session-idle-expiry.test.ts @@ -444,7 +444,7 @@ test('an idle settle cannot finalize or retire a replacement at its scoped addre assert.equal(successor.session.scriptPublication.status, 'complete'); } assert.equal(successor.session.actions.length, 0); - assert.equal(sessionStore.getRuntimeHints(address)?.metroPort, 9090); + assert.equal(sessionStore.getRuntimeHints(address)?.hints?.metroPort, 9090); assert.equal(sessionStore.readIdleExpiryTombstone(address), undefined); } finally { release(); diff --git a/packages/daemon/src/server/http/server-shutdown.ts b/packages/daemon/src/server/http/server-shutdown.ts index 74914884d2..a92cd60414 100644 --- a/packages/daemon/src/server/http/server-shutdown.ts +++ b/packages/daemon/src/server/http/server-shutdown.ts @@ -292,7 +292,7 @@ export async function teardownDaemonSessionForShutdown(params: { const current = sessionStore.resolveCurrent(ref); const session = current ?? ref.session; const runtimeHints = runtimeHintsClearInput( - current ? sessionStore.getStoredRuntimeHints(ref.address) : undefined, + current ? sessionStore.getRuntimeHints(ref.address) : undefined, session.appBundleId, ); const timeoutMs = resolveDaemonSessionTeardownTimeoutMs(session); diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index f7fa48e35c..a535359f84 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -652,7 +652,7 @@ async function teardownExpiredSession(params: { const session = sessionStore.resolveCurrent(ref) ?? ref.session; const sessionName = ref.address; const runtimeHints = runtimeHintsClearInput( - sessionStore.getStoredRuntimeHints(ref.address), + sessionStore.getRuntimeHints(ref.address), session.appBundleId, ); let primaryError: unknown; diff --git a/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts b/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts index fa14ec5d5f..9242bef4b6 100644 --- a/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-recording-health.test.ts @@ -251,7 +251,7 @@ test.each(['rebuild', 'retire'] as const)( } } else { expect(result).toMatchObject({ error: { details: { reason: 'session_lifetime_ended' } } }); - expect(store.getRuntimeHints('default')).toEqual({ metroPort: 8083 }); + expect(store.getRuntimeHints('default')?.hints).toEqual({ metroPort: 8083 }); } }, ); diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-runtime-command.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-runtime-command.test.ts index 91e1a49d55..3f5914db30 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-runtime-command.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-runtime-command.test.ts @@ -253,7 +253,7 @@ test('runtime clear rejects a false runtime-hints fact before its one implementa expect(mockInspectDeviceRuntimeFacts).toHaveBeenCalledTimes(1); expect(mockBindDeviceRuntime).not.toHaveBeenCalled(); expect(mockClearRuntimeHints).not.toHaveBeenCalled(); - expect(sessionStore.getRuntimeHints(sessionName)).toEqual({ + expect(sessionStore.getRuntimeHints(sessionName)?.hints).toEqual({ platform: 'android', metroHost: '10.0.0.10', metroPort: 8081, @@ -370,7 +370,7 @@ for (const phase of ['admission', 'effect'] as const) { code: 'COMMAND_FAILED', details: { reason: 'session_lifetime_ended' }, }); - expect(sessionStore.getRuntimeHints(address)).toBe(successorHints); + expect(sessionStore.getRuntimeHints(address)?.hints).toBe(successorHints); expect(refFrameState(sessionStore.get(address)!)).toBe('active'); expect(mockClearRuntimeHints).toHaveBeenCalledTimes(phase === 'admission' ? 0 : 1); }); diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index e266b72b86..cf886d90ff 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -182,7 +182,7 @@ export function createReplaySession( const reads = { get: () => store.get(name), lookup: () => store.lookup(name), - getRuntimeHints: () => store.getRuntimeHints(name), + getRuntimeHints: () => store.getRuntimeHints(name)?.hints, ensureSessionDir: () => store.ensureSessionDir(name), }; let captureCell: diff --git a/packages/daemon/src/sessions/handlers/session-runtime-command.ts b/packages/daemon/src/sessions/handlers/session-runtime-command.ts index 0495c4798e..ed3abcda23 100644 --- a/packages/daemon/src/sessions/handlers/session-runtime-command.ts +++ b/packages/daemon/src/sessions/handlers/session-runtime-command.ts @@ -3,8 +3,8 @@ import type { DaemonPlatformServices } from '../../core/platform-services.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { publicPlatformString } from '@agent-device/kernel/device'; import { clearRuntimeHintsRuntimeUse } from '@agent-device/contracts/application-lifecycle-runtime-plan'; -import { SessionStore } from '../../core/session-store.ts'; -import type { SessionRef } from '../../core/session-state.ts'; +import { SessionStore, type StoredRuntimeHints } from '../../core/session-store.ts'; +import type { SessionRef, SessionRuntimeHints } from '../../core/session-state.ts'; import { expireRefFrame } from '../../core/ref-frame.ts'; import { admitRuntimeUse } from '../../core/runtime-admission.ts'; import { @@ -76,23 +76,23 @@ export async function handleRuntimeCommand(params: { } const ref = sessionStore.lookup(sessionName); const session = ref?.session; - const current = sessionStore.getRuntimeHints(sessionName); + const stored = sessionStore.getRuntimeHints(sessionName); if (action === 'clear') { return await clearRuntimeCommand({ sessionName, sessionStore, ref, - current, + stored, inspectFacts: params.inspectFacts, platformServices: params.platformServices, bindDevice: params.bindDevice, }); } if (action === 'show') { - return showRuntimeCommand(sessionName, current); + return showRuntimeCommand(sessionName, stored?.hints); } - return setRuntimeCommand({ req, sessionName, sessionStore, session, current }); + return setRuntimeCommand({ req, sessionName, sessionStore, session, stored }); } async function readGestureViewport(params: { @@ -133,15 +133,14 @@ async function clearRuntimeCommand(params: { sessionName: string; sessionStore: SessionStore; ref: SessionRef | undefined; - current: ReturnType; + stored: StoredRuntimeHints | undefined; inspectFacts?: InspectDeviceRuntimeFacts; platformServices: DaemonPlatformServices; bindDevice?: BindDeviceRuntime; }): Promise { - const { sessionName, sessionStore, ref, current, inspectFacts, bindDevice, platformServices } = + const { sessionName, sessionStore, ref, stored, inspectFacts, bindDevice, platformServices } = params; const session = ref ? sessionStore.requireCurrent(ref) : undefined; - const stored = sessionStore.getStoredRuntimeHints(sessionName); if (session && requiresRuntimeHintsClear(runtimeHintsClearInput(stored, session.appBundleId))) { const admission = await admitClearRuntime({ device: session.device, @@ -158,14 +157,14 @@ async function clearRuntimeCommand(params: { runtimeHintsClearInput(stored, currentSession.appBundleId), ); } - const cleared = ref ? sessionStore.clearRuntimeHints(ref) : Boolean(current); + const cleared = ref ? sessionStore.clearRuntimeHints(ref) : Boolean(stored); if (!ref) sessionStore.setRuntimeHints(sessionName, undefined); return { ok: true, data: { session: sessionName, cleared } }; } function showRuntimeCommand( sessionName: string, - current: ReturnType, + current: SessionRuntimeHints | undefined, ): DaemonResponse { return { ok: true, @@ -188,9 +187,10 @@ function setRuntimeCommand(params: { sessionName: string; sessionStore: SessionStore; session: ReturnType; - current: ReturnType; + stored: StoredRuntimeHints | undefined; }): DaemonResponse { - const { req, sessionName, sessionStore, session, current } = params; + const { req, sessionName, sessionStore, session, stored } = params; + const current = stored?.hints; // approach (b): resolve the session's PUBLIC leaf platform (ios/macos), never the // internal `apple`, so the legacy `--platform ios` selector still matches. const sessionLeaf = sessionLeafPlatform(session); @@ -214,11 +214,7 @@ function setRuntimeCommand(params: { 'runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.', ); } - sessionStore.setRuntimeHints( - sessionName, - nextRuntime, - sessionStore.getStoredRuntimeHints(sessionName)?.appId, - ); + sessionStore.setRuntimeHints(sessionName, nextRuntime, stored?.appId); return { ok: true, data: { diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts index 25f3f55966..bceb7f43a6 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts @@ -349,7 +349,7 @@ test('an app-only close with stored hints selects no runtime-hint cleanup siblin expect(mockBindDeviceRuntime).toHaveBeenCalledTimes(1); expect(mockDispatch).toHaveBeenCalledOnce(); expect(clearRuntimeHintsFixture).not.toHaveBeenCalled(); - expect(sessionStore.getRuntimeHints(sessionName)).toEqual({ + expect(sessionStore.getRuntimeHints(sessionName)?.hints).toEqual({ platform: 'android', metroHost: '10.0.2.2', }); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-resource-cleanup.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-resource-cleanup.test.ts index 77f31eda9d..a0c422b2c5 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-resource-cleanup.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-resource-cleanup.test.ts @@ -334,7 +334,7 @@ test('close cannot retire a replacement session while its provider release waits data: { provider: { releasedBy: 'provider' } }, }); expect(sessionStore.requireCurrent(successor)).toBe(successor.session); - expect(sessionStore.getRuntimeHints(address)).toEqual({ metroPort: 9090 }); + expect(sessionStore.getRuntimeHints(address)?.hints).toEqual({ metroPort: 9090 }); expect(leaseRegistry.listActiveLeases()).toHaveLength(0); } finally { release(); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-execution-runtime.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-execution-runtime.test.ts index 1e219b5116..0b9ea16aa7 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-execution-runtime.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-execution-runtime.test.ts @@ -165,7 +165,7 @@ test('open runtime payload replaces stored session runtime atomically', async () { appId: 'com.example.demo', host: '10.0.0.10', port: '8081', launchUrl: undefined }, ]); expect(dispatchCalls).toEqual([{ command: 'open', positionals: ['Demo'] }]); - expect(sessionStore.getRuntimeHints(sessionName)).toEqual({ + expect(sessionStore.getRuntimeHints(sessionName)?.hints).toEqual({ platform: 'android', metroHost: '10.0.0.10', metroPort: 8081, @@ -245,7 +245,7 @@ test('open runtime payload clears stale applied transport hints before launch', 'dispatch:open:Demo', 'dispatch:open:myapp://fresh', ]); - expect(sessionStore.getRuntimeHints(sessionName)).toEqual({ + expect(sessionStore.getRuntimeHints(sessionName)?.hints).toEqual({ platform: 'android', metroHost: undefined, metroPort: undefined, @@ -340,7 +340,7 @@ test('open runtime payload rejects malformed runtime objects without mutating se expect(response.error.code).toBe('INVALID_ARGS'); expect(response.error.message).toBe('open runtime must be an object.'); } - expect(sessionStore.getRuntimeHints(sessionName)).toEqual({ + expect(sessionStore.getRuntimeHints(sessionName)?.hints).toEqual({ platform: 'android', metroHost: '10.0.0.10', metroPort: 8081, @@ -384,7 +384,7 @@ test('open runtime payload does not persist replacement when launch fails', asyn }), ).rejects.toThrow(expect.objectContaining({ code: 'COMMAND_FAILED', message: 'launch failed' })); - expect(sessionStore.getRuntimeHints(sessionName)).toEqual({ + expect(sessionStore.getRuntimeHints(sessionName)?.hints).toEqual({ platform: 'android', metroHost: '10.0.0.10', metroPort: 8081, @@ -565,7 +565,7 @@ test('a retired reopen cannot write hints or actions to the same record republis await refusal; expect(store.requireCurrent(successor)).toBe(session); expect(session.actions).toEqual([]); - expect(store.getRuntimeHints(ref.address)?.metroHost).toBe('successor-host'); + expect(store.getRuntimeHints(ref.address)?.hints?.metroHost).toBe('successor-host'); }); test('a provisional open refuses a successor before native launch', async () => { diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-runtime.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-runtime.test.ts index cbc57934ee..e186e0113c 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-runtime.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-runtime.test.ts @@ -4,6 +4,7 @@ import { test, expect, vi, beforeEach } from 'vitest'; import path from 'node:path'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { DaemonRequest } from '../../../../core/daemon-request.ts'; +import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import { fakeCreateCommandSurface } from '../../../../__tests__/support/command-surface-fake.ts'; const mockResolveTargetDevice = vi.hoisted(() => vi.fn()); @@ -83,6 +84,7 @@ const mockApplyRuntimeHints = vi.mocked(applyRuntimeHintsFixture); const mockClearRuntimeHints = vi.mocked(clearRuntimeHintsFixture); const mockResolveAndroidPackage = vi.mocked(resolveAndroidPackageForOpen); const mockResolveOpenTarget = vi.mocked(resolveOpenTargetFixture); +type BindDevice = Parameters[0]['bindDevice']; beforeEach(() => { vi.clearAllMocks(); @@ -316,8 +318,8 @@ test('open --metro-port alone defaults the host to 10.0.2.2 on an Android emulat expect(response?.ok).toBe(true); expect(runtimeApplyCalls).toEqual([{ host: '10.0.2.2', port: '8084' }]); - expect(sessionStore.getRuntimeHints(sessionName)?.metroHost).toBe('10.0.2.2'); - expect(sessionStore.getRuntimeHints(sessionName)?.metroPort).toBe(8084); + expect(sessionStore.getRuntimeHints(sessionName)?.hints?.metroHost).toBe('10.0.2.2'); + expect(sessionStore.getRuntimeHints(sessionName)?.hints?.metroPort).toBe(8084); }); test('open --metro-port alone defaults the host to 127.0.0.1 on an iOS simulator', async () => { @@ -350,7 +352,7 @@ test('open --metro-port alone defaults the host to 127.0.0.1 on an iOS simulator expect(response?.ok).toBe(true); expect(runtimeApplyCalls).toEqual([{ host: '127.0.0.1', port: '8084' }]); - expect(sessionStore.getRuntimeHints(sessionName)?.metroHost).toBe('127.0.0.1'); + expect(sessionStore.getRuntimeHints(sessionName)?.hints?.metroHost).toBe('127.0.0.1'); }); test('open --metro-port alone stays host-ambiguous on a physical Android device', async () => { @@ -384,8 +386,8 @@ test('open --metro-port alone stays host-ambiguous on a physical Android device' expect(response?.ok).toBe(true); expect(runtimeApplyCalls).toEqual([{ host: undefined, port: '8084' }]); - expect(sessionStore.getRuntimeHints(sessionName)?.metroHost).toBeUndefined(); - expect(sessionStore.getRuntimeHints(sessionName)?.metroPort).toBe(8084); + expect(sessionStore.getRuntimeHints(sessionName)?.hints?.metroHost).toBeUndefined(); + expect(sessionStore.getRuntimeHints(sessionName)?.hints?.metroPort).toBe(8084); }); test('open --relaunch allows Android package names ending with apk-like suffix', async () => { @@ -427,6 +429,7 @@ test('open --relaunch allows Android package names ending with apk-like suffix', async function runSessionCommand( sessionStore: ReturnType, req: Omit, + bindDevice?: BindDevice, ): Promise { const response = await handleSessionCommands({ host: createTestHostEnvironment(), @@ -437,6 +440,7 @@ async function runSessionCommand( logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), sessionStore, invoke: noopInvoke, + bindDevice, }); if (!response) throw new Error(`${req.command} was not handled`); return response; @@ -450,6 +454,98 @@ function recordRuntimeHintApplies(): Array<{ appId?: string; host?: string; port return applies; } +/** The launch reports `appBundleId`, as a platform does for the app it saw after the launch. */ +function bindReportingOpenedApp(appBundleId: string): BindDevice { + return async (device, use) => { + const binding = await mockBindDeviceRuntime(device, use); + return { + ...binding, + operations: { + ...binding.operations, + openApplication: async (input: OpenApplicationInput) => ({ + ...(await binding.operations.openApplication(input)), + appBundleId, + }), + }, + }; + }; +} + +test.each([ + { storedBy: 'open flags', runtime: { metroPort: 8081 }, reopen: 'com.example.metro' }, + { + storedBy: 'runtime hints set before the first open', + runtime: undefined, + reopen: 'com.example.metro', + }, + { storedBy: 'open flags', runtime: { metroPort: 8081 }, reopen: 'myapp://home' }, +])( + 'hints stored by $storedBy apply again on a reopen of $reopen when the open reports another app id', + async ({ runtime, reopen }) => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-outcome-id'; + const applies = recordRuntimeHintApplies(); + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + if (!runtime) sessionStore.setRuntimeHints(session, { platform: 'android', metroPort: 8081 }); + const reportsOtherAppId = bindReportingOpenedApp('com.example.foreground'); + for (const [target, hints] of [ + ['com.example.metro', runtime], + [reopen, undefined], + ] as const) { + const opened = await runSessionCommand( + sessionStore, + { + session, + command: 'open', + positionals: [target], + flags: { platform: 'android' }, + ...(hints ? { runtime: hints } : {}), + }, + reportsOtherAppId, + ); + expect(opened.ok).toBe(true); + } + + expect(applies).toEqual([ + { appId: 'com.example.metro', host: '10.0.2.2', port: '8081' }, + { appId: 'com.example.metro', host: '10.0.2.2', port: '8081' }, + ]); + }, +); + +test.each([ + { storedBy: 'open flags', runtime: { metroPort: 8082 } }, + { storedBy: 'runtime hints set before the first open', runtime: undefined }, +])( + 'hints stored by $storedBy for a deep link bind to the app the launch reports', + async ({ runtime }) => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-deep-link'; + const applies = recordRuntimeHintApplies(); + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + if (!runtime) sessionStore.setRuntimeHints(session, { platform: 'android', metroPort: 8082 }); + const open = async (target: string, hints?: DaemonRequest['runtime']) => + await runSessionCommand( + sessionStore, + { + session, + command: 'open', + positionals: [target], + flags: { platform: 'android' }, + ...(hints ? { runtime: hints } : {}), + }, + bindReportingOpenedApp(target.includes('://') ? 'com.example.metro' : target), + ); + + const deepLink = await open('myapp://home', runtime); + const settings = await open('com.android.settings'); + + expect([deepLink.ok, settings.ok]).toEqual([true, true]); + expect(applies).toEqual([{ appId: undefined, host: '10.0.2.2', port: '8082' }]); + expect(sessionStore.getRuntimeHints(session)?.appId).toBe('com.example.metro'); + }, +); + test.each([ { label: 'an Android emulator', @@ -608,3 +704,166 @@ test.each([ ); }, ); + +async function openTwiceWithHints( + session: string, + second: Readonly<{ target: string; metroPort: number }>, + bindDevice?: BindDevice, + first: DaemonRequest['runtime'] = { metroPort: 8081 }, +): Promise<{ + store: ReturnType; + effects: string[]; + secondOpen: unknown; +}> { + const sessionStore = makeSessionStore(); + const effects: string[] = []; + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + mockApplyRuntimeHints.mockImplementation(async ({ appId, values }) => { + effects.push(`apply ${appId} ${values.metroPort}`); + }); + mockClearRuntimeHints.mockImplementation(async ({ appId, values }) => { + effects.push(`clear ${appId} ${values.metroPort}`); + }); + const open = async (target: string, runtime: DaemonRequest['runtime'], bind?: BindDevice) => + await runSessionCommand( + sessionStore, + { session, command: 'open', positionals: [target], flags: { platform: 'android' }, runtime }, + bind, + ); + + expect((await open('com.example.metro', first)).ok).toBe(true); + const secondOpen = await open(second.target, { metroPort: second.metroPort }, bindDevice).catch( + (error: unknown) => error, + ); + return { store: sessionStore, effects, secondOpen }; +} + +test.each([ + { + opened: 'another app with different hints', + first: undefined, + second: { target: 'com.example.other', metroPort: 8082 }, + effects: [ + 'apply com.example.metro 8081', + 'apply com.example.other 8082', + 'clear com.example.metro 8081', + ], + }, + { + opened: 'another app with the same hints', + first: undefined, + second: { target: 'com.example.other', metroPort: 8081 }, + effects: [ + 'apply com.example.metro 8081', + 'apply com.example.other 8081', + 'clear com.example.metro 8081', + ], + }, + { + opened: 'the same app with different hints', + first: undefined, + second: { target: 'com.example.metro', metroPort: 8082 }, + effects: ['apply com.example.metro 8081', 'apply com.example.metro 8082'], + }, + { + opened: 'another app after an open with only a launch URL', + first: { launchUrl: 'metroapp://dev-client' }, + second: { target: 'com.example.other', metroPort: 8082 }, + effects: ['apply com.example.other 8082'], + }, +])( + 'an open of $opened clears the replaced hints only from another app', + async ({ first, second, effects }) => { + const result = await openTwiceWithHints('runtime-hints-replaced', second, undefined, first); + + expect((result.secondOpen as DaemonResponse).ok).toBe(true); + expect(result.effects).toEqual(effects); + expect(result.store.getRuntimeHints('runtime-hints-replaced')).toMatchObject({ + appId: second.target, + hints: { metroPort: second.metroPort }, + }); + }, +); + +test('an open of another app reports a warning when the replaced hints cannot be removed', async () => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-replaced-clear-fails'; + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + const open = async (target: string, metroPort: number) => + await runSessionCommand(sessionStore, { + session, + command: 'open', + positionals: [target], + flags: { platform: 'android' }, + runtime: { metroPort }, + }); + + await open('com.example.metro', 8081); + mockClearRuntimeHints.mockRejectedValueOnce(new Error('prefs write failed')); + const opened = await open('com.example.other', 8082); + + expect(opened.ok).toBe(true); + expect(opened.ok ? opened.data?.warnings : undefined).toEqual([ + expect.stringContaining('com.example.metro'), + ]); + expect(sessionStore.getRuntimeHints(session)).toMatchObject({ + appId: 'com.example.other', + hints: { metroPort: 8082 }, + }); +}); + +test('a failed launch of another app keeps the replaced hints on the app they were applied to', async () => { + const launchFails: BindDevice = async (device, use) => { + const binding = await mockBindDeviceRuntime(device, use); + return { + ...binding, + operations: { + ...binding.operations, + openApplication: async () => { + throw new Error('launch failed'); + }, + }, + }; + }; + + const result = await openTwiceWithHints( + 'runtime-hints-replaced-failed-launch', + { target: 'com.example.other', metroPort: 8082 }, + launchFails, + ); + + expect(result.secondOpen).toBeInstanceOf(Error); + expect(result.effects).toEqual(['apply com.example.metro 8081']); + expect(result.store.getRuntimeHints('runtime-hints-replaced-failed-launch')).toMatchObject({ + appId: 'com.example.metro', + hints: { metroPort: 8081 }, + }); +}); + +test('an open with new hints clears nothing for replaced hints that no open applied', async () => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-replaced-unbound'; + const applies = recordRuntimeHintApplies(); + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + const open = async (target: string, runtime?: DaemonRequest['runtime']) => + await runSessionCommand(sessionStore, { + session, + command: 'open', + positionals: [target], + flags: { platform: 'android' }, + ...(runtime ? { runtime } : {}), + }); + + await open('com.google.android.apps.photos'); + const set = await runSessionCommand(sessionStore, { + session, + command: 'runtime', + positionals: ['set'], + flags: { metroPort: 8081 }, + }); + const opened = await open('com.example.metro', { metroPort: 8082 }); + + expect([set.ok, opened.ok]).toEqual([true, true]); + expect(mockClearRuntimeHints).not.toHaveBeenCalled(); + expect(applies).toEqual([{ appId: 'com.example.metro', host: '10.0.2.2', port: '8082' }]); +}); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts index 8940ec05a7..2936c474ec 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts @@ -90,7 +90,7 @@ export async function runSessionCloseTeardown(params: { inspectSessionLeaseRetainedOnClose({ session, leaseRegistry: params.leaseRegistry }), )), }); - const configuredRuntimeHints = sessionStore.getStoredRuntimeHints(sessionName); + const configuredRuntimeHints = sessionStore.getRuntimeHints(sessionName); const resourceStops = sessionResourceStopSteps({ ref, sessionStore, diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts index 31296786de..ebd3ca09ec 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -324,10 +324,7 @@ export async function handleSessionCloseCommands( clearRuntimeHints: req.internal?.closeAppOnly !== true && requiresRuntimeHintsClear( - runtimeHintsClearInput( - sessionStore.getStoredRuntimeHints(sessionName), - session.appBundleId, - ), + runtimeHintsClearInput(sessionStore.getRuntimeHints(sessionName), session.appBundleId), ), inspectFacts: params.inspectFacts, platformServices: params.platformServices, 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 e83c2b1d9d..7d7c5784c3 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 @@ -26,7 +26,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { DaemonPlatformServices } from '../../../core/platform-services.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import { requestCwd } from '../../../core/context.ts'; -import type { SessionRef, SessionState } from '../../../core/session-state.ts'; +import type { SessionRef, SessionRuntimeHints, SessionState } from '../../../core/session-state.ts'; import { abortAuthoringOnSecondOpen, armAuthoringOnOpen, @@ -36,6 +36,7 @@ import { import { isRequestCanceled } from '@agent-device/host-kit/request'; import { AppError, + asAppError, createRequestCanceledError, readDispatchDisclosure, type ReasonTable, @@ -45,6 +46,7 @@ import { bindStoredRuntimeHintsToApp, countConfiguredRuntimeHints, openApplicationRuntimeHints, + runtimeHintsClearInput, setSessionRuntimeHintsForOpen, } from '../../session-runtime.ts'; import { STARTUP_SAMPLE_METHOD, type StartupPerfSample } from './session-startup-metrics.ts'; @@ -57,6 +59,7 @@ import { import { emitDiagnostic, getDiagnosticsMeta } from '@agent-device/host-kit/diagnostics'; import { prepareOpenCommandDetails, + type ReplacedRuntimeHints, type ResolvedOpenRuntimeHintPlan, } from './session-open-prepare.ts'; import { findSessionDeviceConflict } from '../../open-device-contention-wait.ts'; @@ -137,6 +140,30 @@ function deviceClaimTakeoverWarning(tookOver: TakenOverDeviceClaim, req: DaemonR ); } +/** + * After the launch, the app the new hints bind to is the only one that keeps native hints. The + * open already succeeded, so a failed removal from the replaced app becomes a warning, as close + * treats its own clear as cleanup. + */ +async function clearReplacedRuntimeHints( + replaced: ReplacedRuntimeHints | undefined, + openedAppId: string | undefined, +): Promise { + if (!replaced || replaced.applied.appId === openedAppId) return undefined; + try { + await replaced.clear(runtimeHintsClearInput(replaced.applied, undefined)); + return undefined; + } catch (error) { + const message = asAppError(error).message; + emitDiagnostic({ + level: 'warn', + phase: 'open_replaced_runtime_hints_clear_failed', + data: { appId: replaced.applied.appId, error: message }, + }); + return `The earlier runtime hints could not be removed from ${replaced.applied.appId}: ${message}`; + } +} + /** What the caller's `open` output says about the launch-confirmation probe on this outcome. */ function launchConfirmationReport( outcome: OpenApplicationOutcome, @@ -267,7 +294,8 @@ export async function completeOpenCommand(params: { appName?: string; surface: SessionSurface; appBundleId?: string; - runtimeHints: ReturnType; + runtimeHints: SessionRuntimeHints | undefined; + replacedRuntimeHints?: ReplacedRuntimeHints; lifecycle: OpenApplicationRuntime; applyRuntimeHints?: RuntimeHintApplyOperation; existingRef?: SessionRef; @@ -288,6 +316,7 @@ export async function completeOpenCommand(params: { surface, appBundleId, runtimeHints, + replacedRuntimeHints, lifecycle, applyRuntimeHints, existingRef, @@ -350,7 +379,10 @@ export async function completeOpenCommand(params: { if (!effectsConfirmedOrUndispatched) markUnconfirmedRelaunch(); throw error; }); - sessionAppBundleId = outcome.appBundleId ?? sessionAppBundleId; + // One id feeds the session and the hint binding, so a later open compares one resolution. Each + // platform reports the prepared id back when there is one; Android reports the app it saw for a + // target without one, such as a deep link with no current app. + sessionAppBundleId ??= outcome.appBundleId; const timing: OpenTiming = { ...outcome.timing }; const preparedSelection = markSelectionBootOccurred(selection); const startupSample = openTarget @@ -366,6 +398,10 @@ export async function completeOpenCommand(params: { } requireOpenSessionAdmission(sessionStore, sessionName, openDispatchRef); + const replacedRuntimeHintsWarning = await clearReplacedRuntimeHints( + replacedRuntimeHints, + sessionAppBundleId, + ); if (existingRef) { markDeferredInteractionOutcome({ session: sessionStore.requireCurrent(existingRef), @@ -408,6 +444,7 @@ export async function completeOpenCommand(params: { if (tookOverDeviceClaim) { appendResponseWarning(openResult, deviceClaimTakeoverWarning(tookOverDeviceClaim, req)); } + if (replacedRuntimeHintsWarning) appendResponseWarning(openResult, replacedRuntimeHintsWarning); if (outcome.launchConfirmation === 'unanswered') { appendResponseWarning( openResult, @@ -639,6 +676,7 @@ export async function openNewSessionWithDeviceClaim(params: { appBundleId: details.details.appBundleId, appName: details.details.appName, runtimeHints: details.details.runtime, + replacedRuntimeHints: details.details.replacedRuntimeHints, lifecycle, applyRuntimeHints, surface, diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts index 1cfa11bce7..6c8c04dfd9 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts @@ -6,13 +6,15 @@ import type { BoundDeviceRuntime } from '@agent-device/contracts/platform-runtim import type { DeviceInfo } from '@agent-device/kernel/device'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionRuntimeHints, SessionState } from '../../../core/session-state.ts'; -import { SessionStore } from '../../../core/session-store.ts'; +import { SessionStore, type StoredRuntimeHints } from '../../../core/session-store.ts'; import type { DaemonPlatformServices } from '../../../core/platform-services.ts'; import { + type AppliedRuntimeHints, hasRuntimeTransportHints, + mayClearRemovedRuntimeTransportHints, maybeClearRemovedRuntimeTransportHints, + replacedAppliedRuntimeTransport, RUNTIME_HINTS_REASONS, - shouldClearRemovedRuntimeTransportHints, storedRuntimeHintsForApp, tryResolveOpenRuntimeHints, } from '../../session-runtime.ts'; @@ -25,8 +27,18 @@ type OpenCommandDetails = { appBundleId?: string; appName?: string; runtime: SessionRuntimeHints | undefined; + replacedRuntimeHints?: ReplacedRuntimeHints; }; +/** + * Applied hints that this open replaces with new transport hints, paired with the admitted clear. + * The open clears them after its launch succeeds, unless it binds the new hints to the same app. + */ +export type ReplacedRuntimeHints = Readonly<{ + applied: AppliedRuntimeHints; + clear: ClearRuntimeHints; +}>; + export type PreparedOpenCommandDetailsResult = | { type: 'response'; response: DaemonResponse } | { type: 'details'; details: OpenCommandDetails }; @@ -36,12 +48,11 @@ type ClearRuntimeHints = (input: RuntimeHintsApplicationInput) => Promise; export type ResolvedOpenRuntimeHintPlan = Readonly<{ runtime: SessionRuntimeHints | undefined; - previousRuntime: SessionRuntimeHints | undefined; - /** The app the stored hints are bound to; absent while they are unbound. */ - previousRuntimeAppId: string | undefined; + /** The stored hints this open found, with the app they are bound to. */ + previous: StoredRuntimeHints | undefined; replacedStoredRuntime: boolean; - // Admission may require the apply operation for stored hints that the open then drops because - // they are bound to another app: the target app is resolved only after admission. + // Admission may require an apply or clear operation that the open then skips because of the + // app the hints are bound to: the target app is resolved only after admission. applyRuntimeHints: boolean; clearRemovedRuntimeHints: boolean; }>; @@ -123,20 +134,17 @@ export function resolveOpenRuntimeHintPlan(params: { }): OpenRuntimeHintPlanResult { const runtimeResult = tryResolveOpenRuntimeHints(params); if (!runtimeResult.ok) return { type: 'response', response: runtimeResult }; - const { runtime, previousRuntime, replacedStoredRuntime } = runtimeResult.data; - const previousRuntimeAppId = params.sessionStore.getStoredRuntimeHints(params.sessionName)?.appId; + const { runtime, previous, replacedStoredRuntime } = runtimeResult.data; return { type: 'plan', plan: { runtime, - previousRuntime, - previousRuntimeAppId, + previous, replacedStoredRuntime, applyRuntimeHints: hasRuntimeTransportHints(runtime), - clearRemovedRuntimeHints: shouldClearRemovedRuntimeTransportHints({ + clearRemovedRuntimeHints: mayClearRemovedRuntimeTransportHints({ replacedStoredRuntime, - previousRuntime, - previousRuntimeAppId, + previous, runtime, session: params.existingSession, }), @@ -193,6 +201,13 @@ export async function prepareOpenCommandDetails(params: { existingAppBundleId: existingSession?.appBundleId, foreground, }); + const policy = { + replacedStoredRuntime: runtimeHintPlan.replacedStoredRuntime, + previous: runtimeHintPlan.previous, + runtime: runtimeHintPlan.runtime, + session: existingSession, + }; + let replacedRuntimeHints: ReplacedRuntimeHints | undefined; if (runtimeHintPlan.clearRemovedRuntimeHints) { if (!clearRuntimeHints) { // prepareApplicationOpen above may already have booted the device — a device-reaching @@ -207,14 +222,9 @@ export async function prepareOpenCommandDetails(params: { }, ); } - await maybeClearRemovedRuntimeTransportHints({ - replacedStoredRuntime: runtimeHintPlan.replacedStoredRuntime, - previousRuntime: runtimeHintPlan.previousRuntime, - previousRuntimeAppId: runtimeHintPlan.previousRuntimeAppId, - runtime: runtimeHintPlan.runtime, - session: existingSession, - clearRuntimeHints, - }); + await maybeClearRemovedRuntimeTransportHints({ ...policy, clearRuntimeHints }); + const applied = replacedAppliedRuntimeTransport(policy); + if (applied) replacedRuntimeHints = { applied, clear: clearRuntimeHints }; } return { @@ -226,9 +236,10 @@ export async function prepareOpenCommandDetails(params: { ? runtimeHintPlan.runtime : storedRuntimeHintsForApp( runtimeHintPlan.runtime, - runtimeHintPlan.previousRuntimeAppId, + runtimeHintPlan.previous?.appId, appBundleId, ), + replacedRuntimeHints, }, }; } diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts index 0b3e7173da..a190180407 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts @@ -346,6 +346,7 @@ async function handleOpenCommand(params: SessionOpenCommandInput): Promise; -}): Promise { - if (!shouldClearRemovedRuntimeTransportHints(params)) return; - await params.clearRuntimeHints(removedRuntimeHintsClearInput(params)); +}>; + +/** Stored hints that an open applied to an app; that app keeps their native transport. */ +export type AppliedRuntimeHints = StoredRuntimeHints & Readonly<{ appId: string }>; + +/** + * An open without transport hints removes the transport of the stored hints it replaces before it + * launches. + */ +function clearsRemovedRuntimeTransportBeforeOpen(params: RemovedRuntimeHintsPolicyInput): boolean { + return ( + params.replacedStoredRuntime && + !hasRuntimeTransportHints(params.runtime) && + requiresRuntimeHintsClear(removedRuntimeHintsClearInput(params)) + ); } -/** Daemon session policy decides whether an open must remove its previous native transport. */ -export function shouldClearRemovedRuntimeTransportHints( - params: Readonly<{ - replacedStoredRuntime: boolean; - previousRuntime: SessionRuntimeHints | undefined; - previousRuntimeAppId: string | undefined; - runtime: SessionRuntimeHints | undefined; - session: SessionState | undefined; - }>, +/** The applied hints that this open replaces with new transport hints. */ +export function replacedAppliedRuntimeTransport( + params: RemovedRuntimeHintsPolicyInput, +): AppliedRuntimeHints | undefined { + const { previous } = params; + if (!params.replacedStoredRuntime || previous?.appId === undefined) return undefined; + if (!hasRuntimeTransportHints(previous.hints) || !hasRuntimeTransportHints(params.runtime)) { + return undefined; + } + return { hints: previous.hints, appId: previous.appId }; +} + +/** + * Whether an open may have to remove the native transport of the stored hints it replaces. + * Admission runs before the open resolves its app, so it admits the clear for replaced applied + * hints whichever app the open reaches. + */ +export function mayClearRemovedRuntimeTransportHints( + params: RemovedRuntimeHintsPolicyInput, ): boolean { return ( - params.replacedStoredRuntime && - requiresRuntimeHintsClear(removedRuntimeHintsClearInput(params)) && - !hasRuntimeTransportHints(params.runtime) + clearsRemovedRuntimeTransportBeforeOpen(params) || + replacedAppliedRuntimeTransport(params) !== undefined ); } +export async function maybeClearRemovedRuntimeTransportHints( + params: RemovedRuntimeHintsPolicyInput & + Readonly<{ clearRuntimeHints(input: RuntimeHintsApplicationInput): Promise }>, +): Promise { + if (!clearsRemovedRuntimeTransportBeforeOpen(params)) return; + await params.clearRuntimeHints(removedRuntimeHintsClearInput(params)); +} + function removedRuntimeHintsClearInput( - params: Readonly<{ - previousRuntime: SessionRuntimeHints | undefined; - previousRuntimeAppId: string | undefined; - session: SessionState | undefined; - }>, + params: Pick, ): RuntimeHintsApplicationInput { - return runtimeHintsClearInput( - params.previousRuntime && { hints: params.previousRuntime, appId: params.previousRuntimeAppId }, - params.session?.appBundleId, - ); + return runtimeHintsClearInput(params.previous, params.session?.appBundleId); } /** Clearing stored hints targets the app they are bound to, else the session's current app. */ diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 9629884733..558845b7c7 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -236,7 +236,7 @@ Exact behavior: `agent-device help close`. - `open --wait ` waits for a device that another session holds. A claim held by another workspace is not waited for: `open` returns the recovery command at once. `install` and `reinstall` never wait. - If an app on an iOS simulator shows an empty accessibility tree after an earlier XCTest session, run `open --relaunch`, then `snapshot -i`. - Android React Native: `open --relaunch` needs an installed package name, not an APK path. For Metro-served JS changes, run `metro reload` instead. -- `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url` apply to the app that `open` opens. A later `open` without these flags applies them again only when it opens the same app. It opens another app, such as a system app, without them. +- `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url` apply to the app that `open` opens. A later `open` without these flags applies them again only when it opens the same app. It opens another app, such as a system app, without them. An `open` that passes these flags for another app also removes the earlier hints from the app an earlier `open` applied them to. - 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.