Skip to content

Commit 633115a

Browse files
committed
refactor(daemon): decide the appstate named-session refusal once, at admission (#3674)
The device-runtime lane re-read the session store and re-ran the naming check after awaiting device resolution, so a store change mid-await could move the request into a different error family than the one it was admitted into, and the classifier was spelled out twice. Admission now carries one typed namedSessionMissing fact, decided from the same store read as the admission session itself. A bare --udid still resolves its stated target first and answers the typed reason from the resolved device — pinned by asserting the resolution call, not just the payload — and the store-changes-during-resolution case pins the snapshot semantics. The manifest-first docstrings say what actually happens: the manifest's identity is re-resolved against the host for the live device fields, with the session/device assertions failing closed. Co-Authored-Worked-On-By: Claude
1 parent 67e4397 commit 633115a

5 files changed

Lines changed: 104 additions & 21 deletions

File tree

‎packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,9 @@ export function screenRecordingManifestIsTerminal(params: ScreenRecordingManifes
7979
* The device a stop without a held session must be answered on: the one the session's durable
8080
* manifest names, when a decodable manifest exists. `undefined` means there is nothing to recover
8181
* from, and a caller that addressed a session answers on the session instead of choosing a device.
82-
* The device is not re-picked from the host; it is read from the manifest the named session
83-
* addresses, and `assertManifestBelongsToRequest` still fails the request closed when the
84-
* resolved device or the session address does not match what the manifest recorded.
82+
* The caller still resolves this identity against the host to recover the live device fields, and
83+
* `assertManifestBelongsToRequest` still fails the request closed when the resolved device or the
84+
* session address does not match what the manifest recorded.
8585
*/
8686
export function screenRecordingManifestDevice(
8787
params: ScreenRecordingManifestParams,

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

Lines changed: 70 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,13 @@ test('appstate --platform apple missing-session error never suggests omitting --
6969
}
7070
});
7171

72-
test('appstate --udid with no --platform still answers the typed reason for a named missing session', async () => {
72+
test('appstate --udid with no --platform resolves the stated device and THEN answers the typed reason', async () => {
7373
// `--udid` is the Apple identity flag, so a bare `--udid <ios>` reaches the device-runtime lane
7474
// and lands on an Apple device. The commands.md row promises the typed reason "even with an
75-
// explicit device", so this lane — the only appstate route that resolves a device — answers it
76-
// too, not the reasonless session-required refusal.
75+
// explicit device", so this lane answers it too — and it answers it from the resolved device,
76+
// NOT from a pre-resolution guard: the request states a target, and the route must first prove
77+
// that target by resolving it. A refusal answered before resolution is a different policy, so
78+
// the resolution call itself is the pin here.
7779
const iosSim: DeviceInfo = {
7880
platform: 'apple',
7981
appleOs: 'ios',
@@ -83,20 +85,84 @@ test('appstate --udid with no --platform still answers the typed reason for a na
8385
target: 'mobile',
8486
booted: true,
8587
};
86-
const resolved = vi.mocked(resolveTargetDevice).mockResolvedValue(iosSim);
88+
const resolved = vi.mocked(resolveTargetDevice);
89+
resolved.mockReset();
90+
resolved.mockResolvedValue(iosSim);
91+
// The refusal precedes runtime admission, so a fact read here would mean the lane queried a
92+
// device it had just refused; the pin is that it never gets that far.
93+
const inspected: string[] = [];
8794
try {
8895
const response = await handleAppStateCommand({
8996
platformServices: daemonPlatformServicesFixture(),
9097
req: appStateRequest('lost', { session: 'lost', udid: 'SIM-UDID-A' }),
9198
sessionName: 'lost',
9299
sessionStore: makeSessionStore(),
100+
inspectFacts: async (inspectedDevice) => {
101+
inspected.push(inspectedDevice.id);
102+
return createUnavailableRuntimeFactsForTest(inspectedDevice, localRuntimeOwner('ios'), {
103+
available: false,
104+
reason: 'owner-capability-missing',
105+
});
106+
},
93107
});
94108

95109
expect(response.ok).toBe(false);
96110
if (response.ok) return;
97111
expect(response.error.code).toBe('SESSION_NOT_FOUND');
98112
expect(response.error.details?.reason).toBe(PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
99113
expect(response.error.details?.session).toBe('lost');
114+
// Resolution ran, once, on the identity the request stated — the refusal is the device
115+
// runtime lane's, after the target was proven, not a guard that skipped the stated device.
116+
expect(resolved).toHaveBeenCalledTimes(1);
117+
expect(resolved).toHaveBeenCalledWith(
118+
expect.objectContaining({ udid: 'SIM-UDID-A' }),
119+
expect.anything(),
120+
);
121+
expect(inspected).toEqual([]);
122+
} finally {
123+
resolved.mockReset();
124+
}
125+
});
126+
127+
test('appstate keeps the admission-time named-session verdict when the store changes during resolution', async () => {
128+
// The error family is decided once, at admission. If another caller recreates the session
129+
// while this request is resolving its device, the Apple refusal this request was admitted into
130+
// stays the typed named-session one — a mid-await store change must not silently switch the
131+
// request into a different family (nor answer from a session it never admitted).
132+
const iosSim: DeviceInfo = {
133+
platform: 'apple',
134+
appleOs: 'ios',
135+
id: 'SIM-UDID-C',
136+
name: 'iPhone Air',
137+
kind: 'simulator',
138+
target: 'mobile',
139+
booted: true,
140+
};
141+
const sessionStore = makeSessionStore();
142+
const resolved = vi.mocked(resolveTargetDevice);
143+
resolved.mockReset();
144+
resolved.mockImplementation(async () => {
145+
// The concurrent store change, planted mid-await exactly where a re-read would disagree.
146+
sessionStore.publish('lost', {
147+
name: 'lost',
148+
device: iosSim,
149+
createdAt: 1,
150+
actions: [],
151+
});
152+
return iosSim;
153+
});
154+
try {
155+
const response = await handleAppStateCommand({
156+
platformServices: daemonPlatformServicesFixture(),
157+
req: appStateRequest('lost', { session: 'lost', udid: 'SIM-UDID-C' }),
158+
sessionName: 'lost',
159+
sessionStore,
160+
});
161+
162+
expect(response.ok).toBe(false);
163+
if (response.ok) return;
164+
expect(response.error.details?.reason).toBe(PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
165+
expect(response.error.details?.session).toBe('lost');
100166
} finally {
101167
resolved.mockReset();
102168
}

‎packages/daemon/src/sessions/handlers/record-runtime.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,11 +174,12 @@ async function resolveRecordingSession(
174174
* A request that names a session this daemon does not hold and states no device is answered from
175175
* the durable manifest the session address finds — never from an unconstrained sweep of the host,
176176
* which with several booted devices would answer `AMBIGUOUS_MATCH` (or, worse, silently pick a
177-
* different device) before the manifest is read. A decodable manifest carries the exact device the
178-
* recording was started on, so the stop recovery resolves that device; a start, or a stop with no
179-
* decodable manifest to recover from, refuses with the named-session error. The manifest's own
180-
* session and device are still proven against the request by `assertManifestBelongsToRequest`
181-
* before anything is served, so a manifest belonging to another session or device fails closed.
177+
* different device) before the manifest is read. A decodable manifest names the exact device the
178+
* recording was started on; the stop recovery re-resolves that identity, so the host is asked
179+
* only for the device the manifest already specified. A start, or a stop with no decodable
180+
* manifest to recover from, refuses with the named-session error.
181+
* `assertManifestBelongsToRequest` still proves the resolved device and the session address
182+
* against the manifest before anything is served, so a mismatch fails closed.
182183
*
183184
* The two shapes that keep their chosen target are unchanged: a request that never named a
184185
* session resolves sessionlessly from its flags, and one that states a device selector resolves

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import {
55
publicPlatformString,
66
type DeviceInfo,
77
} from '@agent-device/kernel/device';
8-
import { namesSessionExplicitly } from '@agent-device/kernel/contracts';
98
import type { DaemonResponse } from '@agent-device/kernel/contracts';
109
import { resolveAndroidSerialAllowlist } from '@agent-device/kernel/device-isolation';
1110
import { admitRuntimeUse } from '../../core/runtime-admission.ts';
@@ -29,13 +28,14 @@ function sortedAndroidSerialAllowlist(value: string | undefined): string[] | und
2928
export async function queryDeviceRuntimeAppState(
3029
params: RuntimeCommandHandlerParams,
3130
device: DeviceInfo,
31+
namedSessionMissing: boolean,
3232
): Promise<DaemonResponse> {
3333
if (isIosFamily(device) || isMacOs(device)) {
34-
// A request that names a session this daemon does not hold and resolves onto an Apple device
35-
// is missing its session, not its device (#3674): the same typed refusal the session-required
36-
// selectors answer, whatever flag routed it here. A request that named no session keeps the
37-
// plain session-required refusal, which is the right advice for it.
38-
if (!params.sessionStore.get(params.sessionName) && namesSessionExplicitly(params.req)) {
34+
// A request admitted without the session it names (#3674) keeps the typed refusal whatever
35+
// flag routed it here — the fact comes from admission, so resolving the device cannot change
36+
// the error family. A request that named no session keeps the plain session-required refusal,
37+
// which is the right advice for it.
38+
if (namedSessionMissing) {
3939
return appStateSessionNotFoundResponse(params.sessionName, device.platform);
4040
}
4141
return appleSessionRequiredRefusal(isMacOs(device) ? 'macos' : 'ios');

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

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,17 @@ type AppStateSessionStoreEntry = ReturnType<RuntimeCommandHandlerParams['session
2222
type AppStateTargetDecision =
2323
| { refusal: DaemonResponse }
2424
| { answeredBy: 'apple-session'; session: AppStateSessionRecord }
25-
| { answeredBy: 'device-runtime'; session: AppStateSessionStoreEntry };
25+
| {
26+
answeredBy: 'device-runtime';
27+
session: AppStateSessionStoreEntry;
28+
/**
29+
* Decided from the same store read as `session`: the request names a session this daemon
30+
* does not hold. The device-runtime lane answers an Apple device from this admission-time
31+
* fact, not from a re-read after the await — resolution cannot change which error family
32+
* the request was admitted into.
33+
*/
34+
namedSessionMissing: boolean;
35+
};
2636

2737
/**
2838
* Has this appstate request an answerable target, and which authority answers it: the Apple
@@ -64,7 +74,13 @@ function admitAppStateTarget(params: RuntimeCommandHandlerParams): AppStateTarge
6474
if (useSessionStateForApple && session) {
6575
return { answeredBy: 'apple-session' as const, session };
6676
}
67-
return { answeredBy: 'device-runtime' as const, session };
77+
// Only an identity selector reaches the device-runtime lane with a named-but-missing session
78+
// (the guard above refused the rest); this is the one read that decides it.
79+
return {
80+
answeredBy: 'device-runtime' as const,
81+
session,
82+
namedSessionMissing: !session && namesSessionExplicitly(req),
83+
};
6884
}
6985

7086
/**
@@ -85,5 +101,5 @@ export async function handleAppStateCommand(
85101
flags: params.req.flags ?? {},
86102
platformServices: params.platformServices,
87103
});
88-
return await queryDeviceRuntimeAppState(params, device);
104+
return await queryDeviceRuntimeAppState(params, device, target.namedSessionMissing);
89105
}

0 commit comments

Comments
 (0)