From ce36ce4c69ce0945c73a42c89c7f5e85b847052b Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 18:23:05 +0530 Subject: [PATCH 1/5] refactor(daemon): read stored runtime hints through one session store accessor SessionStore had getRuntimeHints for the hints and getStoredRuntimeHints for the same map entry with its bound app. getRuntimeHints now returns the stored entry, and callers that need only the hints read its hints field. --- .../__tests__/session-store-lifetime.test.ts | 2 +- packages/daemon/src/core/session-store.ts | 6 +--- .../daemon-runtime-lifecycle-shutdown.test.ts | 4 +-- .../daemon/src/server/http/daemon-runtime.ts | 2 +- .../http/daemon-session-idle-expiry.test.ts | 2 +- .../daemon/src/server/http/server-shutdown.ts | 2 +- .../src/server/request-execution-scope.ts | 2 +- .../request-recording-health.test.ts | 2 +- .../__tests__/session-runtime-command.test.ts | 4 +-- .../handlers/session-replay-command.ts | 2 +- .../handlers/session-runtime-command.ts | 32 ++++++++----------- .../session-close-lifecycle-runtime.test.ts | 2 +- .../session-close-resource-cleanup.test.ts | 2 +- .../session-open-execution-runtime.test.ts | 10 +++--- .../__tests__/session-open-runtime.test.ts | 10 +++--- .../session-close-lifecycle-teardown.ts | 2 +- .../internal/session-close.ts | 5 +-- .../internal/session-open-execution.ts | 4 +-- .../internal/session-open-prepare.ts | 2 +- .../daemon/src/sessions/session-runtime.ts | 8 ++--- 20 files changed, 47 insertions(+), 58 deletions(-) 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..7113dc424f 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 @@ -316,8 +316,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 +350,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 +384,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 () => { 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..739651365e 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, @@ -267,7 +267,7 @@ export async function completeOpenCommand(params: { appName?: string; surface: SessionSurface; appBundleId?: string; - runtimeHints: ReturnType; + runtimeHints: SessionRuntimeHints | undefined; lifecycle: OpenApplicationRuntime; applyRuntimeHints?: RuntimeHintApplyOperation; existingRef?: SessionRef; 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..16bf024b49 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 @@ -124,7 +124,7 @@ export function resolveOpenRuntimeHintPlan(params: { 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 previousRuntimeAppId = params.sessionStore.getRuntimeHints(params.sessionName)?.appId; return { type: 'plan', plan: { diff --git a/packages/daemon/src/sessions/session-runtime.ts b/packages/daemon/src/sessions/session-runtime.ts index e421f0e3c4..57a610b441 100644 --- a/packages/daemon/src/sessions/session-runtime.ts +++ b/packages/daemon/src/sessions/session-runtime.ts @@ -242,8 +242,8 @@ export function bindStoredRuntimeHintsToApp( sessionName: string, appId: string | undefined, ): void { - const runtime = sessionStore.getRuntimeHints(sessionName); - if (runtime && appId) sessionStore.setRuntimeHints(sessionName, runtime, appId); + const stored = sessionStore.getRuntimeHints(sessionName); + if (stored && appId) sessionStore.setRuntimeHints(sessionName, stored.hints, appId); } /** Stored hints apply to the app they are bound to, or to any app while they are unbound. */ @@ -261,7 +261,7 @@ function resolveSessionRuntimeHints( device?: DeviceInfo, platform?: RuntimePlatform, ): SessionRuntimeHints | undefined { - const runtime = sessionStore.getRuntimeHints(sessionName); + const runtime = sessionStore.getRuntimeHints(sessionName)?.hints; if (!runtime) return undefined; const boundPlatform = device ? publicPlatformString(device) : undefined; const deviceRuntimePlatform = toRuntimePlatform(boundPlatform) ?? platform; @@ -298,7 +298,7 @@ function resolveOpenRuntimeHints(params: { const runtimePlatform = device ? toRuntimePlatform(publicPlatformString(device)) : params.platform; - const previousRuntime = sessionStore.getRuntimeHints(sessionName); + const previousRuntime = sessionStore.getRuntimeHints(sessionName)?.hints; const explicitRuntime = normalizeExplicitRuntimeHints({ runtime: req.runtime, sessionName, From 3d9a1dc35f8ccff2839e343680b7663f7c54a786 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 18:24:22 +0530 Subject: [PATCH 2/5] fix(daemon): bind stored runtime hints to the app id the open resolved An open bound stored hints to the app id its launch outcome reported, but a later open compares the binding with the id it resolves for its target before the launch. When the two differed for the same target, a reopen of the app the hints were applied to opened it without them. The binding now uses the id the open resolved before the launch, the same id the hints were applied to and the one a later open compares. --- .../__tests__/session-open-runtime.test.ts | 52 +++++++++++++++++++ .../internal/session-open-execution.ts | 6 ++- 2 files changed, 56 insertions(+), 2 deletions(-) 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 7113dc424f..6cc5234f68 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(); @@ -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,54 @@ function recordRuntimeHintApplies(): Array<{ appId?: string; host?: string; port return applies; } +test.each([ + { storedBy: 'open flags', runtime: { metroPort: 8081 } }, + { storedBy: 'runtime hints set before the first open', runtime: undefined }, +])( + 'hints stored by $storedBy apply again on a reopen when the open reports another app id', + async ({ runtime }) => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-outcome-id'; + const applies = recordRuntimeHintApplies(); + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + if (!runtime) sessionStore.setRuntimeHints(session, { platform: 'android', metroPort: 8081 }); + // The platform reports the app it saw after the launch, which can differ from the id the + // open resolved for its target before the launch. + const reportsOtherAppId: BindDevice = async (device, use) => { + const binding = await mockBindDeviceRuntime(device, use); + return { + ...binding, + operations: { + ...binding.operations, + openApplication: async (input: OpenApplicationInput) => ({ + ...(await binding.operations.openApplication(input)), + appBundleId: 'com.example.foreground', + }), + }, + }; + }; + for (const hints of [runtime, undefined]) { + const opened = await runSessionCommand( + sessionStore, + { + session, + command: 'open', + positionals: ['com.example.metro'], + 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([ { label: 'an Android emulator', 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 739651365e..71d8455003 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 @@ -440,10 +440,12 @@ export async function completeOpenCommand(params: { sessionStore.clearCloseEffectsUnconfirmed(nextRef); const nextSession = sessionStore.requireCurrent(nextRef); markPostOpenStabilization(nextSession, timing.postOpenObservation, req.flags); + // Bind to the prepared id the hints were applied to, not the outcome's: a later open compares + // the binding with its own prepared id. if (req.runtime !== undefined) { - setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints, sessionAppBundleId); + setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints, appBundleId); } else if (runtimeHints) { - bindStoredRuntimeHintsToApp(sessionStore, sessionName, sessionAppBundleId); + bindStoredRuntimeHintsToApp(sessionStore, sessionName, appBundleId); } applyOrdinaryScriptRecordingOpenOutcome({ session: nextSession, From 8ff2ad6439d189c4155b3ef694580053eac7c0f6 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 18:28:48 +0530 Subject: [PATCH 3/5] fix(daemon): clear replaced runtime hints from the app they were bound to An open with new transport hints for another app stored the new hints for that app and rebound them, but left the old hints written in the app they had been applied to. Nothing cleared them later: close and runtime clear target the app the stored hints are bound to. When an open replaces hints bound to another app, it now clears them from that app before it applies the new ones, through the open plan that admits both the apply and the clear operation. Reopening the same app with new hints writes over the old ones without a clear, and hints that no open applied are not cleared. The open plan carries the stored hints with their app as one value. --- .../command-surface/src/management/app.ts | 4 +- .../__tests__/session-open-runtime.test.ts | 79 +++++++++++++++++++ .../internal/session-open-prepare.ts | 30 +++---- .../daemon/src/sessions/session-runtime.ts | 67 ++++++++-------- website/docs/docs/commands.md | 2 +- 5 files changed, 128 insertions(+), 54 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 92b4bd5905..0b9c4cadda 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 with new hints for another app first clears the old hints from the app they were set for. 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 with new hints for another app first clears the old hints from the app they were set for. 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/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 6cc5234f68..186a8f8582 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 @@ -660,3 +660,82 @@ test.each([ ); }, ); + +test.each([ + { + reopened: 'another app', + target: 'com.example.other', + effects: [ + 'apply com.example.metro 8081', + 'clear com.example.metro 8081', + 'apply com.example.other 8082', + ], + }, + { + reopened: 'the same app', + target: 'com.example.metro', + effects: ['apply com.example.metro 8081', 'apply com.example.metro 8082'], + }, +])( + 'an open with new hints for $reopened clears the replaced hints only from a different app', + async ({ target, effects }) => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-replaced-for-another-app'; + const recorded: string[] = []; + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + mockApplyRuntimeHints.mockImplementation(async ({ appId, values }) => { + recorded.push(`apply ${appId} ${values.metroPort}`); + }); + mockClearRuntimeHints.mockImplementation(async ({ appId, values }) => { + recorded.push(`clear ${appId} ${values.metroPort}`); + }); + + for (const [app, metroPort] of [ + ['com.example.metro', 8081], + [target, 8082], + ] as const) { + const opened = await runSessionCommand(sessionStore, { + session, + command: 'open', + positionals: [app], + flags: { platform: 'android' }, + runtime: { metroPort }, + }); + expect(opened.ok).toBe(true); + } + + expect(recorded).toEqual(effects); + expect(sessionStore.getRuntimeHints(session)).toMatchObject({ + appId: target, + hints: { metroPort: 8082 }, + }); + }, +); + +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-open-prepare.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts index 16bf024b49..4c1660977d 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,13 @@ 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 { hasRuntimeTransportHints, + mayClearRemovedRuntimeTransportHints, maybeClearRemovedRuntimeTransportHints, RUNTIME_HINTS_REASONS, - shouldClearRemovedRuntimeTransportHints, storedRuntimeHintsForApp, tryResolveOpenRuntimeHints, } from '../../session-runtime.ts'; @@ -36,12 +36,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 +122,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.getRuntimeHints(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, }), @@ -209,10 +205,10 @@ export async function prepareOpenCommandDetails(params: { } await maybeClearRemovedRuntimeTransportHints({ replacedStoredRuntime: runtimeHintPlan.replacedStoredRuntime, - previousRuntime: runtimeHintPlan.previousRuntime, - previousRuntimeAppId: runtimeHintPlan.previousRuntimeAppId, + previous: runtimeHintPlan.previous, runtime: runtimeHintPlan.runtime, session: existingSession, + appId: appBundleId, clearRuntimeHints, }); } @@ -226,7 +222,7 @@ export async function prepareOpenCommandDetails(params: { ? runtimeHintPlan.runtime : storedRuntimeHintsForApp( runtimeHintPlan.runtime, - runtimeHintPlan.previousRuntimeAppId, + runtimeHintPlan.previous?.appId, appBundleId, ), }, diff --git a/packages/daemon/src/sessions/session-runtime.ts b/packages/daemon/src/sessions/session-runtime.ts index 57a610b441..4f48cd73e9 100644 --- a/packages/daemon/src/sessions/session-runtime.ts +++ b/packages/daemon/src/sessions/session-runtime.ts @@ -256,12 +256,11 @@ export function storedRuntimeHintsForApp( } function resolveSessionRuntimeHints( - sessionStore: SessionRuntimeHintsStore, + runtime: SessionRuntimeHints | undefined, sessionName: string, device?: DeviceInfo, platform?: RuntimePlatform, ): SessionRuntimeHints | undefined { - const runtime = sessionStore.getRuntimeHints(sessionName)?.hints; if (!runtime) return undefined; const boundPlatform = device ? publicPlatformString(device) : undefined; const deviceRuntimePlatform = toRuntimePlatform(boundPlatform) ?? platform; @@ -291,14 +290,14 @@ function resolveOpenRuntimeHints(params: { platform?: RuntimePlatform; }): { runtime: SessionRuntimeHints | undefined; - previousRuntime: SessionRuntimeHints | undefined; + previous: StoredRuntimeHints | undefined; replacedStoredRuntime: boolean; } { const { req, sessionStore, sessionName, device } = params; const runtimePlatform = device ? toRuntimePlatform(publicPlatformString(device)) : params.platform; - const previousRuntime = sessionStore.getRuntimeHints(sessionName)?.hints; + const previous = sessionStore.getRuntimeHints(sessionName); const explicitRuntime = normalizeExplicitRuntimeHints({ runtime: req.runtime, sessionName, @@ -306,14 +305,14 @@ function resolveOpenRuntimeHints(params: { }); if (req.runtime === undefined) { const storedRuntime = resolveSessionRuntimeHints( - sessionStore, + previous?.hints, sessionName, device, runtimePlatform, ); return { runtime: device ? applyDeviceDefaultMetroHost(storedRuntime, device) : storedRuntime, - previousRuntime, + previous, replacedStoredRuntime: false, }; } @@ -323,7 +322,7 @@ function resolveOpenRuntimeHints(params: { : undefined; return { runtime: device ? applyDeviceDefaultMetroHost(selectedRuntime, device) : selectedRuntime, - previousRuntime, + previous, replacedStoredRuntime: true, }; } @@ -348,46 +347,46 @@ export function tryResolveOpenRuntimeHints( } } -export async function maybeClearRemovedRuntimeTransportHints(params: { +type RemovedRuntimeHintsPolicyInput = Readonly<{ replacedStoredRuntime: boolean; - previousRuntime: SessionRuntimeHints | undefined; - previousRuntimeAppId: string | undefined; + previous: StoredRuntimeHints | undefined; runtime: SessionRuntimeHints | undefined; session: SessionState | undefined; - clearRuntimeHints(input: RuntimeHintsApplicationInput): Promise; -}): Promise { - if (!shouldClearRemovedRuntimeTransportHints(params)) return; - await params.clearRuntimeHints(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; - }>, +/** + * 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 new transport hints admit the clear whenever + * the replaced hints are bound to an app. + */ +export function mayClearRemovedRuntimeTransportHints( + params: RemovedRuntimeHintsPolicyInput, ): boolean { return ( params.replacedStoredRuntime && requiresRuntimeHintsClear(removedRuntimeHintsClearInput(params)) && - !hasRuntimeTransportHints(params.runtime) + (!hasRuntimeTransportHints(params.runtime) || params.previous?.appId !== undefined) ); } +/** New transport hints overwrite the replaced ones on their bound app; another app is cleared. */ +export async function maybeClearRemovedRuntimeTransportHints( + params: RemovedRuntimeHintsPolicyInput & + Readonly<{ + /** The app this open resolved for its target. */ + appId: string | undefined; + clearRuntimeHints(input: RuntimeHintsApplicationInput): Promise; + }>, +): Promise { + if (!mayClearRemovedRuntimeTransportHints(params)) return; + if (hasRuntimeTransportHints(params.runtime) && params.previous?.appId === params.appId) 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..7fdde38cae 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` with new flags for another app first clears the old hints from the app they were set for. - 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. From c083dc7c3a5918cf2bf26a0d82fc7b5531506111 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 19:39:28 +0530 Subject: [PATCH 4/5] fix(daemon): clear replaced runtime hints after the launch, only when they change Three gaps in how an open rebinds and clears stored hints: - An open whose target resolves to no app id before the launch, such as a deep link with no current app, left the hints unbound, so a later open of another app applied them again. The binding now falls back to the app the launch reports. - The clear of the previous app ran before the new app's launch. When the apply or the launch failed, the previous app lost its hints while the session still bound them to it. The clear now runs after the launch succeeds, before the binding moves. An open without transport hints still clears before its launch. - A connection that attaches the same runtime hints to every request made each app switch clear the previous app. Identical transport hints leave nothing stale there, so only different hints clear it. --- .../command-surface/src/management/app.ts | 4 +- .../src/application-lifecycle-runtime.ts | 8 + .../__tests__/session-open-runtime.test.ts | 191 +++++++++++++----- .../internal/session-open-execution.ts | 20 +- .../internal/session-open-prepare.ts | 31 ++- .../internal/session-open.ts | 1 + .../daemon/src/sessions/session-runtime.ts | 53 +++-- website/docs/docs/commands.md | 2 +- 8 files changed, 231 insertions(+), 79 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 0b9c4cadda..fc09e27600 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. An open with new hints for another app first clears the old hints from the app they were set for. 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 different hints for another app also removes the earlier ones 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. An open with new hints for another app first clears the old hints from the app they were set for. 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 different hints for another app also removes the earlier ones 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..c8c444cea1 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -26,6 +26,14 @@ export function hasRuntimeTransportHintValues(values: RuntimeHintValues): boolea return RUNTIME_TRANSPORT_HINT_KEYS.some((key) => values[key] !== undefined); } +/** True when both payloads name the same bundle transport. */ +export function sameRuntimeTransportHintValues( + left: RuntimeHintValues, + right: RuntimeHintValues, +): boolean { + return RUNTIME_TRANSPORT_HINT_KEYS.every((key) => left[key] === right[key]); +} + /** Request-scoped runner/diagnostic context, without daemon request types. */ export type ApplicationLifecycleExecution = Readonly<{ /** 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 186a8f8582..2d89ca926a 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 @@ -454,6 +454,23 @@ 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 } }, { storedBy: 'runtime hints set before the first open', runtime: undefined }, @@ -465,21 +482,7 @@ test.each([ const applies = recordRuntimeHintApplies(); mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); if (!runtime) sessionStore.setRuntimeHints(session, { platform: 'android', metroPort: 8081 }); - // The platform reports the app it saw after the launch, which can differ from the id the - // open resolved for its target before the launch. - const reportsOtherAppId: BindDevice = async (device, use) => { - const binding = await mockBindDeviceRuntime(device, use); - return { - ...binding, - operations: { - ...binding.operations, - openApplication: async (input: OpenApplicationInput) => ({ - ...(await binding.operations.openApplication(input)), - appBundleId: 'com.example.foreground', - }), - }, - }; - }; + const reportsOtherAppId = bindReportingOpenedApp('com.example.foreground'); for (const hints of [runtime, undefined]) { const opened = await runSessionCommand( sessionStore, @@ -502,6 +505,39 @@ test.each([ }, ); +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', @@ -661,57 +697,110 @@ 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([ { - reopened: 'another app', - target: 'com.example.other', + opened: 'another app with different hints', + first: undefined, + second: { target: 'com.example.other', metroPort: 8082 }, effects: [ 'apply com.example.metro 8081', - 'clear com.example.metro 8081', 'apply com.example.other 8082', + 'clear com.example.metro 8081', ], }, { - reopened: 'the same app', - target: 'com.example.metro', + 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'], + }, + { + 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 with new hints for $reopened clears the replaced hints only from a different app', - async ({ target, effects }) => { - const sessionStore = makeSessionStore(); - const session = 'runtime-hints-replaced-for-another-app'; - const recorded: string[] = []; - mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); - mockApplyRuntimeHints.mockImplementation(async ({ appId, values }) => { - recorded.push(`apply ${appId} ${values.metroPort}`); - }); - mockClearRuntimeHints.mockImplementation(async ({ appId, values }) => { - recorded.push(`clear ${appId} ${values.metroPort}`); - }); - - for (const [app, metroPort] of [ - ['com.example.metro', 8081], - [target, 8082], - ] as const) { - const opened = await runSessionCommand(sessionStore, { - session, - command: 'open', - positionals: [app], - flags: { platform: 'android' }, - runtime: { metroPort }, - }); - expect(opened.ok).toBe(true); - } - - expect(recorded).toEqual(effects); - expect(sessionStore.getRuntimeHints(session)).toMatchObject({ - appId: target, - hints: { metroPort: 8082 }, + 'an open of $opened clears the replaced hints only when they differ on 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('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'; 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 71d8455003..923f7746dc 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 @@ -45,6 +45,7 @@ import { bindStoredRuntimeHintsToApp, countConfiguredRuntimeHints, openApplicationRuntimeHints, + runtimeHintsClearInput, setSessionRuntimeHintsForOpen, } from '../../session-runtime.ts'; import { STARTUP_SAMPLE_METHOD, type StartupPerfSample } from './session-startup-metrics.ts'; @@ -57,6 +58,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'; @@ -268,6 +270,7 @@ export async function completeOpenCommand(params: { surface: SessionSurface; appBundleId?: string; runtimeHints: SessionRuntimeHints | undefined; + replacedRuntimeHints?: ReplacedRuntimeHints; lifecycle: OpenApplicationRuntime; applyRuntimeHints?: RuntimeHintApplyOperation; existingRef?: SessionRef; @@ -288,6 +291,7 @@ export async function completeOpenCommand(params: { surface, appBundleId, runtimeHints, + replacedRuntimeHints, lifecycle, applyRuntimeHints, existingRef, @@ -351,6 +355,10 @@ export async function completeOpenCommand(params: { throw error; }); sessionAppBundleId = outcome.appBundleId ?? sessionAppBundleId; + // The hints were applied to the prepared id, and a later open compares the binding with the id + // it prepares. Without a prepared id, as for a deep link with no current app, the app the launch + // reports is the one a later open names. + const runtimeHintsAppId = appBundleId ?? outcome.appBundleId; const timing: OpenTiming = { ...outcome.timing }; const preparedSelection = markSelectionBootOccurred(selection); const startupSample = openTarget @@ -366,6 +374,11 @@ export async function completeOpenCommand(params: { } requireOpenSessionAdmission(sessionStore, sessionName, openDispatchRef); + if (replacedRuntimeHints && replacedRuntimeHints.applied.appId !== runtimeHintsAppId) { + await replacedRuntimeHints.clear( + runtimeHintsClearInput(replacedRuntimeHints.applied, undefined), + ); + } if (existingRef) { markDeferredInteractionOutcome({ session: sessionStore.requireCurrent(existingRef), @@ -440,12 +453,10 @@ export async function completeOpenCommand(params: { sessionStore.clearCloseEffectsUnconfirmed(nextRef); const nextSession = sessionStore.requireCurrent(nextRef); markPostOpenStabilization(nextSession, timing.postOpenObservation, req.flags); - // Bind to the prepared id the hints were applied to, not the outcome's: a later open compares - // the binding with its own prepared id. if (req.runtime !== undefined) { - setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints, appBundleId); + setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints, runtimeHintsAppId); } else if (runtimeHints) { - bindStoredRuntimeHintsToApp(sessionStore, sessionName, appBundleId); + bindStoredRuntimeHintsToApp(sessionStore, sessionName, runtimeHintsAppId); } applyOrdinaryScriptRecordingOpenOutcome({ session: nextSession, @@ -641,6 +652,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 4c1660977d..2472cf75c9 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 @@ -9,9 +9,11 @@ import type { SessionRuntimeHints, SessionState } from '../../../core/session-st 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, storedRuntimeHintsForApp, tryResolveOpenRuntimeHints, @@ -25,8 +27,18 @@ type OpenCommandDetails = { appBundleId?: string; appName?: string; runtime: SessionRuntimeHints | undefined; + replacedRuntimeHints?: ReplacedRuntimeHints; }; +/** + * Applied hints that this open replaces with a different transport, 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 }; @@ -189,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 @@ -203,14 +222,9 @@ export async function prepareOpenCommandDetails(params: { }, ); } - await maybeClearRemovedRuntimeTransportHints({ - replacedStoredRuntime: runtimeHintPlan.replacedStoredRuntime, - previous: runtimeHintPlan.previous, - runtime: runtimeHintPlan.runtime, - session: existingSession, - appId: appBundleId, - clearRuntimeHints, - }); + await maybeClearRemovedRuntimeTransportHints({ ...policy, clearRuntimeHints }); + const applied = replacedAppliedRuntimeTransport(policy); + if (applied) replacedRuntimeHints = { applied, clear: clearRuntimeHints }; } return { @@ -225,6 +239,7 @@ export async function prepareOpenCommandDetails(params: { 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; +/** 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)) + ); +} + +/** + * The applied hints that this open replaces with a different transport. Identical transport hints + * leave nothing stale on the app they were applied to. + */ +export function replacedAppliedRuntimeTransport( + params: RemovedRuntimeHintsPolicyInput, +): AppliedRuntimeHints | undefined { + const { previous, runtime } = params; + if (!params.replacedStoredRuntime || previous?.appId === undefined) return undefined; + const previousValues = runtimeHintValues(previous.hints); + const values = runtimeHintValues(runtime); + if (!hasRuntimeTransportHintValues(previousValues) || !hasRuntimeTransportHintValues(values)) { + return undefined; + } + if (sameRuntimeTransportHintValues(previousValues, values)) 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 new transport hints admit the clear whenever - * the replaced hints are bound to an app. + * 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) || params.previous?.appId !== undefined) + clearsRemovedRuntimeTransportBeforeOpen(params) || + replacedAppliedRuntimeTransport(params) !== undefined ); } -/** New transport hints overwrite the replaced ones on their bound app; another app is cleared. */ export async function maybeClearRemovedRuntimeTransportHints( params: RemovedRuntimeHintsPolicyInput & - Readonly<{ - /** The app this open resolved for its target. */ - appId: string | undefined; - clearRuntimeHints(input: RuntimeHintsApplicationInput): Promise; - }>, + Readonly<{ clearRuntimeHints(input: RuntimeHintsApplicationInput): Promise }>, ): Promise { - if (!mayClearRemovedRuntimeTransportHints(params)) return; - if (hasRuntimeTransportHints(params.runtime) && params.previous?.appId === params.appId) return; + if (!clearsRemovedRuntimeTransportBeforeOpen(params)) return; await params.clearRuntimeHints(removedRuntimeHintsClearInput(params)); } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 7fdde38cae..9095862f6f 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. An `open` with new flags for another app first clears the old hints from the app they were set for. +- `--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 different 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. From a666d77c1f1046f1aba44aa98c65af9d56fe0de0 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 21:47:39 +0530 Subject: [PATCH 5/5] fix(daemon): keep native runtime hints only on the app the open bound them to - After a successful open that applies hints to another app, the open now clears the previously bound app whatever the values are. Identical hints left that app holding native hints with no binding left to clear them. - The session and the hint binding now take one app id: the prepared id, else the id the launch reports. Every platform reports the prepared id back when there is one, and Android fills one in only for a target without it. A later deep-link or targetless open resolves from the session id, so it now compares the same id the binding holds. - A failed removal from the replaced app no longer fails an open that already launched. The open reports it as a warning and binds the new hints. --- .../command-surface/src/management/app.ts | 4 +- .../src/application-lifecycle-runtime.ts | 9 +-- .../__tests__/session-open-runtime.test.ts | 55 ++++++++++++++++--- .../internal/session-open-execution.ts | 48 ++++++++++++---- .../internal/session-open-prepare.ts | 2 +- .../daemon/src/sessions/session-runtime.ts | 13 +---- website/docs/docs/commands.md | 2 +- 7 files changed, 91 insertions(+), 42 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index fc09e27600..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. An open that passes different hints for another app also removes the earlier ones 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.', + '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. An open that passes different hints for another app also removes the earlier ones 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.", + "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 c8c444cea1..9622133a2e 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -26,14 +26,6 @@ export function hasRuntimeTransportHintValues(values: RuntimeHintValues): boolea return RUNTIME_TRANSPORT_HINT_KEYS.some((key) => values[key] !== undefined); } -/** True when both payloads name the same bundle transport. */ -export function sameRuntimeTransportHintValues( - left: RuntimeHintValues, - right: RuntimeHintValues, -): boolean { - return RUNTIME_TRANSPORT_HINT_KEYS.every((key) => left[key] === right[key]); -} - /** Request-scoped runner/diagnostic context, without daemon request types. */ export type ApplicationLifecycleExecution = Readonly<{ /** @@ -268,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/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 2d89ca926a..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 @@ -472,24 +472,32 @@ function bindReportingOpenedApp(appBundleId: string): BindDevice { } test.each([ - { storedBy: 'open flags', runtime: { metroPort: 8081 } }, - { storedBy: 'runtime hints set before the first open', runtime: undefined }, + { 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 when the open reports another app id', - async ({ runtime }) => { + '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 hints of [runtime, undefined]) { + for (const [target, hints] of [ + ['com.example.metro', runtime], + [reopen, undefined], + ] as const) { const opened = await runSessionCommand( sessionStore, { session, command: 'open', - positionals: ['com.example.metro'], + positionals: [target], flags: { platform: 'android' }, ...(hints ? { runtime: hints } : {}), }, @@ -745,7 +753,11 @@ test.each([ 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'], + effects: [ + 'apply com.example.metro 8081', + 'apply com.example.other 8081', + 'clear com.example.metro 8081', + ], }, { opened: 'the same app with different hints', @@ -760,7 +772,7 @@ test.each([ effects: ['apply com.example.other 8082'], }, ])( - 'an open of $opened clears the replaced hints only when they differ on another app', + '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); @@ -773,6 +785,33 @@ test.each([ }, ); +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); 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 923f7746dc..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 @@ -36,6 +36,7 @@ import { import { isRequestCanceled } from '@agent-device/host-kit/request'; import { AppError, + asAppError, createRequestCanceledError, readDispatchDisclosure, type ReasonTable, @@ -139,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, @@ -354,11 +379,10 @@ export async function completeOpenCommand(params: { if (!effectsConfirmedOrUndispatched) markUnconfirmedRelaunch(); throw error; }); - sessionAppBundleId = outcome.appBundleId ?? sessionAppBundleId; - // The hints were applied to the prepared id, and a later open compares the binding with the id - // it prepares. Without a prepared id, as for a deep link with no current app, the app the launch - // reports is the one a later open names. - const runtimeHintsAppId = appBundleId ?? outcome.appBundleId; + // 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 @@ -374,11 +398,10 @@ export async function completeOpenCommand(params: { } requireOpenSessionAdmission(sessionStore, sessionName, openDispatchRef); - if (replacedRuntimeHints && replacedRuntimeHints.applied.appId !== runtimeHintsAppId) { - await replacedRuntimeHints.clear( - runtimeHintsClearInput(replacedRuntimeHints.applied, undefined), - ); - } + const replacedRuntimeHintsWarning = await clearReplacedRuntimeHints( + replacedRuntimeHints, + sessionAppBundleId, + ); if (existingRef) { markDeferredInteractionOutcome({ session: sessionStore.requireCurrent(existingRef), @@ -421,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, @@ -454,9 +478,9 @@ export async function completeOpenCommand(params: { const nextSession = sessionStore.requireCurrent(nextRef); markPostOpenStabilization(nextSession, timing.postOpenObservation, req.flags); if (req.runtime !== undefined) { - setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints, runtimeHintsAppId); + setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints, sessionAppBundleId); } else if (runtimeHints) { - bindStoredRuntimeHintsToApp(sessionStore, sessionName, runtimeHintsAppId); + bindStoredRuntimeHintsToApp(sessionStore, sessionName, sessionAppBundleId); } applyOrdinaryScriptRecordingOpenOutcome({ session: nextSession, 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 2472cf75c9..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 @@ -31,7 +31,7 @@ type OpenCommandDetails = { }; /** - * Applied hints that this open replaces with a different transport, paired with the admitted clear. + * 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<{ diff --git a/packages/daemon/src/sessions/session-runtime.ts b/packages/daemon/src/sessions/session-runtime.ts index 9cbb9eaef9..0781dc0364 100644 --- a/packages/daemon/src/sessions/session-runtime.ts +++ b/packages/daemon/src/sessions/session-runtime.ts @@ -4,7 +4,6 @@ import { type RuntimeHintValues, type RuntimeHintsApplicationInput, hasRuntimeTransportHintValues, - sameRuntimeTransportHintValues, } from '@agent-device/contracts/application-lifecycle-runtime'; import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/errors'; import { @@ -370,21 +369,15 @@ function clearsRemovedRuntimeTransportBeforeOpen(params: RemovedRuntimeHintsPoli ); } -/** - * The applied hints that this open replaces with a different transport. Identical transport hints - * leave nothing stale on the app they were applied to. - */ +/** The applied hints that this open replaces with new transport hints. */ export function replacedAppliedRuntimeTransport( params: RemovedRuntimeHintsPolicyInput, ): AppliedRuntimeHints | undefined { - const { previous, runtime } = params; + const { previous } = params; if (!params.replacedStoredRuntime || previous?.appId === undefined) return undefined; - const previousValues = runtimeHintValues(previous.hints); - const values = runtimeHintValues(runtime); - if (!hasRuntimeTransportHintValues(previousValues) || !hasRuntimeTransportHintValues(values)) { + if (!hasRuntimeTransportHints(previous.hints) || !hasRuntimeTransportHints(params.runtime)) { return undefined; } - if (sameRuntimeTransportHintValues(previousValues, values)) return undefined; return { hints: previous.hints, appId: previous.appId }; } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 9095862f6f..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. An `open` that passes different flags for another app also removes the earlier hints from the app an earlier `open` applied them to. +- `--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.