Skip to content

Commit 4abff15

Browse files
authored
fix(limrun): stop answering appstate for an unreachable iOS instance (callstack#4176)
* fix(limrun): stop answering appstate for an unreachable iOS instance Limrun iOS answered appstate from the session record without contacting the instance, so a terminated instance still reported the last opened app. The Limrun owner now binds appState on iOS and confirms the instance answers before leaving the session record to name the app. A failed read reports limrun_instance_unreachable, and a device with no live session is refused. The Apple session handler no longer falls back to the session record when a read fails, so a busy local runner now fails appstate too. Closes callstack#3924 * fix(limrun): check the instance for a session with no bundle id A session opened from a URL records no bundle id, and the appstate handler skipped the owner for it, so a terminated Limrun iOS instance still answered from the session record. The handler now always asks the owner, and the Apple runner read owns the rule that it needs a bundle id. capabilities no longer advertises appstate when the owner holds no live session, because appstate refuses that case. A provider session lost before the read now reports a typed reason on both platforms, and the docs name both failure reasons. * fix(daemon): share the no-live-session rule from runtime admission The capabilities inventory may not import a session handler, so the rule now lives in runtime admission below both callers. The inventory also reads the first unavailable appstate cell, as admission does, so capabilities and appstate agree on which reason applies. * fix(limrun): report a lost session with the documented reason A provider session lost after admission now reports owner-capability-missing, as a session lost before admission does. capabilities no longer advertises appstate when the owner's facts cannot be inspected, because appstate fails in that case too. It also walks appStateUse directly, so it follows the same order as admission. * test(limrun): cover iOS appstate through the daemon when the instance is gone The Limrun read tests hand-build their session, so the route from a real daemon to the Limrun owner had no coverage. Also state in the docs that any provider whose session has ended refuses appstate, not only Limrun.
1 parent 01e77b1 commit 4abff15

18 files changed

Lines changed: 523 additions & 89 deletions

File tree

‎packages/daemon/src/core/runtime-admission.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,11 @@ export type RuntimeAdmissionRequest = RuntimeAdmissionBindings &
4545

4646
export type { RuntimeAdmissionBindings };
4747

48+
/** The owner has no live session for the device, so a session record must not answer for it. */
49+
export function ownerHoldsNoLiveSession(reason: unknown): boolean {
50+
return reason === 'owner-capability-missing';
51+
}
52+
4853
/**
4954
* The one refusal the daemon reports when a device's exact runtime owner did not admit an
5055
* operation. Both seams — this generic route and the request-scoped session handlers — build their

‎packages/daemon/src/sessions/handlers/__tests__/session-appstate-input.test.ts‎

Lines changed: 110 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts';
2-
import { test, expect } from 'vitest';
2+
import { test, expect, vi } from 'vitest';
33
import * as path from 'node:path';
44
import {
55
mockDispatch,
@@ -30,6 +30,7 @@ import {
3030
narrowDeviceBinding,
3131
type DeviceBinding,
3232
type RuntimeFacts,
33+
type RuntimeOperationUnavailability,
3334
} from '@agent-device/contracts/platform-runtime';
3435
import type { BindDeviceRuntime } from '../../../core/request-runtime-binding.ts';
3536
import { fakeCreateCommandSurface } from '../../../__tests__/support/command-surface-fake.ts';
@@ -122,6 +123,7 @@ test('appstate returns session appName when bundle id is unavailable', async ()
122123
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
123124
sessionStore,
124125
invoke: noopInvoke,
126+
...appleAppStateRuntime(async () => ({})),
125127
});
126128

127129
expect(response).toBeTruthy();
@@ -437,20 +439,26 @@ test('appstate on iOS keeps the session answer, with no state, when no runner is
437439
}
438440
});
439441

440-
test('appstate on iOS keeps the session answer, with no state, when the runner cannot read one', async () => {
441-
const sessionStore = makeSessionStore();
442-
const sessionName = 'sim';
443-
sessionStore.publish(sessionName, {
444-
...makeSession(sessionName, IOS_SESSION_DEVICE),
445-
appBundleId: 'dev.e2e.benchmark',
446-
appName: 'Benchmark',
447-
});
442+
const BUNDLED_APP = { appBundleId: 'dev.e2e.benchmark', appName: 'Benchmark' };
443+
const DEEP_LINK_APP = { appName: 'myapp://path' };
444+
445+
function publishIosSession(
446+
sessionStore: ReturnType<typeof makeSessionStore>,
447+
sessionName: string,
448+
app: Readonly<{ appBundleId?: string; appName: string }> = BUNDLED_APP,
449+
) {
450+
sessionStore.publish(sessionName, { ...makeSession(sessionName, IOS_SESSION_DEVICE), ...app });
448451
mockResolveTargetDevice.mockResolvedValue(IOS_SESSION_DEVICE);
449-
const runtime = appleAppStateRuntime(async () => {
450-
throw new AppError('COMMAND_FAILED', 'runner is busy');
451-
});
452+
}
452453

453-
const response = await handleSessionCommands({
454+
async function appStateWith(
455+
runtime: ReturnType<typeof appleAppStateRuntime>,
456+
app?: Parameters<typeof publishIosSession>[2],
457+
) {
458+
const sessionStore = makeSessionStore();
459+
const sessionName = 'sim';
460+
publishIosSession(sessionStore, sessionName, app);
461+
return await handleSessionCommands({
454462
host: createTestHostEnvironment(),
455463
createCommandSurface: fakeCreateCommandSurface,
456464
platformServices: daemonPlatformServicesFixture(),
@@ -461,11 +469,94 @@ test('appstate on iOS keeps the session answer, with no state, when the runner c
461469
invoke: noopInvoke,
462470
...runtime,
463471
});
472+
}
464473

465-
expect(response?.ok).toBe(true);
466-
if (response && response.ok) {
467-
expect(response.data?.appName).toBe('Benchmark');
468-
expect(response.data?.source).toBe('session');
469-
expect(response.data).not.toHaveProperty('state');
470-
}
474+
function runtimeWithAppStateFact(
475+
fact: RuntimeOperationUnavailability,
476+
): ReturnType<typeof appleAppStateRuntime> {
477+
return {
478+
...appleAppStateRuntime(async () => ({})),
479+
inspectFacts: async (device) => {
480+
const base = await mockInspectDeviceRuntimeFacts(device);
481+
return { ...base, operations: { ...base.operations, appState: fact } };
482+
},
483+
};
484+
}
485+
486+
test('appstate on iOS fails with the read error when the runtime read fails', async () => {
487+
const failure = new AppError('COMMAND_FAILED', 'runner is busy', { reason: 'runner_busy' });
488+
489+
await expect(
490+
appStateWith(
491+
appleAppStateRuntime(async () => {
492+
throw failure;
493+
}),
494+
),
495+
).rejects.toBe(failure);
496+
});
497+
498+
test('appstate on iOS is refused when the owner holds no live session for the device', async () => {
499+
const response = await appStateWith(
500+
runtimeWithAppStateFact({
501+
available: false,
502+
reason: 'owner-capability-missing',
503+
hint: 'Limrun requires a matching live provider session for this device.',
504+
}),
505+
);
506+
507+
expect(response).toMatchObject({
508+
ok: false,
509+
error: {
510+
code: 'UNSUPPORTED_OPERATION',
511+
details: { reason: 'owner-capability-missing' },
512+
},
513+
});
514+
});
515+
516+
test('appstate on iOS asks the owner about a session opened with no bundle id', async () => {
517+
const read = vi.fn(async () => ({}));
518+
519+
const response = await appStateWith(appleAppStateRuntime(read), DEEP_LINK_APP);
520+
521+
expect(response).toMatchObject({
522+
ok: true,
523+
data: { source: 'session', appName: 'myapp://path' },
524+
});
525+
expect(read).toHaveBeenCalledTimes(1);
526+
});
527+
528+
test('appstate on iOS fails when the read fails for a session with no bundle id', async () => {
529+
const failure = new AppError('COMMAND_FAILED', 'instance gone', {
530+
reason: 'limrun_instance_unreachable',
531+
});
532+
533+
await expect(
534+
appStateWith(
535+
appleAppStateRuntime(async () => {
536+
throw failure;
537+
}),
538+
DEEP_LINK_APP,
539+
),
540+
).rejects.toBe(failure);
541+
});
542+
543+
test('appstate on iOS is refused for a session with no bundle id and no live owner session', async () => {
544+
const response = await appStateWith(
545+
runtimeWithAppStateFact({ available: false, reason: 'owner-capability-missing' }),
546+
DEEP_LINK_APP,
547+
);
548+
549+
expect(response).toMatchObject({
550+
ok: false,
551+
error: { code: 'UNSUPPORTED_OPERATION', details: { reason: 'owner-capability-missing' } },
552+
});
471553
});
554+
555+
test.each(['unsupported-provider-mode', 'unsupported-platform-leaf'] as const)(
556+
'appstate on iOS keeps the session answer when the owner reports %s',
557+
async (reason) => {
558+
const response = await appStateWith(runtimeWithAppStateFact({ available: false, reason }));
559+
560+
expect(response).toMatchObject({ ok: true, data: { source: 'session', appName: 'Benchmark' } });
561+
},
562+
);

‎packages/daemon/src/sessions/handlers/session-appstate-apple-session.ts‎

Lines changed: 23 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { DaemonResponse } from '@agent-device/kernel/contracts';
1+
import type { DaemonFailureResponse, DaemonResponse } from '@agent-device/kernel/contracts';
22
import type { AppleApplicationState } from '@agent-device/kernel/snapshot';
33
import {
44
isApplePlatform,
@@ -10,14 +10,9 @@ import {
1010
} from '@agent-device/kernel/device';
1111
import type { SessionSurface } from '@agent-device/contracts/session';
1212
import { errorResponse } from '@agent-device/kernel/contracts';
13-
import {
14-
asAppError,
15-
isRequestCanceledError,
16-
namedSessionNotFoundDetails,
17-
} from '@agent-device/kernel/errors';
18-
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
13+
import { namedSessionNotFoundDetails } from '@agent-device/kernel/errors';
1914
import { appStateUse } from '@agent-device/contracts/platform-runtime-operations';
20-
import { admitRuntimeUse } from '../../core/runtime-admission.ts';
15+
import { admitRuntimeUse, ownerHoldsNoLiveSession } from '../../core/runtime-admission.ts';
2116
import type { RuntimeCommandHandlerParams } from '../../core/session-runtime-admission.ts';
2217

2318
/**
@@ -73,17 +68,20 @@ export function appleSessionRequiredRefusal(platform: 'ios' | 'macos'): DaemonRe
7368
);
7469
}
7570

71+
type AppleAppStateRead =
72+
| Readonly<{ state?: AppleApplicationState }>
73+
| Readonly<{ refusal: DaemonFailureResponse }>;
74+
7675
/**
77-
* The session app's state as a live runner reads it, when this device's owner admits the read;
78-
* nothing otherwise, so the session record alone answers and no state is invented. The owner never
79-
* starts a runner for it. A runner that cannot answer right now (busy, mid-restart) leaves the
80-
* session answer as it was and says so in the log; a cancelled request stays cancelled.
76+
* What a live read says about the session app. An owner with no live read for this kind of device
77+
* leaves the session record to answer, and one with no live session for this device refuses, so the
78+
* record never answers for a device that is gone. A read that fails throws for the same reason. The
79+
* owner never starts a runner for it.
8180
*/
8281
async function readAppleSessionAppState(
8382
params: RuntimeCommandHandlerParams,
8483
session: Readonly<{ device: DeviceInfo; appBundleId?: string }>,
85-
): Promise<AppleApplicationState | undefined> {
86-
if (!session.appBundleId) return undefined;
84+
): Promise<AppleAppStateRead> {
8785
const admitted = await admitRuntimeUse({
8886
command: 'appstate',
8987
device: session.device,
@@ -92,19 +90,13 @@ async function readAppleSessionAppState(
9290
platformServices: params.platformServices,
9391
bindDevice: params.bindDevice,
9492
});
95-
if (admitted.type === 'response') return undefined;
96-
try {
97-
const read = await admitted.runtime.operations.appState({ appBundleId: session.appBundleId });
98-
return read.applicationState;
99-
} catch (error) {
100-
if (isRequestCanceledError(error)) throw error;
101-
emitDiagnostic({
102-
level: 'warn',
103-
phase: 'apple_appstate_runner_read_failed',
104-
data: { code: asAppError(error).code, message: asAppError(error).message },
105-
});
106-
return undefined;
93+
if (admitted.type === 'response') {
94+
return ownerHoldsNoLiveSession(admitted.response.error.details?.reason)
95+
? { refusal: admitted.response }
96+
: {};
10797
}
98+
const read = await admitted.runtime.operations.appState({ appBundleId: session.appBundleId });
99+
return { state: read.applicationState };
108100
}
109101

110102
/** A macOS desktop surface (not an app session) is answered from the session record alone. */
@@ -125,8 +117,8 @@ function desktopSurfaceResponse(session: AppStateSessionRecord): DaemonResponse
125117

126118
/**
127119
* What this Apple session currently hosts: the tracked app's live runner state when the owner
128-
* admits a read, otherwise the session record itself. A session with no tracked foreground app
129-
* says so instead of inventing one.
120+
* admits a read and has one, otherwise the session record itself. A session with no tracked
121+
* foreground app says so instead of inventing one.
130122
*/
131123
export async function appleSessionAppStateResponse(
132124
params: RuntimeCommandHandlerParams,
@@ -142,7 +134,9 @@ export async function appleSessionAppStateResponse(
142134
);
143135
}
144136

145-
const state = await readAppleSessionAppState(params, session);
137+
const read = await readAppleSessionAppState(params, session);
138+
if ('refusal' in read) return read.refusal;
139+
const { state } = read;
146140
const appName = session.appName ?? session.appBundleId;
147141
return {
148142
ok: true,

‎packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-capabilities.test.ts‎

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -463,14 +463,15 @@ test.each([
463463
});
464464
// The projection still reads one sessionless snapshot, because open/close/prepare/runtime
465465
// availability is a runtime fact. What the session owns is the appstate answer itself, so a
466-
// snapshot that reports appstate unavailable must not remove the command.
466+
// snapshot that reports appstate unavailable must not remove the command. The provider mode
467+
// matters: it reports no live read for this device, not that the owner has no live session.
467468
const inspectFacts: InspectDeviceRuntimeFacts = vi.fn(
468469
async (inspected: DeviceInfo) =>
469470
createAdmissionBinding(inspected, {
470471
appLogAvailable: false,
471472
appStateAvailable: false,
472473
networkAvailable: false,
473-
providerMode: 'local',
474+
providerMode: 'provider-runtime',
474475
}).facts,
475476
);
476477

@@ -503,6 +504,76 @@ test.each([
503504
},
504505
);
505506

507+
const ownerWithNoLiveSession: InspectDeviceRuntimeFacts = async (inspected: DeviceInfo) => {
508+
const { facts } = createAdmissionBinding(inspected, {
509+
appLogAvailable: false,
510+
networkAvailable: false,
511+
providerMode: 'provider-runtime',
512+
});
513+
return {
514+
...facts,
515+
operations: {
516+
...facts.operations,
517+
ensureReady: { available: false, reason: 'owner-capability-missing' },
518+
appState: { available: false, reason: 'owner-capability-missing' },
519+
},
520+
};
521+
};
522+
523+
const ownerThatCannotBeInspected: InspectDeviceRuntimeFacts = async () => {
524+
throw new Error('provider facts unavailable');
525+
};
526+
527+
test.each([
528+
['holds no live session', ownerWithNoLiveSession],
529+
['cannot be inspected', ownerThatCannotBeInspected],
530+
])('capabilities drops session-owned appstate when the owner %s', async (_label, inspectFacts) => {
531+
const device: DeviceInfo = {
532+
platform: 'apple',
533+
appleOs: 'ios',
534+
id: 'limrun-gone',
535+
name: 'Limrun iPhone',
536+
kind: 'simulator',
537+
target: 'mobile',
538+
booted: true,
539+
};
540+
const sessionName = 'limrun-gone-session';
541+
const sessionStore = makeSessionStore('agent-device-capabilities-limrun-gone-');
542+
sessionStore.publish(sessionName, {
543+
name: sessionName,
544+
device,
545+
createdAt: Date.now(),
546+
actions: [],
547+
appName: 'Settings',
548+
appBundleId: 'com.example.settings',
549+
});
550+
const response = await withTargetDeviceResolutionScope(
551+
async () => [device],
552+
async () =>
553+
await handleSessionCommands({
554+
host: createTestHostEnvironment(),
555+
createCommandSurface: fakeCreateCommandSurface,
556+
platformServices: daemonPlatformServicesFixture(),
557+
req: {
558+
token: 't',
559+
session: sessionName,
560+
command: PUBLIC_COMMANDS.capabilities,
561+
positionals: [],
562+
flags: {},
563+
},
564+
sessionName,
565+
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
566+
sessionStore,
567+
inspectFacts,
568+
invoke: async () => ({ ok: true, data: {} }),
569+
}),
570+
);
571+
572+
expect(response?.ok).toBe(true);
573+
if (!response?.ok) return;
574+
expect(response.data?.availableCommands).not.toContain(PUBLIC_COMMANDS.appState);
575+
});
576+
506577
test('capabilities accepts a stopped Android AVD placeholder for explicit platform discovery', async () => {
507578
const stoppedAvd: DeviceInfo = {
508579
platform: 'android',

0 commit comments

Comments
 (0)