Skip to content

Commit 3c24b0a

Browse files
committed
fix(daemon): distinguish known relaunch refusals
1 parent 7ac2f23 commit 3c24b0a

4 files changed

Lines changed: 65 additions & 6 deletions

File tree

‎packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution-relaunch.test.ts‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import path from 'node:path';
22
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
33
import type { DaemonResponse } from '@agent-device/kernel/contracts';
44
import type { DeviceInfo } from '@agent-device/kernel/device';
5+
import { AppError } from '@agent-device/kernel/errors';
6+
import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request';
57
import {
68
acquireDeviceClaim,
79
inspectDeviceClaims,
@@ -111,6 +113,7 @@ async function openRelaunch(params: {
111113
flags?: Record<string, unknown>;
112114
onOpenApplication?: (input: OpenApplicationInput) => Promise<void> | void;
113115
openOutcome?: LaunchConfirmationOutcome | LaunchConfirmationAbsent;
116+
requestId?: string;
114117
}) {
115118
const opened: OpenApplicationInput[] = [];
116119
const boundDevices: DeviceInfo[] = [];
@@ -142,6 +145,7 @@ async function openRelaunch(params: {
142145
command: 'open',
143146
positionals: params.positionals ?? [],
144147
flags: { relaunch: true, ...params.flags },
148+
...(params.requestId ? { meta: { requestId: params.requestId } } : {}),
145149
},
146150
sessionName: params.sessionName,
147151
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
@@ -225,10 +229,12 @@ test('failed relaunch retains the claim for close while allowing daemon idle rea
225229
sessionStore,
226230
sessionName,
227231
onOpenApplication: () => {
228-
throw new Error('lifecycle dispatch failed');
232+
throw new AppError('COMMAND_FAILED', 'cleanup timeout', {
233+
reason: 'android-app-close-timeout',
234+
});
229235
},
230236
}),
231-
).rejects.toThrow('lifecycle dispatch failed');
237+
).rejects.toThrow('cleanup timeout');
232238
expect(sessionStore.get(sessionName)).toMatchObject({
233239
name: sessionName,
234240
deviceClaim: acquired.ownership,
@@ -247,6 +253,7 @@ test('failed relaunch retains the claim for close while allowing daemon idle rea
247253
},
248254
}),
249255
).rejects.toThrow('lifecycle dispatch failed again');
256+
expect(isDaemonIdle({ sessionStore, inFlightRequestCount: 0 })).toBe(true);
250257

251258
const { loader } = lifecycleOperationsSpy();
252259
const closed = await handleSessionCommands({
@@ -278,6 +285,42 @@ test('failed relaunch retains the claim for close while allowing daemon idle rea
278285
}
279286
});
280287

288+
test.each([{ dispatched: 'no' as const }, { reason: 'runtime-hints-operation-missing' }])(
289+
'a known relaunch refusal leaves the daemon active: %o',
290+
async (details) => {
291+
const sessionStore = makeSessionStore();
292+
publishSession(sessionStore, 'android-session', ANDROID_EMULATOR);
293+
await expect(
294+
openRelaunch({
295+
sessionStore,
296+
sessionName: 'android-session',
297+
onOpenApplication: () => {
298+
throw new AppError('COMMAND_FAILED', 'hint refused', details);
299+
},
300+
}),
301+
).rejects.toThrow('hint refused');
302+
expect(isDaemonIdle({ sessionStore, inFlightRequestCount: 0 })).toBe(false);
303+
},
304+
);
305+
306+
test('a canceled relaunch after lifecycle completion allows daemon idle reap', async () => {
307+
const sessionStore = makeSessionStore();
308+
const requestId = 'relaunch-canceled-after-dispatch';
309+
publishSession(sessionStore, 'android-session', ANDROID_EMULATOR);
310+
try {
311+
const { response } = await openRelaunch({
312+
sessionStore,
313+
sessionName: 'android-session',
314+
requestId,
315+
onOpenApplication: () => markRequestCanceled(requestId),
316+
});
317+
expect(response?.ok).toBe(false);
318+
expect(isDaemonIdle({ sessionStore, inFlightRequestCount: 0 })).toBe(true);
319+
} finally {
320+
clearRequestCanceled(requestId);
321+
}
322+
});
323+
281324
test('relaunch rejected before dispatch still keeps the daemon active', async () => {
282325
const sessionStore = makeSessionStore();
283326
publishSession(sessionStore, 'android-session', ANDROID_EMULATOR, { appName: undefined });

‎packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@ import {
3232
isAuthoringArmedSession,
3333
} from '../../../core/session-script-publication-capability.ts';
3434
import { isRequestCanceled } from '@agent-device/host-kit/request';
35-
import { createRequestCanceledError } from '@agent-device/kernel/errors';
35+
import {
36+
AppError,
37+
createRequestCanceledError,
38+
readDispatchDisclosure,
39+
} from '@agent-device/kernel/errors';
3640
import { SessionStore } from '../../../core/session-store.ts';
3741
import {
3842
countConfiguredRuntimeHints,
@@ -303,7 +307,16 @@ export async function completeOpenCommand(params: {
303307
),
304308
})
305309
.catch((error: unknown) => {
306-
if (existingRef && shouldRelaunch && sessionStore.resolveCurrent(existingRef)) {
310+
if (
311+
existingRef &&
312+
shouldRelaunch &&
313+
!(
314+
error instanceof AppError &&
315+
(readDispatchDisclosure(error.details) === 'no' ||
316+
error.details?.reason === 'runtime-hints-operation-missing')
317+
) &&
318+
sessionStore.resolveCurrent(existingRef)
319+
) {
307320
sessionStore.markCloseEffectsUnconfirmed(existingRef);
308321
}
309322
throw error;
@@ -315,6 +328,9 @@ export async function completeOpenCommand(params: {
315328
? buildStartupPerfSample(openStartedAtMs, openTarget, sessionAppBundleId)
316329
: undefined;
317330
if (isRequestCanceled(req.meta?.requestId)) {
331+
if (existingRef && shouldRelaunch && sessionStore.resolveCurrent(existingRef)) {
332+
sessionStore.markCloseEffectsUnconfirmed(existingRef);
333+
}
318334
const canceled = createRequestCanceledError();
319335
return {
320336
type: 'response',

‎src/commands/schema/cli-help.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,7 @@ Android physical-device prerequisites:
408408
409409
Runner and daemon lifecycle (applies to simulators too):
410410
open without --relaunch is idempotent-foreground for an already-running app, except native macOS app opens keep it in the background (help macos); neither restarts the process. open --relaunch restarts the app; on iOS simulators this collapses to one simctl launch --terminate-running-process call instead of a separate terminate-then-launch.
411-
If an existing session's relaunch fails after dispatch, close can release its device claim. The session does not keep an idle daemon alive until a successful open.
411+
If a relaunch leaves an existing session's device effects unconfirmed, close can release its claim; idle shutdown retries cleanup and leaves an unconfirmed claim stale, while embedded runtimes and AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0 require close because they do not shut down for idleness.
412412
No runner read launches a session app that is not running: snapshot, wait, is, get, a reading find, and an interaction's leading reads (a gesture's viewport read, the capture that resolves a selector click/fill) answer the retriable APP_NOT_RUNNING instead of bare-launching over a launch SpringBoard still holds behind its deep-link confirmation. Only open, activate, and a command that mutates without a leading read bring a stopped app up.
413413
close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that simulator (same udid in the same simulator set) skips the runner build, unless --shutdown was requested, the session was recording, or its device lease ends on close. A lease allocated with retainOnClose can keep the runner between sessions; releasing or expiring that lease stops its runner unless a session outside the lease has taken over the device. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stopping. Lease release, expiry, and graceful daemon shutdown still clean up runners they own. Only a ready runner with an observed listener is retained; close retires unfinished prewarm recovery. Losing the retained listener stops that generation, and graceful daemon shutdown stops idle retained runners rather than handing them off without supervision.
414414
Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap.

‎website/docs/docs/commands.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ Open apps and links:
105105
- Android (adb): an intent target such as `open settings` records the package that opened as `appBundleId`. `open settings --relaunch` stops and restarts that app. If the intent matches more than one activity, `--relaunch` fails.
106106
- Android (ADB): `close` force-stops the app, then checks for 2 seconds that it has left the foreground, waits up to 10 seconds for the processes it killed to exit, and checks for 2 more that no new process started. If a check window ends first, `close` fails with `details.reason: android-app-close-timeout` and `details.phase` set to `foreground`, `exit`, or `process`; a process that survives the force-stop fails with `exit`, and apps Android restarts at once, such as the launcher, fail with `process`. When `pidof` cannot list the app's processes, `close` fails with `details.reason: android-process-probe-unavailable`; if that happens before the force-stop, the app keeps running.
107107
- When `close` cannot confirm its cleanup on a session that holds a device claim, it fails and keeps the session and its claim, so the device is not handed on unconfirmed. Run `close` again with the same options to retry the cleanup and release the device, leaving out `--save-script` once the first attempt has published the script. Only `close`, or a successful `open`, is supported on the kept session: other commands work, but the session stays marked, so an idle daemon can still shut it down. If nobody retries, the kept session does not keep the daemon alive: when the daemon has been idle for its idle timeout and shuts down, its shutdown retries the cleanup, and a claim it still cannot confirm goes stale instead of being released. Embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` never shut down for idleness, so there a retried `close` is the only release.
108-
- If `open --relaunch` fails after it starts on an existing session, the session and its claim remain available for `close`. The session does not keep an idle daemon alive until a successful `open`.
108+
- If `open --relaunch` leaves an existing session's device effects unconfirmed, the session and claim remain available for `close`, but idle shutdown can retry cleanup and leave an unconfirmed claim stale; embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` do not shut down for idleness, so use `close` to release the claim.
109109

110110
iOS Simulator launch behavior:
111111

0 commit comments

Comments
 (0)