Skip to content

Commit c81bf0b

Browse files
committed
fix(daemon): thread the resolved session address through every recovery producer
The store key a request resolves — `cwd:<hash>:default` for an implicit session — was known upstream but dropped before the selector-conflict and lock-conflict producers, which then named `SessionState.name`. Both emitted `close --session default`, the unreachable recovery this PR fixes for DEVICE_IN_USE: `--session` marks the session explicit, so that command addresses a different session. `SessionRef` ({ address, session }) now carries the pair, so a recovery producer cannot be handed a record whose address was never resolved. `buildSessionRecoveryHint`, `assertSessionSelectorMatches` and `applyRequestLockPolicy` take it; `prepareLockedRequestBinding` and the Maestro replay route build it from the store key they already hold. Replaces the broad `SessionStore.entries()` with the store's own narrow lookups — `lookup`, `findByDevice`, `listRefs` — so callers receive the session with its address instead of enumerating raw key/record tuples. `session list` reports `address` alongside `name`, through the client contract and serializer, so its discovery output names a value `--session` accepts. Regressions run the production routes, not the helpers: router-level device-in-use, selector-conflict, lock-policy-conflict and `session list` cases open an implicit session and read the address back off the store, plus a typed-Maestro selector-conflict case. Each was observed red against the pre-fix behavior it pins. Refs #2031, #1394.
1 parent def3734 commit c81bf0b

21 files changed

Lines changed: 480 additions & 158 deletions

‎packages/contracts/src/client-device-view.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ export type AgentDeviceSessionDevice = {
6868

6969
export type AgentDeviceSession = {
7070
name: string;
71+
/**
72+
* The exact value `--session` must carry to address this session, which is not always `name`:
73+
* a session opened without `--session` is named `default` but stored — and addressed — as
74+
* `cwd:<hash>:default` (#2031/#1394). Optional only because a daemon older than the field does
75+
* not send it.
76+
*/
77+
address?: string;
7178
createdAt: number;
7279
sessionStateDir?: string;
7380
runnerLogPath?: string;

‎scripts/__tests__/help-conformance-sample-producers.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ export const SAMPLE_PRODUCERS: SampleProducer[] = [
365365
producer: 'the real session-open by-session conflict producer',
366366
sample: DEVICE_IN_USE_SAMPLE,
367367
render: () => {
368-
const owningSession = { name: 'checkout' } as SessionState;
368+
// An explicitly named session is stored under its own name, so address === name here.
369+
const owningSession = { address: 'checkout', session: { name: 'checkout' } as SessionState };
369370
const device = { id: 'SIM-001', name: 'iPhone 17 Pro' } as Parameters<
370371
typeof buildDeviceInUseBySessionError
371372
>[1];
372-
// An explicitly named session addresses itself, so the sample text is unchanged.
373-
const response = buildDeviceInUseBySessionError(owningSession, device, owningSession.name);
373+
const response = buildDeviceInUseBySessionError(owningSession, device);
374374
assertErrorResponse(response, 'the by-session conflict');
375375
return renderErrorResponse(response);
376376
},

‎src/client/client-normalizers.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ export function normalizeSession(value: unknown): AgentDeviceSession {
122122
};
123123
return {
124124
name,
125+
address: readOptionalString(record, 'address'),
125126
createdAt: readRequiredNumber(record, 'createdAt'),
126127
sessionStateDir: readOptionalString(record, 'sessionStateDir'),
127128
runnerLogPath: readOptionalString(record, 'runnerLogPath'),

‎src/daemon/__tests__/request-lock-identity-policy.test.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { test } from 'vitest';
22
import assert from 'node:assert/strict';
33
import { AppError } from '@agent-device/kernel/errors';
44
import { applyRequestLockPolicy } from '../request-lock-policy.ts';
5-
import type { DaemonRequest, SessionState } from '../types.ts';
5+
import type { DaemonRequest, SessionRef, SessionState } from '../types.ts';
66

77
/**
88
* One table for the device-identity half of the session lock. A device identity selector
@@ -172,6 +172,11 @@ const ROWS: Row[] = [
172172
},
173173
];
174174

175+
/** Every row's session is explicitly named, so it is stored under — and addressed by — its name. */
176+
function ref(session: SessionState | undefined): SessionRef | undefined {
177+
return session ? { address: session.name, session } : undefined;
178+
}
179+
175180
for (const row of ROWS) {
176181
test(`session lock: ${row.name}`, () => {
177182
const request = {
@@ -187,7 +192,7 @@ for (const row of ROWS) {
187192
} as DaemonRequest;
188193

189194
if (row.expect.kind === 'refused') {
190-
const error = assertThrowsAppError(() => applyRequestLockPolicy(request, row.session));
195+
const error = assertThrowsAppError(() => applyRequestLockPolicy(request, ref(row.session)));
191196
assert.equal(error.code, 'INVALID_ARGS');
192197
assert.ok(
193198
error.message.includes(row.expect.namesSelector),
@@ -212,7 +217,7 @@ for (const row of ROWS) {
212217
return;
213218
}
214219

215-
const applied = applyRequestLockPolicy(request, row.session);
220+
const applied = applyRequestLockPolicy(request, ref(row.session));
216221
for (const [key, value] of Object.entries(row.expect.keepsSelectors)) {
217222
assert.equal(
218223
(applied.flags as Record<string, unknown>)[key],

‎src/daemon/__tests__/request-lock-policy.test.ts‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { test } from 'vitest';
22
import assert from 'node:assert/strict';
33
import { applyRequestLockPolicy } from '../request-lock-policy.ts';
4-
import type { SessionState } from '../types.ts';
4+
import type { SessionRef, SessionState } from '../types.ts';
55

66
const IOS_SESSION: SessionState = {
77
name: 'qa-ios',
@@ -32,6 +32,11 @@ const ANDROID_SESSION: SessionState = {
3232
},
3333
};
3434

35+
/** Both fixtures are explicitly named, so each is stored under — and addressed by — its name. */
36+
function ref(session: SessionState): SessionRef {
37+
return { address: session.name, session };
38+
}
39+
3540
test('allows compatible fresh-session selectors under request lock policy', () => {
3641
const req = applyRequestLockPolicy({
3742
token: 'token',
@@ -135,7 +140,7 @@ test('rejects existing-session selector conflicts under request lock policy', ()
135140
lockPolicy: 'reject',
136141
},
137142
},
138-
IOS_SESSION,
143+
ref(IOS_SESSION),
139144
),
140145
/--serial=emulator-5554/i,
141146
);
@@ -194,7 +199,7 @@ test('allows matching redundant selectors for existing sessions', () => {
194199
lockPolicy: 'reject',
195200
},
196201
},
197-
IOS_SESSION,
202+
ref(IOS_SESSION),
198203
);
199204

200205
assert.equal(req.flags?.udid, 'SIM-001');
@@ -217,7 +222,7 @@ test('rejects mismatching udid selectors for existing sessions', () => {
217222
lockPolicy: 'reject',
218223
},
219224
},
220-
IOS_SESSION,
225+
ref(IOS_SESSION),
221226
),
222227
/--udid=SIM-999/i,
223228
);
@@ -238,7 +243,7 @@ test('allows matching serial selectors for existing android sessions', () => {
238243
lockPolicy: 'reject',
239244
},
240245
},
241-
ANDROID_SESSION,
246+
ref(ANDROID_SESSION),
242247
);
243248

244249
assert.equal(req.flags?.serial, 'emulator-5554');
@@ -261,7 +266,7 @@ test('rejects mismatching device selectors for existing android sessions', () =>
261266
lockPolicy: 'reject',
262267
},
263268
},
264-
ANDROID_SESSION,
269+
ref(ANDROID_SESSION),
265270
),
266271
/--device=Pixel 8/i,
267272
);
@@ -283,7 +288,7 @@ test('rejects mismatching serial selectors for existing android sessions', () =>
283288
lockPolicy: 'reject',
284289
},
285290
},
286-
ANDROID_SESSION,
291+
ref(ANDROID_SESSION),
287292
),
288293
/--serial=emulator-9999/i,
289294
);
@@ -306,7 +311,7 @@ test('strips only conflicting scope selectors for existing sessions, keeping mat
306311
lockPolicy: 'strip',
307312
},
308313
},
309-
IOS_SESSION,
314+
ref(IOS_SESSION),
310315
);
311316

312317
assert.equal(req.flags?.platform, 'ios');
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
import { createTestDeviceInventoryGateways } from '../../__tests__/test-utils/device-inventory-gateways.ts';
2+
import { legacyDispatchCapture } from './legacy-snapshot-capture-fixture.ts';
3+
import { test, expect, vi, beforeEach } from 'vitest';
4+
import os from 'node:os';
5+
import path from 'node:path';
6+
import { getResolveTargetDeviceMock } from './request-router-dispatch-mocks.ts';
7+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
8+
9+
vi.mock('../device-ready.ts', () => ({ ensureDeviceReady: vi.fn(async () => {}) }));
10+
vi.mock('../../utils/host-process.ts', async (importOriginal) => {
11+
const actual = await importOriginal<typeof import('../../utils/host-process.ts')>();
12+
return { ...actual, readProcessStartTime: vi.fn(() => 'test-process-start') };
13+
});
14+
// Opening a session runs owned-lease cleanup, which pattern-kills stale xcodebuild runners with a
15+
// real `pkill -f`; the session ids here are fabricated, so stub the tool seam (#1824).
16+
vi.mock('../../platforms/apple/core/tool-provider.ts', async (importOriginal) => {
17+
const actual =
18+
await importOriginal<typeof import('../../platforms/apple/core/tool-provider.ts')>();
19+
return {
20+
...actual,
21+
runAppleToolCommand: vi.fn(async () => ({ exitCode: 0, stdout: '', stderr: '' })),
22+
};
23+
});
24+
25+
import {
26+
createRequestHandler,
27+
lifecycleDeviceRuntimeGateway,
28+
} from './test-device-runtime-gateway.ts';
29+
import { LeaseRegistry } from '../lease-registry.ts';
30+
import { ensureDeviceReady } from '../device-ready.ts';
31+
import { awaitFixtureReadiness } from './application-lifecycle-runtime-fixture.ts';
32+
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
33+
import type { DeviceInfo } from '@agent-device/kernel/device';
34+
import type { DaemonRequest, DaemonResponse } from '../types.ts';
35+
36+
/**
37+
* The production route for the #2031/#1394 defect: a request without `--session` resolves the
38+
* store key `cwd:<hash>:default`, loads THAT entry, and hands it to a recovery producer whose
39+
* record is only named `default`. Every recovery below must name the store key, because
40+
* `--session default` marks the session explicit and therefore addresses a different session.
41+
*
42+
* The address is never hand-written here — it is read back from the store the router wrote, so a
43+
* regression that reverts to `SessionState.name` cannot be papered over by an updated constant.
44+
*/
45+
const SCOPED_ADDRESS_PATTERN = /^cwd:[0-9a-f]{16}:default$/;
46+
47+
const mockResolveTargetDevice = vi.mocked(getResolveTargetDeviceMock());
48+
const mockEnsureDeviceReady = vi.mocked(ensureDeviceReady);
49+
const mockAwaitFixtureReadiness = vi.mocked(awaitFixtureReadiness);
50+
51+
function makeIosDevice(id: string): DeviceInfo {
52+
return {
53+
platform: 'apple',
54+
id,
55+
name: `iPhone ${id}`,
56+
kind: 'simulator',
57+
target: 'mobile',
58+
booted: true,
59+
};
60+
}
61+
62+
function createHandler(sessionStore: ReturnType<typeof makeSessionStore>) {
63+
return createRequestHandler({
64+
logPath: path.join(os.tmpdir(), 'daemon.log'),
65+
token: 'test-token',
66+
sessionStore,
67+
leaseRegistry: new LeaseRegistry(),
68+
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
69+
deviceInventoryGateways: createTestDeviceInventoryGateways(),
70+
trackDownloadableArtifact: () => 'artifact-id',
71+
});
72+
}
73+
74+
/** A request as the CLI sends it when the caller passed no `--session`: named, but not explicit. */
75+
function implicitRequest(params: {
76+
command: string;
77+
cwd: string;
78+
requestId: string;
79+
flags?: Record<string, unknown>;
80+
meta?: Record<string, unknown>;
81+
}): DaemonRequest {
82+
return {
83+
token: 'test-token',
84+
session: 'default',
85+
command: params.command,
86+
positionals: [],
87+
flags: params.flags ?? {},
88+
meta: { requestId: params.requestId, cwd: params.cwd, ...params.meta },
89+
} as DaemonRequest;
90+
}
91+
92+
/** Opens the implicit session and returns the store key the router filed it under. */
93+
async function openImplicitSession(
94+
handler: ReturnType<typeof createHandler>,
95+
sessionStore: ReturnType<typeof makeSessionStore>,
96+
cwd: string,
97+
): Promise<string> {
98+
const response = await handler(
99+
implicitRequest({ command: 'open', cwd, requestId: 'req-implicit-open' }),
100+
);
101+
expect(response.ok).toBe(true);
102+
const refs = sessionStore.listRefs();
103+
expect(refs).toHaveLength(1);
104+
const address = refs[0]!.address;
105+
// The defect in one line: the record is named `default`, the store key is not.
106+
expect(refs[0]!.session.name).toBe('default');
107+
expect(address).toMatch(SCOPED_ADDRESS_PATTERN);
108+
return address;
109+
}
110+
111+
function errorHint(response: DaemonResponse): string {
112+
expect(response.ok).toBe(false);
113+
if (response.ok) return '';
114+
return String(response.error.hint ?? '');
115+
}
116+
117+
function expectAddressableRecovery(hint: string, address: string): void {
118+
expect(hint).toContain(`--session ${address}`);
119+
expect(hint).not.toMatch(/--session default\b/);
120+
}
121+
122+
beforeEach(() => {
123+
legacyDispatchCapture.mockReset();
124+
legacyDispatchCapture.mockResolvedValue({});
125+
mockResolveTargetDevice.mockReset();
126+
mockEnsureDeviceReady.mockReset();
127+
mockEnsureDeviceReady.mockResolvedValue(undefined);
128+
mockAwaitFixtureReadiness.mockReset();
129+
mockAwaitFixtureReadiness.mockResolvedValue(undefined);
130+
});
131+
132+
test('device-in-use against an implicit session names its store key, not "default"', async () => {
133+
const sessionStore = makeSessionStore('agent-device-router-address-');
134+
const cwd = mkdtempForTestSync('agent-device-scope-');
135+
const device = makeIosDevice('SIM-IN-USE');
136+
mockResolveTargetDevice.mockResolvedValue(device);
137+
const handler = createHandler(sessionStore);
138+
const address = await openImplicitSession(handler, sessionStore, cwd);
139+
140+
const response = await handler({
141+
token: 'test-token',
142+
session: 'checkout',
143+
command: 'open',
144+
positionals: [],
145+
flags: { platform: 'ios' },
146+
meta: { requestId: 'req-explicit-open', cwd, sessionExplicit: true },
147+
} as DaemonRequest);
148+
149+
expect(response.ok).toBe(false);
150+
if (response.ok) return;
151+
expect(response.error.code).toBe('DEVICE_IN_USE');
152+
expect(response.error.message).toContain(`session "${address}"`);
153+
expect(response.error.details?.session).toBe(address);
154+
expectAddressableRecovery(errorHint(response), address);
155+
expect(errorHint(response)).toContain(`agent-device close --session ${address}`);
156+
});
157+
158+
test('selector conflict on an implicit session names its store key, not "default"', async () => {
159+
const sessionStore = makeSessionStore('agent-device-router-address-');
160+
const cwd = mkdtempForTestSync('agent-device-scope-');
161+
mockResolveTargetDevice.mockResolvedValue(makeIosDevice('SIM-BOUND'));
162+
const handler = createHandler(sessionStore);
163+
const address = await openImplicitSession(handler, sessionStore, cwd);
164+
165+
const response = await handler(
166+
implicitRequest({
167+
command: 'home',
168+
cwd,
169+
requestId: 'req-selector-conflict',
170+
flags: { udid: 'SIM-OTHER' },
171+
}),
172+
);
173+
174+
expect(response.ok).toBe(false);
175+
if (response.ok) return;
176+
expect(response.error.code).toBe('INVALID_ARGS');
177+
expect(response.error.message).toContain(`Session "${address}"`);
178+
expectAddressableRecovery(errorHint(response), address);
179+
});
180+
181+
test('lock-policy conflict on an implicit session names its store key, not "default"', async () => {
182+
const sessionStore = makeSessionStore('agent-device-router-address-');
183+
const cwd = mkdtempForTestSync('agent-device-scope-');
184+
mockResolveTargetDevice.mockResolvedValue(makeIosDevice('SIM-LOCKED'));
185+
const handler = createHandler(sessionStore);
186+
const address = await openImplicitSession(handler, sessionStore, cwd);
187+
188+
const response = await handler(
189+
implicitRequest({
190+
command: 'home',
191+
cwd,
192+
requestId: 'req-lock-conflict',
193+
flags: { udid: 'SIM-OTHER' },
194+
meta: { lockPolicy: 'reject' },
195+
}),
196+
);
197+
198+
expect(response.ok).toBe(false);
199+
if (response.ok) return;
200+
expect(response.error.code).toBe('INVALID_ARGS');
201+
expect(response.error.message).toContain(`session "${address}"`);
202+
expect(response.error.details?.session).toBe(address);
203+
expectAddressableRecovery(errorHint(response), address);
204+
});
205+
206+
test('session list reports the address an implicit session answers to alongside its name', async () => {
207+
const sessionStore = makeSessionStore('agent-device-router-address-');
208+
const cwd = mkdtempForTestSync('agent-device-scope-');
209+
mockResolveTargetDevice.mockResolvedValue(makeIosDevice('SIM-LISTED'));
210+
const handler = createHandler(sessionStore);
211+
const address = await openImplicitSession(handler, sessionStore, cwd);
212+
213+
const response = await handler(
214+
implicitRequest({ command: 'session_list', cwd, requestId: 'req-session-list' }),
215+
);
216+
217+
expect(response.ok).toBe(true);
218+
if (!response.ok) return;
219+
const sessions = response.data?.sessions as { name: string; address: string }[] | undefined;
220+
expect(sessions).toHaveLength(1);
221+
expect(sessions?.[0]?.name).toBe('default');
222+
expect(sessions?.[0]?.address).toBe(address);
223+
expect(sessions?.[0]?.address).toMatch(SCOPED_ADDRESS_PATTERN);
224+
});

0 commit comments

Comments
 (0)