Skip to content

Commit 081264a

Browse files
committed
fix(daemon): answer the named-session refusal with its own reason at every seam
Round-2 review found #3674's refusal reaching some callers as an untyped event. `get`/`is` answered a missing session with the generic "no active session" error before the provenance guard could run; `record start` let its app-scope INVALID_ARGS refusal win over a session that was gone altogether; `appstate` carried no typed details and refused requests that had also stated a concrete device. The refusal details now have one producer, `namedSessionNotFoundDetails` beside its sibling builders, that the guard's AppError and `appstate`'s platform-aware response both build from; each seam orders the guard before its own missing-session refusal; `appstate` preserves a request naming an identity selector, matching the resolution guard. The guard module's function-scoped import is confined to the missing-session branch it can fire on: that keeps the eager- closure gate at parity and removes a first-time transform cost from the held-session wait path, which under coverage instrumentation alone overran `wait-runtime.test.ts`'s fake-timer budget at the unconditional form (3/3 deterministic failures restored, 3/3 passes at this form). `namesSessionExplicitly` now accepts the generic flag-record shape the batch runner carries, fixing the TS2345 the batch call site raised.
1 parent 6df0362 commit 081264a

10 files changed

Lines changed: 196 additions & 29 deletions

File tree

‎packages/daemon/src/core/explicit-session-resolution.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell';
33
import { namesSessionExplicitly } from '@agent-device/kernel/contracts';
44
import {
55
AppError,
6-
PRE_DISPATCH_REFUSAL_REASONS,
6+
namedSessionNotFoundDetails,
77
type RefusalDetails,
88
} from '@agent-device/kernel/errors';
99
import { hasDeviceSelectionInput } from './device/device-selector-intent.ts';
@@ -18,14 +18,15 @@ export function namedSessionNotFoundError(sessionAddress: string): AppError {
1818
return new AppError(
1919
'SESSION_NOT_FOUND',
2020
`No active session "${sessionAddress}". Run agent-device open <app> --session ${sessionArg} first, or omit --session to run against a device selector.`,
21+
// One producer for the refusal shape: the reason, dispatched marker, and session address come
22+
// from the kernel builder every named-session seam shares (#3674); only this site's message
23+
// adds the open/omit guidance and the session-list hint.
2124
{
22-
reason: PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound,
23-
dispatched: 'no',
24-
session: sessionAddress,
25+
...namedSessionNotFoundDetails(sessionAddress),
2526
hint:
2627
'Run agent-device session list to see the sessions this daemon holds. ' +
2728
"A daemon that was replaced or restarted starts without its predecessor's sessions.",
28-
} satisfies RefusalDetails<(typeof PRE_DISPATCH_REFUSAL_REASONS)['namedSessionNotFound']>,
29+
} satisfies RefusalDetails<'named_session_not_found'>,
2930
);
3031
}
3132

‎packages/daemon/src/core/snapshot-session.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,16 @@ export async function resolveSessionDevice(
1414
) {
1515
const ref = boundRef ?? sessionStore.lookup(sessionName);
1616
const session = ref ? sessionStore.requireCurrent(ref) : undefined;
17-
const { requireNamedSessionHoldsDevice } = await import('./explicit-session-resolution.ts');
18-
requireNamedSessionHoldsDevice({ req, sessionAddress: sessionName, session });
17+
// The guard asks whether a *missing* session was named, so a held session answers it for free
18+
// and the refused path is the only one that loads the module — keeping the guard off the eager
19+
// closure of every request that resolves through here (ADR-0019 loading shape, #3674). It also
20+
// keeps a first-time module load out of the held-session hot path, whose transform cost under
21+
// coverage instrumentation alone overran `wait-runtime.test.ts`'s fake-timer budget when the
22+
// import ran unconditionally.
23+
if (!session) {
24+
const { requireNamedSessionHoldsDevice } = await import('./explicit-session-resolution.ts');
25+
requireNamedSessionHoldsDevice({ req, sessionAddress: sessionName, session });
26+
}
1927
const device = session?.device ?? (await resolveTargetDevice(req.flags ?? {}));
2028
return { ref, session, device };
2129
}

‎packages/daemon/src/execution/selector-runtime-backend.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,21 @@ async function resolveSelectorRuntimeDevice(
115115
params.captureProof ??= {};
116116
const ref = params.sessionStore.lookup(params.sessionName);
117117
const session = ref?.session;
118+
// Ordered before the required-session return on purpose: a request that *named* this address
119+
// deserves the typed named-session refusal, not the generic one; one that named nothing still
120+
// lands on noActiveSessionError below, which is its own pre-existing refusal. The guard can only
121+
// fire for a missing session, so only that path pays the function-scoped import (ADR-0019
122+
// loading shape).
123+
if (!session) {
124+
const { requireNamedSessionHoldsDevice } =
125+
await import('../core/explicit-session-resolution.ts');
126+
requireNamedSessionHoldsDevice({
127+
req: params.req,
128+
sessionAddress: params.sessionName,
129+
session,
130+
});
131+
}
118132
if (!session && requireSession) return { ok: false, response: noActiveSessionError() };
119-
const { requireNamedSessionHoldsDevice } = await import('../core/explicit-session-resolution.ts');
120-
requireNamedSessionHoldsDevice({
121-
req: params.req,
122-
sessionAddress: params.sessionName,
123-
session,
124-
});
125133
const device = session?.device ?? (await resolveTargetDevice(params.req.flags ?? {}));
126134
return { ok: true, ref, session, device };
127135
}

‎packages/daemon/src/server/__tests__/request-router-named-session.test.ts‎

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@ import { test, expect } from 'vitest';
33
import path from 'node:path';
44
import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts';
55
import {
6+
createLifecycleDeviceRuntimeGatewaySpies,
67
createRequestHandler,
78
lifecycleDeviceRuntimeGateway,
89
} from '../../__tests__/support/test-device-runtime-gateway.ts';
910
import type { DaemonRequest } from '../../core/daemon-request.ts';
11+
import type { DeviceRuntimeGateway } from '@agent-device/contracts/platform-runtime';
12+
import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations';
1013
import { LeaseRegistry } from '../../resources/lease-registry.ts';
1114
import { makeSessionStore } from '../../__tests__/support/store-factory.ts';
1215
import type { DeviceInfo } from '@agent-device/kernel/device';
@@ -35,15 +38,18 @@ const BOOTED_SIMULATORS: DeviceInfo[] = [
3538
bootedSimulator('SIM-B', 'Perf iPhone 17'),
3639
];
3740

38-
function makeHandler(listings: { count: number }) {
41+
function makeHandler(
42+
listings: { count: number },
43+
deviceRuntimeGateway: DeviceRuntimeGateway<PlatformRuntimeOperations> = lifecycleDeviceRuntimeGateway,
44+
) {
3945
const sessionStore = makeSessionStore('agent-device-router-named-session-');
4046
const handler = createRequestHandler({
4147
createCommandSurface: fakeCreateCommandSurface,
4248
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
4349
token: 'test-token',
4450
sessionStore,
4551
leaseRegistry: new LeaseRegistry(),
46-
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
52+
deviceRuntimeGateway,
4753
deviceInventoryGateways: createTestDeviceInventoryGateways({
4854
local: async () => {
4955
listings.count += 1;
@@ -90,6 +96,39 @@ test('the refusal answers without listing the host devices at all', async () =>
9096
expect(listings.count).toBe(0);
9197
});
9298

99+
test('a required-session command naming a missing session gets the typed refusal, not the generic one', async () => {
100+
// `get` requires a session, so its seam used to answer any missing session with the generic
101+
// "no active session" error before the provenance check could run. A caller that *named* the
102+
// session still deserves to learn which address is gone — the same event, the same typed reason.
103+
const listings = { count: 0 };
104+
const { handler } = makeHandler(listings);
105+
106+
const response = await handler(request({ command: 'get', positionals: ['text', '@ref-1'] }));
107+
108+
expect(response.ok).toBe(false);
109+
if (response.ok) return;
110+
expect(response.error.code).toBe('SESSION_NOT_FOUND');
111+
expect(response.error.details?.reason).toBe(PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
112+
expect(response.error.details?.session).toBe(LOST_SESSION);
113+
expect(listings.count).toBe(0);
114+
});
115+
116+
test('a record start naming a missing session answers on the session, not on app scope', async () => {
117+
// `record start` defaults to app scope and used to answer a missing session with the
118+
// app-session INVALID_ARGS refusal. When the session itself is gone, the session is the first
119+
// cause, and the typed named-session refusal wins over the record-specific one.
120+
const listings = { count: 0 };
121+
const { handler } = makeHandler(listings);
122+
123+
const response = await handler(request({ command: 'record', positionals: ['start'] }));
124+
125+
expect(response.ok).toBe(false);
126+
if (response.ok) return;
127+
expect(response.error.code).toBe('SESSION_NOT_FOUND');
128+
expect(response.error.details?.reason).toBe(PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
129+
expect(response.error.details?.session).toBe(LOST_SESSION);
130+
});
131+
93132
test('the same command with no session named still resolves a device sessionlessly', async () => {
94133
// The closest negative: same daemon, same two booted simulators, same command. What changes is
95134
// only whether the caller named a session, and that is what the answer must turn on.
@@ -108,12 +147,21 @@ test('the same command with no session named still resolves a device sessionless
108147

109148
test('a named session beside a device selector keeps honouring the device it names', async () => {
110149
// The other closest negative: the same missing session, but the request states its target
111-
// outright. Then the session is not what is missing and the refusal must stay out of the way.
150+
// outright. Then the session is not what is missing and the refusal must stay out of the way —
151+
// proven by the runtime gateway actually binding the named simulator, not by the absence of a
152+
// particular error code (AMBIGUOUS_MATCH would satisfy a weaker assertion).
112153
const listings = { count: 0 };
113-
const { handler } = makeHandler(listings);
154+
const { gateway, inspectFacts } = createLifecycleDeviceRuntimeGatewaySpies();
155+
const { handler } = makeHandler(listings, gateway);
114156

115157
const response = await handler(request({ flags: { platform: 'ios', udid: 'SIM-A' } }));
116158

159+
// Positive proof, not an absence: the runtime lane inspected SIM-A (and never SIM-B), so the
160+
// request's stated target won. Any refusal after that point is the device's own — here the
161+
// iOS app-session rule — and never the named-session one the missing session would answer.
162+
const inspectedDeviceIds = inspectFacts.mock.calls.map(([call]) => call.id);
163+
expect(inspectedDeviceIds).toContain('SIM-A');
164+
expect(inspectedDeviceIds).not.toContain('SIM-B');
117165
if (!response.ok) {
118166
expect(response.error.details?.reason).not.toBe(
119167
PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound,
@@ -123,12 +171,20 @@ test('a named session beside a device selector keeps honouring the device it nam
123171
});
124172

125173
test('a sessionless close naming a missing session answers on the session', async () => {
126-
const { handler } = makeHandler({ count: 0 });
174+
// The close fall-through is the sibling of the snapshot one: it names the missing session with
175+
// the same typed refusal and resolves no device at all. The generic SESSION_NOT_FOUND the
176+
// sessionless close used to answer must not satisfy this.
177+
const listings = { count: 0 };
178+
const { handler } = makeHandler(listings);
127179

128180
const response = await handler(request({ command: 'close', positionals: ['com.example.app'] }));
129181

130182
expect(response.ok).toBe(false);
131183
if (response.ok) return;
132184
expect(response.error.code).toBe('SESSION_NOT_FOUND');
133185
expect(response.error.message).toContain(`No active session "${LOST_SESSION}"`);
186+
expect(response.error.details?.reason).toBe(PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
187+
expect(response.error.details?.dispatched).toBe('no');
188+
expect(response.error.details?.session).toBe(LOST_SESSION);
189+
expect(listings.count).toBe(0);
134190
});

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

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
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 { makeSessionStore } from '../../../__tests__/support/handlers/session-test-harness.ts';
44
import { handleAppStateCommand } from '../session-appstate.ts';
5+
import { PRE_DISPATCH_REFUSAL_REASONS } from '@agent-device/kernel/errors';
6+
import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve';
7+
import { createUnavailableRuntimeFactsForTest } from '@agent-device/test-kit';
8+
import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime';
9+
import type { DeviceInfo } from '@agent-device/kernel/device';
510
import type { DaemonRequest } from '../../../core/daemon-request.ts';
611

712
function appStateRequest(session: string, flags: DaemonRequest['flags']): DaemonRequest {
@@ -21,6 +26,10 @@ test('appstate returns missing-session error for explicit session flag', async (
2126
if (!response.ok) {
2227
expect(response.error.code).toBe('SESSION_NOT_FOUND');
2328
expect(response.error.message).toMatch(/Run open with --session named first/i);
29+
// The same typed refusal every named-session seam answers with (#3674).
30+
expect(response.error.details?.reason).toBe(PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
31+
expect(response.error.details?.dispatched).toBe('no');
32+
expect(response.error.details?.session).toBe('named');
2433
}
2534
});
2635

@@ -60,6 +69,53 @@ test('appstate --platform apple missing-session error never suggests omitting --
6069
}
6170
});
6271

72+
test('appstate with a named session and an identity device selector keeps the stated target', async () => {
73+
// Same priority as the resolution guard (#3674): the request names a session this daemon lost
74+
// but states a concrete device, so it is not answered on the missing session. It resolves the
75+
// stated device and reaches that device's own runtime admission — proven by the resolution and
76+
// fact inspection naming emulator-5554 — and any refusal is the device's, never the named one.
77+
const device: DeviceInfo = {
78+
platform: 'android',
79+
id: 'emulator-5554',
80+
name: 'Pixel 9',
81+
kind: 'emulator',
82+
target: 'mobile',
83+
booted: true,
84+
};
85+
// This file's harness stubs device resolution; this test drives that stub and asserts the
86+
// request's stated identity reaches it.
87+
const resolved = vi.mocked(resolveTargetDevice).mockResolvedValue(device);
88+
const inspected: string[] = [];
89+
try {
90+
const response = await handleAppStateCommand({
91+
platformServices: daemonPlatformServicesFixture(),
92+
req: appStateRequest('named', { session: 'named', platform: 'android', device: 'Pixel 9' }),
93+
sessionName: 'named',
94+
sessionStore: makeSessionStore(),
95+
inspectFacts: async (inspectedDevice) => {
96+
inspected.push(inspectedDevice.id);
97+
return createUnavailableRuntimeFactsForTest(inspectedDevice, localRuntimeOwner('android'), {
98+
available: false,
99+
reason: 'owner-capability-missing',
100+
});
101+
},
102+
});
103+
104+
expect(resolved).toHaveBeenCalledWith(
105+
expect.objectContaining({ platform: 'android', device: 'Pixel 9' }),
106+
expect.anything(),
107+
);
108+
expect(inspected).toEqual(['emulator-5554']);
109+
if (!response.ok) {
110+
expect(response.error.details?.reason).not.toBe(
111+
PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound,
112+
);
113+
}
114+
} finally {
115+
resolved.mockReset();
116+
}
117+
});
118+
63119
test('appstate refuses --platform ios without a session at the message level', async () => {
64120
const response = await handleAppStateCommand({
65121
platformServices: daemonPlatformServicesFixture(),

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

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,19 @@ async function handleRecordCommandUnsafe(
9999
const { req, sessionName, sessionStore } = params;
100100
const existingRef = sessionStore.lookup(sessionName);
101101
const existingSession = existingRef?.session;
102+
// The named-session refusal runs before any record-specific refusal: a request whose session
103+
// this daemon lost is answered on the session first, whatever it wanted to record (#3674). The
104+
// guard can only fire for a missing session, so only that path pays the function-scoped import
105+
// (ADR-0019 loading shape).
106+
if (!existingSession) {
107+
const { requireNamedSessionHoldsDevice } =
108+
await import('../../core/explicit-session-resolution.ts');
109+
requireNamedSessionHoldsDevice({
110+
req,
111+
sessionAddress: sessionName,
112+
session: existingSession,
113+
});
114+
}
102115
const { plan, scope } = resolveRecordPlan(req, existingSession);
103116
if (plan.kind === 'start' && !isWholeScreenRecordingScope(scope) && !existingSession) {
104117
return missingAppSessionResponse(req);
@@ -140,13 +153,6 @@ async function resolveRecordingSession(
140153
params: RecordRuntimeHandlerParams,
141154
ref: SessionRef | undefined,
142155
): Promise<Readonly<{ session: SessionState; ref?: SessionRef; needsReadiness: boolean }>> {
143-
const { requireNamedSessionHoldsDevice } =
144-
await import('../../core/explicit-session-resolution.ts');
145-
requireNamedSessionHoldsDevice({
146-
req: params.req,
147-
sessionAddress: params.sessionName,
148-
session: ref?.session,
149-
});
150156
const device = ref?.session.device ?? (await resolveTargetDevice(params.req.flags ?? {}));
151157
await params.retainDeviceExecutionLock(device.id);
152158
if (ref) return { session: params.sessionStore.requireCurrent(ref), ref, needsReadiness: false };

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import type { DaemonResponse } from '@agent-device/kernel/contracts';
22
import { isApplePlatform, type PlatformSelector } from '@agent-device/kernel/device';
33
import { errorResponse, namesSessionExplicitly } from '@agent-device/kernel/contracts';
4+
import { namedSessionNotFoundDetails } from '@agent-device/kernel/errors';
5+
import { hasExplicitDeviceSelector } from '../../core/device/device-selector-intent.ts';
46
import {
57
requireSessionOrExplicitSelector,
68
resolveCommandDevice,
@@ -21,15 +23,19 @@ function appStateSessionNotFoundResponse(
2123
// Every Apple selector — `apple`, `ios`, or `macos` — answers appstate only from an open
2224
// session and its runner, so the "omit --session" route they would otherwise be pointed at
2325
// just reaches the session-required refusal. Send them straight to opening the session.
26+
// The details are the shared named-session refusal's, so one branch on
27+
// `named_session_not_found` sees the same shape wherever a lost session answers (#3674).
2428
if (isApplePlatform(platform)) {
2529
return errorResponse(
2630
'SESSION_NOT_FOUND',
2731
`No active session "${sessionName}". Run open with --session ${sessionName} first.`,
32+
namedSessionNotFoundDetails(sessionName),
2833
);
2934
}
3035
return errorResponse(
3136
'SESSION_NOT_FOUND',
3237
`No active session "${sessionName}". Run open with --session ${sessionName} first, or omit --session to query by device selector.`,
38+
namedSessionNotFoundDetails(sessionName),
3339
);
3440
}
3541

@@ -54,7 +60,13 @@ function admitAppStateTarget(params: RuntimeCommandHandlerParams): AppStateTarge
5460
const flags = req.flags ?? {};
5561
const normalizedPlatform = flags.platform;
5662

57-
if (!session && namesSessionExplicitly(req)) {
63+
// Same priority as the resolution guard (#3674), read for what this command can actually serve:
64+
// an identity selector (`--device`/`--udid`/`--serial`) states a concrete target the daemon can
65+
// answer sessionlessly — an Android device, or an iOS one the caller will run `open` against —
66+
// so the refusal stays out of the way there. A bare `--platform` filter states no device this
67+
// command can answer without a session (Apple appstate is session-required one step later), so
68+
// for those the typed named-session refusal remains the truest answer.
69+
if (!session && namesSessionExplicitly(req) && !hasExplicitDeviceSelector(flags)) {
5870
return { refusal: appStateSessionNotFoundResponse(sessionName, normalizedPlatform) };
5971
}
6072

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,8 @@ async function closeWithoutSession(params: {
433433
bindDevice?: BindDeviceRuntime;
434434
}): Promise<DaemonResponse> {
435435
const { req, sessionName, logPath, inspectFacts, bindDevice, platformServices } = params;
436+
// There is no session here by definition, so this is exactly the refused shape; the guard's own
437+
// provenance check still decides between the typed refusal and sessionless close.
436438
const { requireNamedSessionHoldsDevice } =
437439
await import('../../../core/explicit-session-resolution.ts');
438440
requireNamedSessionHoldsDevice({ req, sessionAddress: sessionName, session: undefined });

‎packages/kernel/src/contracts.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -261,10 +261,12 @@ export const NO_ACTIVE_SESSION_MESSAGE = 'No active session. Run open first.';
261261
* from the session string. Every request has a session *name*, because an unnamed one inherits the
262262
* workspace's own session address, so comparing names cannot answer this. Both carriers count:
263263
* every client sets `meta.sessionExplicit`, and the commands whose own input schema declares
264-
* `--session` also deliver the value in `flags.session`.
264+
* `--session` also deliver the value in `flags.session`. The flag bag reaches this predicate in
265+
* both shapes the wire carries it in: a command's declared flag type, or a generic record from a
266+
* runner that merges flags (batch steps); the string check below is what decides either way.
265267
*/
266268
export function namesSessionExplicitly(request: {
267-
flags?: { session?: unknown } | undefined;
269+
flags?: { session?: unknown } | Record<string, unknown> | undefined;
268270
meta?: { sessionExplicit?: boolean } | undefined;
269271
}): boolean {
270272
if (request.meta?.sessionExplicit === true) return true;

0 commit comments

Comments
 (0)