From 7df289959560d05e678be2ff30839b232b43f03e Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 12:26:19 +0530 Subject: [PATCH 1/2] fix(daemon): apply stored runtime hints only to the app they were set for An open with --metro-port, --metro-host, --bundle-url or --launch-url stored the hints for the session without the app they were for. Every later open without runtime flags re-applied them to whatever app it opened: on Android the run-as write into a non-debuggable app such as Photos or the launcher failed the open, and on an iOS simulator it wrote RCT_jsLocation into the other app's defaults and followed up with the first app's launch URL. The session store now binds stored hints to the app an open applied them to. A later open without runtime flags applies them only when it opens that app; another app opens without them. Hints stored before any open bind to the first app that applies them, and runtime set keeps the binding. --- .../command-surface/src/management/app.ts | 4 +- packages/daemon/src/core/session-store.ts | 15 +- .../handlers/session-runtime-command.ts | 6 +- .../__tests__/session-open-runtime.test.ts | 143 ++++++++++++++++++ .../internal/session-open-execution.ts | 8 +- .../internal/session-open-prepare.ts | 12 +- .../daemon/src/sessions/session-runtime.ts | 22 ++- website/docs/docs/commands.md | 1 + 8 files changed, 200 insertions(+), 11 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 0a55ef9401..92b4bd5905 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. 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. 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 fresh open without Metro hints clears an older same-name binding; close also clears it.", + "metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A later open without hints applies them again only when it opens the same app; it opens another app without them. A fresh open without Metro hints clears an older same-name binding; close also clears it.", }, metadata: openCommandMetadata, run: (client, input) => client.apps.open(toAppOpenOptions(input)), diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 404acd0522..8bba4f950e 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -65,11 +65,14 @@ export type RetainedExecutionHost = Readonly<{ lease: NonNullable; }>; +// `appId` is the app an open applied the hints to; it stays absent until an open applies them. +type StoredRuntimeHints = Readonly<{ hints: SessionRuntimeHints; appId?: string }>; + export class SessionStore { private readonly sessions = new Map(); private readonly retainedExecutionHosts = new Map(); private acceptingSessions = true; - private readonly runtimeHints = new Map(); + private readonly runtimeHints = new Map(); private readonly sessionsDir: string; private readonly scriptWriter: SessionScriptWriter; @@ -230,11 +233,15 @@ export class SessionStore { } getRuntimeHints(name: string): SessionRuntimeHints | undefined { - return this.runtimeHints.get(name); + return this.runtimeHints.get(name)?.hints; + } + + getRuntimeHintsAppId(name: string): string | undefined { + return this.runtimeHints.get(name)?.appId; } - setRuntimeHints(address: string, hints: SessionRuntimeHints | undefined): void { - if (hints) this.runtimeHints.set(address, hints); + setRuntimeHints(address: string, hints: SessionRuntimeHints | undefined, appId?: string): void { + if (hints) this.runtimeHints.set(address, { hints, appId }); else this.runtimeHints.delete(address); } diff --git a/packages/daemon/src/sessions/handlers/session-runtime-command.ts b/packages/daemon/src/sessions/handlers/session-runtime-command.ts index 19eb958fe6..5d3a8fc25a 100644 --- a/packages/daemon/src/sessions/handlers/session-runtime-command.ts +++ b/packages/daemon/src/sessions/handlers/session-runtime-command.ts @@ -214,7 +214,11 @@ 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.setRuntimeHints( + sessionName, + nextRuntime, + sessionStore.getRuntimeHintsAppId(sessionName), + ); return { ok: true, data: { 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 47f56ad7fc..1e61129690 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 @@ -2,6 +2,8 @@ import { daemonPlatformServicesFixture } from '../../../../__tests__/support/pla 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 { fakeCreateCommandSurface } from '../../../../__tests__/support/command-surface-fake.ts'; const mockResolveTargetDevice = vi.hoisted(() => vi.fn()); @@ -419,3 +421,144 @@ test('open --relaunch allows Android package names ending with apk-like suffix', expect(dispatchCalls[1]?.command).toBe('open'); expect(dispatchCalls[1]?.positionals).toEqual(['com.example.apk']); }); + +async function runSessionCommand( + sessionStore: ReturnType, + req: Omit, +): Promise { + const response = await handleSessionCommands({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + req: { token: 't', ...req }, + sessionName: req.session!, + logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + }); + if (!response) throw new Error(`${req.command} was not handled`); + return response; +} + +function recordRuntimeHintApplies(): Array<{ appId?: string; host?: string; port?: string }> { + const applies: Array<{ appId?: string; host?: string; port?: string }> = []; + mockApplyRuntimeHints.mockImplementation(async ({ appId, values }) => { + applies.push({ appId, host: values.metroHost, port: values.metroPort }); + }); + return applies; +} + +test.each([ + { + label: 'an Android emulator', + device: makeAndroidEmulator(), + platform: 'android' as const, + host: '10.0.2.2', + otherApp: 'com.google.android.apps.photos', + }, + { + label: 'an iOS simulator', + device: makeAppleSimulator(), + platform: 'ios' as const, + host: '127.0.0.1', + otherApp: 'com.apple.mobileslideshow', + }, +])( + 'open hints apply again only to the app they were set for on $label', + async ({ device, platform, host, otherApp }) => { + const sessionStore = makeSessionStore(); + const session = `runtime-hints-per-app-${platform}`; + const openedTargets: string[][] = []; + const applies = recordRuntimeHintApplies(); + mockResolveTargetDevice.mockResolvedValue(device); + mockDispatch.mockImplementation(async (_device, command, positionals) => { + if (command === 'open') openedTargets.push(positionals); + return {}; + }); + const open = async (target: string, runtime?: DaemonRequest['runtime']) => + await runSessionCommand(sessionStore, { + session, + command: 'open', + positionals: [target], + flags: { platform }, + ...(runtime ? { runtime } : {}), + }); + + const first = await open('com.example.metro', { + metroPort: 8081, + launchUrl: 'metroapp://dev-client', + }); + const other = await open(otherApp); + const again = await open('com.example.metro'); + + expect([first.ok, other.ok, again.ok]).toEqual([true, true, true]); + expect(applies).toEqual([ + { appId: 'com.example.metro', host, port: '8081' }, + { appId: 'com.example.metro', host, port: '8081' }, + ]); + expect(openedTargets).toEqual([ + ['com.example.metro'], + ['metroapp://dev-client'], + [otherApp], + ['com.example.metro'], + ['metroapp://dev-client'], + ]); + expect(other.ok ? other.data?.runtime : 'failed').toBeUndefined(); + expect(again.ok ? again.data?.runtime : 'failed').toMatchObject({ + metroHost: host, + metroPort: 8081, + launchUrl: 'metroapp://dev-client', + }); + }, +); + +test('hints stored before the first open bind to the app that open applied them to', async () => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-bind-on-first-open'; + const applies = recordRuntimeHintApplies(); + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + sessionStore.setRuntimeHints(session, { platform: 'android', metroPort: 8081 }); + + for (const target of ['com.example.metro', 'com.google.android.apps.photos']) { + const response = await runSessionCommand(sessionStore, { + session, + command: 'open', + positionals: [target], + flags: { platform: 'android' }, + }); + expect(response.ok).toBe(true); + } + + expect(applies).toEqual([{ appId: 'com.example.metro', host: '10.0.2.2', port: '8081' }]); +}); + +test('runtime set keeps edited hints bound to the app an open applied them to', async () => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-set-keeps-app'; + 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.example.metro', { metroPort: 8081 }); + const set = await runSessionCommand(sessionStore, { + session, + command: 'runtime', + positionals: ['set'], + flags: { metroPort: 8082 }, + }); + await open('com.google.android.apps.photos'); + await open('com.example.metro'); + + expect(set.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: '8082' }, + ]); +}); 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 252801f809..e83c2b1d9d 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 @@ -42,6 +42,7 @@ import { } from '@agent-device/kernel/errors'; import { SessionStore } from '../../../core/session-store.ts'; import { + bindStoredRuntimeHintsToApp, countConfiguredRuntimeHints, openApplicationRuntimeHints, setSessionRuntimeHintsForOpen, @@ -439,8 +440,11 @@ export async function completeOpenCommand(params: { sessionStore.clearCloseEffectsUnconfirmed(nextRef); const nextSession = sessionStore.requireCurrent(nextRef); markPostOpenStabilization(nextSession, timing.postOpenObservation, req.flags); - if (req.runtime !== undefined) - setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints); + if (req.runtime !== undefined) { + setSessionRuntimeHintsForOpen(sessionStore, sessionName, runtimeHints, sessionAppBundleId); + } else if (runtimeHints) { + bindStoredRuntimeHintsToApp(sessionStore, sessionName, sessionAppBundleId); + } applyOrdinaryScriptRecordingOpenOutcome({ session: nextSession, existingSession: existingRef ? nextSession : undefined, 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 9490802011..146018e159 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 @@ -13,6 +13,7 @@ import { maybeClearRemovedRuntimeTransportHints, RUNTIME_HINTS_REASONS, shouldClearRemovedRuntimeTransportHints, + storedRuntimeHintsForApp, tryResolveOpenRuntimeHints, } from '../../session-runtime.ts'; import { AppError } from '@agent-device/kernel/errors'; @@ -37,6 +38,8 @@ export type ResolvedOpenRuntimeHintPlan = Readonly<{ runtime: SessionRuntimeHints | undefined; previousRuntime: SessionRuntimeHints | undefined; replacedStoredRuntime: boolean; + /** The app the reused stored hints are bound to; absent for explicit or unbound hints. */ + storedRuntimeAppId: string | undefined; applyRuntimeHints: boolean; clearRemovedRuntimeHints: boolean; }>; @@ -125,6 +128,9 @@ export function resolveOpenRuntimeHintPlan(params: { runtime, previousRuntime, replacedStoredRuntime, + storedRuntimeAppId: replacedStoredRuntime + ? undefined + : params.sessionStore.getRuntimeHintsAppId(params.sessionName), applyRuntimeHints: hasRuntimeTransportHints(runtime), clearRemovedRuntimeHints: shouldClearRemovedRuntimeTransportHints({ replacedStoredRuntime, @@ -213,7 +219,11 @@ export async function prepareOpenCommandDetails(params: { details: { appBundleId, appName, - runtime: runtimeHintPlan.runtime, + runtime: storedRuntimeHintsForApp( + runtimeHintPlan.runtime, + runtimeHintPlan.storedRuntimeAppId, + appBundleId, + ), }, }; } diff --git a/packages/daemon/src/sessions/session-runtime.ts b/packages/daemon/src/sessions/session-runtime.ts index d26c85acdc..498149536b 100644 --- a/packages/daemon/src/sessions/session-runtime.ts +++ b/packages/daemon/src/sessions/session-runtime.ts @@ -225,16 +225,36 @@ export function setSessionRuntimeHintsForOpen( sessionStore: SessionStore, sessionName: string, runtime: SessionRuntimeHints | undefined, + appId: string | undefined, ): SessionRuntimeHints | undefined { if (!runtime) return undefined; if (countConfiguredRuntimeHints(runtime) === 0) { sessionStore.setRuntimeHints(sessionName, undefined); return undefined; } - sessionStore.setRuntimeHints(sessionName, runtime); + sessionStore.setRuntimeHints(sessionName, runtime, appId); return runtime; } +/** Binds stored hints that an open applied to the app it opened. */ +export function bindStoredRuntimeHintsToApp( + sessionStore: SessionStore, + sessionName: string, + appId: string | undefined, +): void { + const runtime = sessionStore.getRuntimeHints(sessionName); + if (runtime && appId) sessionStore.setRuntimeHints(sessionName, runtime, appId); +} + +/** Stored hints apply to the app they are bound to, or to any app while they are unbound. */ +export function storedRuntimeHintsForApp( + runtime: SessionRuntimeHints | undefined, + boundAppId: string | undefined, + appId: string | undefined, +): SessionRuntimeHints | undefined { + return boundAppId === undefined || boundAppId === appId ? runtime : undefined; +} + function resolveSessionRuntimeHints( sessionStore: SessionRuntimeHintsStore, sessionName: string, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 18c5f1cc1c..9c415d9821 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -236,6 +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. - 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 91761f668d35cc0168b8bd512c786b5de255f1d4 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 15:08:28 +0530 Subject: [PATCH 2/2] fix(daemon): clear stored runtime hints from the app they are bound to Opening another app no longer re-applies stored hints, so the session app moves on while the hints stay bound to the first app. Every clear path still targeted the session's current app: close, runtime clear, daemon shutdown and idle expiry, and an open with flags but no Metro address. On Android the clear then missed the app that held debug_http_host. Each path now clears the app the stored hints are bound to and falls back to the session app for unbound hints. The session store returns the hints with their app, and the lifecycle finalization takes the clear input with its app id. --- packages/daemon/src/core/session-store.ts | 6 +-- .../application-lifecycle-recovery.test.ts | 14 +++--- .../server/application-lifecycle-recovery.ts | 27 ++++------- .../daemon-runtime-lifecycle-shutdown.test.ts | 14 ++++-- .../daemon/src/server/http/daemon-runtime.ts | 7 ++- .../daemon/src/server/http/server-shutdown.ts | 11 +++-- .../src/server/request-execution-scope.ts | 7 ++- .../handlers/session-runtime-command.ts | 16 +++---- .../__tests__/session-open-runtime.test.ts | 46 +++++++++++++++++++ .../session-close-lifecycle-teardown.ts | 16 ++----- .../internal/session-close.ts | 10 ++-- .../internal/session-open-prepare.ts | 25 ++++++---- .../daemon/src/sessions/session-runtime.ts | 42 ++++++++++++----- 13 files changed, 155 insertions(+), 86 deletions(-) diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 8bba4f950e..3e4fef40c0 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -66,7 +66,7 @@ export type RetainedExecutionHost = Readonly<{ }>; // `appId` is the app an open applied the hints to; it stays absent until an open applies them. -type StoredRuntimeHints = Readonly<{ hints: SessionRuntimeHints; appId?: string }>; +export type StoredRuntimeHints = Readonly<{ hints: SessionRuntimeHints; appId?: string }>; export class SessionStore { private readonly sessions = new Map(); @@ -236,8 +236,8 @@ export class SessionStore { return this.runtimeHints.get(name)?.hints; } - getRuntimeHintsAppId(name: string): string | undefined { - return this.runtimeHints.get(name)?.appId; + getStoredRuntimeHints(name: string): StoredRuntimeHints | undefined { + return this.runtimeHints.get(name); } setRuntimeHints(address: string, hints: SessionRuntimeHints | undefined, appId?: string): void { diff --git a/packages/daemon/src/server/__tests__/application-lifecycle-recovery.test.ts b/packages/daemon/src/server/__tests__/application-lifecycle-recovery.test.ts index 35f1d6a014..db6e559ae6 100644 --- a/packages/daemon/src/server/__tests__/application-lifecycle-recovery.test.ts +++ b/packages/daemon/src/server/__tests__/application-lifecycle-recovery.test.ts @@ -173,7 +173,7 @@ test('daemon lifecycle finalization admits facts once, binds once, and disposes scope: scope(), session, stateDir: '/state', - runtimeHints: { metroHost: '10.0.2.2', metroPort: '8081' }, + runtimeHints: { values: { metroHost: '10.0.2.2', metroPort: '8081' } }, }); expect(runtime.inspectFacts).toHaveBeenCalledTimes(1); @@ -200,7 +200,7 @@ test('a daemon that stays alive finalizes without the shutdown deferral', async scope: scope(), session, stateDir: '/state', - runtimeHints: {}, + runtimeHints: { values: {} }, daemonLeaving: false, }); @@ -272,7 +272,7 @@ test.each([ scope: scope(), session: providerSession, stateDir: '/state', - runtimeHints: {}, + runtimeHints: { values: {} }, }); expect(inspectFacts).toHaveBeenCalledExactlyOnceWith(providerDevice); @@ -297,7 +297,7 @@ test('daemon lifecycle finalization rejects a false fact before binding', async scope: scope(), session, stateDir: '/state', - runtimeHints: {}, + runtimeHints: { values: {} }, }), ).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', @@ -329,7 +329,7 @@ test('daemon lifecycle finalization admits its distinct runtime-hint cleanup bef scope: scope(), session: sessionWithApplication, stateDir: '/state', - runtimeHints, + runtimeHints: { appId: 'com.example.app', values: runtimeHints }, }); expect(runtime.inspectFacts).toHaveBeenCalledTimes(1); @@ -358,7 +358,7 @@ test('daemon lifecycle finalization rejects a false runtime-hint cleanup fact be scope: scope(), session: sessionWithApplication, stateDir: '/state', - runtimeHints: { metroHost: '10.0.2.2' }, + runtimeHints: { appId: 'com.example.app', values: { metroHost: '10.0.2.2' } }, }), ).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', @@ -388,7 +388,7 @@ test('daemon lifecycle finalization keeps an operation failure primary over bind scope: scope(events), session, stateDir: '/state', - runtimeHints: {}, + runtimeHints: { values: {} }, }), ).rejects.toBe(operationFailure); diff --git a/packages/daemon/src/server/application-lifecycle-recovery.ts b/packages/daemon/src/server/application-lifecycle-recovery.ts index ff5910371d..d18e057960 100644 --- a/packages/daemon/src/server/application-lifecycle-recovery.ts +++ b/packages/daemon/src/server/application-lifecycle-recovery.ts @@ -1,7 +1,4 @@ -import { - type RuntimeHintValues, - hasRuntimeTransportHintValues, -} from '@agent-device/contracts/application-lifecycle-runtime'; +import type { RuntimeHintsApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import { finalizeApplicationCloseRuntimeUse, finalizeApplicationCloseWithRuntimeHintClearUse, @@ -17,6 +14,7 @@ import type { PlatformRequestScope } from '@agent-device/contracts/platform-runt import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations'; import { AppError, errorMessage } from '@agent-device/kernel/errors'; import type { SessionState } from '../core/session-state.ts'; +import { requiresRuntimeHintsClear } from '../sessions/session-runtime.ts'; import type { BindDeviceRuntime, InspectDeviceRuntimeFacts, @@ -27,7 +25,7 @@ type SessionFinalization = Readonly<{ bind: BindDeviceRuntime; session: SessionState; stateDir: string; - runtimeHints: RuntimeHintValues; + runtimeHints: RuntimeHintsApplicationInput; daemonShutdown?: boolean; }>; @@ -41,7 +39,7 @@ async function finalizeSessionApplicationLifecycle(params: SessionFinalization): ...finalizationInput(session, stateDir), ...(params.daemonShutdown ? { daemonShutdown: true } : {}), }; - if (!requiresRuntimeHintCleanup(session, runtimeHints)) { + if (!requiresRuntimeHintsClear(runtimeHints)) { const use = finalizeApplicationCloseRuntimeUse; assertLifecycleFacts(await inspectFacts(session.device), use.required, session); await (await bind(session.device, use)).operations.finalizeApplicationClose(input); @@ -51,10 +49,7 @@ async function finalizeSessionApplicationLifecycle(params: SessionFinalization): assertLifecycleFacts(await inspectFacts(session.device), use.required, session); const runtime = await bind(session.device, use); await runtime.operations.finalizeApplicationClose(input); - await runtime.operations.clearRuntimeHints({ - appId: session.appBundleId, - values: runtimeHints, - }); + await runtime.operations.clearRuntimeHints(runtimeHints); } export async function finalizeBoundSessionApplicationLifecycle(params: { @@ -62,7 +57,7 @@ export async function finalizeBoundSessionApplicationLifecycle(params: { bindDevice: BindDeviceRuntime; session: SessionState; stateDir: string; - runtimeHints: RuntimeHintValues; + runtimeHints: RuntimeHintsApplicationInput; }): Promise { await finalizeSessionApplicationLifecycle({ ...params, bind: params.bindDevice }); } @@ -83,7 +78,8 @@ export async function finalizeDaemonSessionApplicationLifecycle(params: { scope: PlatformRequestScope; session: SessionState; stateDir: string; - runtimeHints: RuntimeHintValues; + /** The stored hints to clear and the app they are bound to, else the session's app. */ + runtimeHints: RuntimeHintsApplicationInput; daemonLeaving?: boolean; }): Promise { const { gateway, scope, session, stateDir, runtimeHints } = params; @@ -148,10 +144,3 @@ function finalizationInput(session: SessionState, stateDir: string) { stateDir, }; } - -function requiresRuntimeHintCleanup( - session: SessionState, - runtimeHints: RuntimeHintValues, -): boolean { - return session.appBundleId !== undefined && hasRuntimeTransportHintValues(runtimeHints); -} 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 87995ee169..8cf9ccf470 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 @@ -440,7 +440,11 @@ test.each([false, true])( const address = 'cwd:shutdown-hints:default'; const ref = sessionStore.publish(address, makeIosSession('default')); const publicRef = sessionStore.publish('default', makeIosSession('default')); - sessionStore.setRuntimeHints(address, { metroHost: 'scoped.example', metroPort: 8082 }); + sessionStore.setRuntimeHints( + address, + { metroHost: 'scoped.example', metroPort: 8082 }, + 'com.example.bound', + ); sessionStore.setRuntimeHints('default', { metroHost: 'public.example', metroPort: 8083 }); let successor; if (retired) { @@ -458,10 +462,10 @@ test.each([false, true])( platformCleanup: platformResourceCleanupFixture(), }); - expect(finalizeApplicationLifecycle).toHaveBeenCalledWith( - ref.session, - retired ? {} : { metroHost: 'scoped.example', metroPort: '8082' }, - ); + expect(finalizeApplicationLifecycle).toHaveBeenCalledWith(ref.session, { + appId: retired ? undefined : 'com.example.bound', + values: retired ? {} : { metroHost: 'scoped.example', metroPort: '8082' }, + }); expect(sessionStore.resolveCurrent(publicRef)).toBe(publicRef.session); expect(sessionStore.getRuntimeHints('default')).toEqual({ metroHost: 'public.example', diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index fb0d85e6f5..85d7c82f7f 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -43,7 +43,7 @@ import type { LeaseEndReason } from '../../sessions/lease-lifecycle.ts'; import { teardownSessionResources } from '../../sessions/session-teardown.ts'; import { resolveDaemonSessionTeardownTimeoutMs } from '../../sessions/session-teardown-budget.ts'; import { finalizeDaemonSessionApplicationLifecycle } from '../application-lifecycle-recovery.ts'; -import { runtimeHintValues } from '../../sessions/session-runtime.ts'; +import { runtimeHintsClearInput } from '../../sessions/session-runtime.ts'; import { closeDaemonServers, teardownDaemonSessionForShutdown, @@ -416,7 +416,10 @@ async function startDaemonRuntimeOnHost( const settleIdleExpiredSession = async (ref: SessionRef): Promise => { const session = sessionStore.resolveCurrent(ref) ?? ref.session; const sessionName = ref.address; - const runtimeHints = runtimeHintValues(sessionStore.getRuntimeHints(sessionName)); + const runtimeHints = runtimeHintsClearInput( + sessionStore.getStoredRuntimeHints(sessionName), + session.appBundleId, + ); await teardownSessionResources({ appLog: 'run', ref, diff --git a/packages/daemon/src/server/http/server-shutdown.ts b/packages/daemon/src/server/http/server-shutdown.ts index bdae4b6ab0..74914884d2 100644 --- a/packages/daemon/src/server/http/server-shutdown.ts +++ b/packages/daemon/src/server/http/server-shutdown.ts @@ -5,13 +5,13 @@ import type { import { normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; import { settleWithin, type SettleWithinOutcome } from '@agent-device/host-kit/settle-within'; import type { DaemonServer } from './transport.ts'; -import type { RuntimeHintValues } from '@agent-device/contracts/application-lifecycle-runtime'; +import type { RuntimeHintsApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import { SessionStore } from '../../core/session-store.ts'; import type { SessionRef, SessionState } from '../../core/session-state.ts'; import type { PlatformResourceCleanup } from '../../core/platform-resource-cleanup.ts'; import { stopSessionAppLog, teardownSessionResources } from '../../sessions/session-teardown.ts'; import { resolveDaemonSessionTeardownTimeoutMs } from '../../sessions/session-teardown-budget.ts'; -import { runtimeHintValues } from '../../sessions/session-runtime.ts'; +import { runtimeHintsClearInput } from '../../sessions/session-runtime.ts'; const DAEMON_SHUTDOWN_TIMEOUT_MS = 5_000; const DAEMON_PLUGIN_SHUTDOWN_TIMEOUT_MS = 5_000; @@ -277,7 +277,7 @@ export async function teardownDaemonSessionForShutdown(params: { platformCleanup: PlatformResourceCleanup; finalizeApplicationLifecycle?: ( session: SessionState, - runtimeHints: RuntimeHintValues, + runtimeHints: RuntimeHintsApplicationInput, ) => Promise; afterSuccessfulTeardown?: (session: SessionState) => Promise; }): Promise { @@ -291,8 +291,9 @@ export async function teardownDaemonSessionForShutdown(params: { } = params; const current = sessionStore.resolveCurrent(ref); const session = current ?? ref.session; - const runtimeHints = runtimeHintValues( - current ? sessionStore.getRuntimeHints(ref.address) : undefined, + const runtimeHints = runtimeHintsClearInput( + current ? sessionStore.getStoredRuntimeHints(ref.address) : undefined, + session.appBundleId, ); const timeoutMs = resolveDaemonSessionTeardownTimeoutMs(session); // The ownership-fenced app-log side effect must settle while this process diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index 218632b647..53fa298003 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -83,7 +83,7 @@ import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionRef, SessionState } from '../core/session-state.ts'; import { teardownSessionResources } from '../sessions/session-teardown.ts'; import { finalizeBoundSessionApplicationLifecycle } from './application-lifecycle-recovery.ts'; -import { runtimeHintValues } from '../sessions/session-runtime.ts'; +import { runtimeHintsClearInput } from '../sessions/session-runtime.ts'; import type { DeviceRuntimeGateway } from '@agent-device/contracts/platform-runtime'; import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; @@ -647,7 +647,10 @@ async function teardownExpiredSession(params: { const { ref, sessionStore, inspectFacts, bindDevice, platformCleanup } = params; const session = sessionStore.resolveCurrent(ref) ?? ref.session; const sessionName = ref.address; - const runtimeHints = runtimeHintValues(sessionStore.getRuntimeHints(ref.address)); + const runtimeHints = runtimeHintsClearInput( + sessionStore.getStoredRuntimeHints(ref.address), + session.appBundleId, + ); let primaryError: unknown; try { await teardownSessionResources({ diff --git a/packages/daemon/src/sessions/handlers/session-runtime-command.ts b/packages/daemon/src/sessions/handlers/session-runtime-command.ts index 5d3a8fc25a..0495c4798e 100644 --- a/packages/daemon/src/sessions/handlers/session-runtime-command.ts +++ b/packages/daemon/src/sessions/handlers/session-runtime-command.ts @@ -10,9 +10,9 @@ import { admitRuntimeUse } from '../../core/runtime-admission.ts'; import { buildRuntimeHints, countConfiguredRuntimeHints, - hasRuntimeTransportHints, mergeRuntimeHints, - runtimeHintValues, + requiresRuntimeHintsClear, + runtimeHintsClearInput, toRuntimePlatform, } from '../session-runtime.ts'; import type { @@ -141,7 +141,8 @@ async function clearRuntimeCommand(params: { const { sessionName, sessionStore, ref, current, inspectFacts, bindDevice, platformServices } = params; const session = ref ? sessionStore.requireCurrent(ref) : undefined; - if (hasRuntimeTransportHints(current) && session?.appBundleId) { + const stored = sessionStore.getStoredRuntimeHints(sessionName); + if (session && requiresRuntimeHintsClear(runtimeHintsClearInput(stored, session.appBundleId))) { const admission = await admitClearRuntime({ device: session.device, inspectFacts, @@ -153,10 +154,9 @@ async function clearRuntimeCommand(params: { // the mutation boundary, after admission and immediately before the bound package effect. const currentSession = sessionStore.requireCurrent(ref!); expireRefFrame(currentSession); - await admission.runtime.operations.clearRuntimeHints({ - appId: currentSession.appBundleId, - values: runtimeHintValues(current), - }); + await admission.runtime.operations.clearRuntimeHints( + runtimeHintsClearInput(stored, currentSession.appBundleId), + ); } const cleared = ref ? sessionStore.clearRuntimeHints(ref) : Boolean(current); if (!ref) sessionStore.setRuntimeHints(sessionName, undefined); @@ -217,7 +217,7 @@ function setRuntimeCommand(params: { sessionStore.setRuntimeHints( sessionName, nextRuntime, - sessionStore.getRuntimeHintsAppId(sessionName), + sessionStore.getStoredRuntimeHints(sessionName)?.appId, ); return { ok: true, 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 1e61129690..cbc57934ee 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 @@ -57,6 +57,7 @@ import { } from '../../../../__tests__/support/handlers/session-command-harness.ts'; import { applyRuntimeHintsFixture, + clearRuntimeHintsFixture, dispatchApplicationLifecycleEffect, resolveOpenTargetFixture, } from '../../../../__tests__/support/application-lifecycle-runtime-fixture.ts'; @@ -79,6 +80,7 @@ bindTestCommandHost(); const mockDispatch = vi.mocked(dispatchApplicationLifecycleEffect); const mockApplyRuntimeHints = vi.mocked(applyRuntimeHintsFixture); +const mockClearRuntimeHints = vi.mocked(clearRuntimeHintsFixture); const mockResolveAndroidPackage = vi.mocked(resolveAndroidPackageForOpen); const mockResolveOpenTarget = vi.mocked(resolveOpenTargetFixture); @@ -562,3 +564,47 @@ test('runtime set keeps edited hints bound to the app an open applied them to', { appId: 'com.example.metro', host: '10.0.2.2', port: '8082' }, ]); }); + +test.each([ + { clearer: 'close', req: { command: 'close', positionals: [], flags: {} } }, + { clearer: 'runtime clear', req: { command: 'runtime', positionals: ['clear'], flags: {} } }, + { + clearer: 'an open with only a launch URL', + req: { + command: 'open', + positionals: ['com.example.other'], + flags: { platform: 'android' as const }, + runtime: { launchUrl: 'otherapp://home' }, + }, + }, +])( + '$clearer clears stored hints from the app they are bound to after another app opened', + async ({ req }) => { + const sessionStore = makeSessionStore(); + const session = 'runtime-hints-clear-bound-app'; + mockResolveTargetDevice.mockResolvedValue(makeAndroidEmulator()); + for (const [target, runtime] of [ + ['com.example.metro', { metroPort: 8081 }], + ['com.google.android.apps.photos', undefined], + ] as const) { + const opened = await runSessionCommand(sessionStore, { + session, + command: 'open', + positionals: [target], + flags: { platform: 'android' }, + ...(runtime ? { runtime } : {}), + }); + expect(opened.ok).toBe(true); + } + + const response = await runSessionCommand(sessionStore, { session, ...req }); + + expect(response.ok).toBe(true); + expect(mockClearRuntimeHints).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + appId: 'com.example.metro', + values: { metroHost: '10.0.2.2', metroPort: '8081' }, + }), + ); + }, +); 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 7617fe4f34..8940ec05a7 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 @@ -13,7 +13,7 @@ import { type SessionCleanupFailure, } from '../../session-teardown.ts'; import type { PlatformResourceCleanup } from '../../../core/platform-resource-cleanup.ts'; -import { hasRuntimeTransportHints, runtimeHintValues } from '../../session-runtime.ts'; +import { requiresRuntimeHintsClear, runtimeHintsClearInput } from '../../session-runtime.ts'; import type { CloseRuntime, CloseRuntimeWithRuntimeHintClear, @@ -90,7 +90,7 @@ export async function runSessionCloseTeardown(params: { inspectSessionLeaseRetainedOnClose({ session, leaseRegistry: params.leaseRegistry }), )), }); - const configuredRuntimeHints = sessionStore.getRuntimeHints(sessionName); + const configuredRuntimeHints = sessionStore.getStoredRuntimeHints(sessionName); const resourceStops = sessionResourceStopSteps({ ref, sessionStore, @@ -102,16 +102,10 @@ export async function runSessionCloseTeardown(params: { const platformCloseError = repairArmed ? undefined : await dispatchTargetedPlatformClose({ req, session, logPath, lifecycle }); - if ( - clearRuntimeHints && - session.appBundleId && - hasRuntimeTransportHints(configuredRuntimeHints) - ) { + const runtimeHintsClear = runtimeHintsClearInput(configuredRuntimeHints, session.appBundleId); + if (clearRuntimeHints && requiresRuntimeHintsClear(runtimeHintsClear)) { await attemptCleanup('runtime_hints', async () => { - await clearRuntimeHints({ - appId: session.appBundleId, - values: runtimeHintValues(configuredRuntimeHints), - }); + await clearRuntimeHints(runtimeHintsClear); }); } const finalization = await attemptCleanup( 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 660d040e26..31296786de 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -28,7 +28,7 @@ import type { SessionCleanupFailure } from '../../session-teardown.ts'; import { isWebSession } from '../../web-session-names.ts'; import { clearDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; import { applicationLifecycleExecutionFromRequest } from '../../application-lifecycle-execution.ts'; -import { hasRuntimeTransportHints } from '../../session-runtime.ts'; +import { requiresRuntimeHintsClear, runtimeHintsClearInput } from '../../session-runtime.ts'; import type { BindDeviceRuntime, InspectDeviceRuntimeFacts, @@ -323,8 +323,12 @@ export async function handleSessionCloseCommands( device: session.device, clearRuntimeHints: req.internal?.closeAppOnly !== true && - Boolean(session.appBundleId) && - hasRuntimeTransportHints(sessionStore.getRuntimeHints(sessionName)), + requiresRuntimeHintsClear( + runtimeHintsClearInput( + sessionStore.getStoredRuntimeHints(sessionName), + session.appBundleId, + ), + ), inspectFacts: params.inspectFacts, platformServices: params.platformServices, bindDevice: params.bindDevice, 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 146018e159..1cfa11bce7 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 @@ -37,9 +37,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; replacedStoredRuntime: boolean; - /** The app the reused stored hints are bound to; absent for explicit or unbound hints. */ - storedRuntimeAppId: string | undefined; + // 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. applyRuntimeHints: boolean; clearRemovedRuntimeHints: boolean; }>; @@ -122,19 +124,19 @@ 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; return { type: 'plan', plan: { runtime, previousRuntime, + previousRuntimeAppId, replacedStoredRuntime, - storedRuntimeAppId: replacedStoredRuntime - ? undefined - : params.sessionStore.getRuntimeHintsAppId(params.sessionName), applyRuntimeHints: hasRuntimeTransportHints(runtime), clearRemovedRuntimeHints: shouldClearRemovedRuntimeTransportHints({ replacedStoredRuntime, previousRuntime, + previousRuntimeAppId, runtime, session: params.existingSession, }), @@ -208,6 +210,7 @@ export async function prepareOpenCommandDetails(params: { await maybeClearRemovedRuntimeTransportHints({ replacedStoredRuntime: runtimeHintPlan.replacedStoredRuntime, previousRuntime: runtimeHintPlan.previousRuntime, + previousRuntimeAppId: runtimeHintPlan.previousRuntimeAppId, runtime: runtimeHintPlan.runtime, session: existingSession, clearRuntimeHints, @@ -219,11 +222,13 @@ export async function prepareOpenCommandDetails(params: { details: { appBundleId, appName, - runtime: storedRuntimeHintsForApp( - runtimeHintPlan.runtime, - runtimeHintPlan.storedRuntimeAppId, - appBundleId, - ), + runtime: runtimeHintPlan.replacedStoredRuntime + ? runtimeHintPlan.runtime + : storedRuntimeHintsForApp( + runtimeHintPlan.runtime, + runtimeHintPlan.previousRuntimeAppId, + appBundleId, + ), }, }; } diff --git a/packages/daemon/src/sessions/session-runtime.ts b/packages/daemon/src/sessions/session-runtime.ts index 498149536b..e421f0e3c4 100644 --- a/packages/daemon/src/sessions/session-runtime.ts +++ b/packages/daemon/src/sessions/session-runtime.ts @@ -13,7 +13,7 @@ import { } from '@agent-device/kernel/contracts'; import { publicPlatformString, type DeviceInfo } from '@agent-device/kernel/device'; 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 { trimRuntimeValue } from '@agent-device/host-kit/runtime-transport-hints'; import { isAndroidEmulator, isIosSimulator } from './device/device-targets.ts'; @@ -351,18 +351,13 @@ export function tryResolveOpenRuntimeHints( export async function maybeClearRemovedRuntimeTransportHints(params: { replacedStoredRuntime: boolean; previousRuntime: SessionRuntimeHints | undefined; + previousRuntimeAppId: string | undefined; runtime: SessionRuntimeHints | undefined; session: SessionState | undefined; - clearRuntimeHints(input: { appId?: string; values: RuntimeHintValues }): Promise; + clearRuntimeHints(input: RuntimeHintsApplicationInput): Promise; }): Promise { - const { previousRuntime, clearRuntimeHints } = params; if (!shouldClearRemovedRuntimeTransportHints(params)) return; - const session = params.session; - if (!session?.appBundleId) return; - await clearRuntimeHints({ - appId: session.appBundleId, - values: runtimeHintValues(previousRuntime), - }); + await params.clearRuntimeHints(removedRuntimeHintsClearInput(params)); } /** Daemon session policy decides whether an open must remove its previous native transport. */ @@ -370,14 +365,39 @@ export function shouldClearRemovedRuntimeTransportHints( params: Readonly<{ replacedStoredRuntime: boolean; previousRuntime: SessionRuntimeHints | undefined; + previousRuntimeAppId: string | undefined; runtime: SessionRuntimeHints | undefined; session: SessionState | undefined; }>, ): boolean { return ( params.replacedStoredRuntime && - Boolean(params.session?.appBundleId) && - hasRuntimeTransportHints(params.previousRuntime) && + requiresRuntimeHintsClear(removedRuntimeHintsClearInput(params)) && !hasRuntimeTransportHints(params.runtime) ); } + +function removedRuntimeHintsClearInput( + params: Readonly<{ + previousRuntime: SessionRuntimeHints | undefined; + previousRuntimeAppId: string | undefined; + session: SessionState | undefined; + }>, +): RuntimeHintsApplicationInput { + return runtimeHintsClearInput( + params.previousRuntime && { hints: params.previousRuntime, appId: params.previousRuntimeAppId }, + params.session?.appBundleId, + ); +} + +/** Clearing stored hints targets the app they are bound to, else the session's current app. */ +export function runtimeHintsClearInput( + stored: StoredRuntimeHints | undefined, + sessionAppId: string | undefined, +): RuntimeHintsApplicationInput { + return { appId: stored?.appId ?? sessionAppId, values: runtimeHintValues(stored?.hints) }; +} + +export function requiresRuntimeHintsClear(input: RuntimeHintsApplicationInput): boolean { + return Boolean(input.appId) && hasRuntimeTransportHintValues(input.values); +}