Skip to content

Commit cc4c340

Browse files
committed
fix(remote): decide the platform family wherever a lease gets bound
The collapse added for the proxy binding was written inside resolveProxyLeaseState, so it only covered the policy that resolves a device itself. The default, cloud-webdriver, and deferred policies record their state through buildMaterializedLeaseState, which kept whatever selector the command was asked with: a connection opened as `connect --platform apple --lease-backend ios-instance` held an `ios-instance` lease while its own record said `apple`, the scope guard answered family-vs-leaf as no-conflict, and a later `--platform macos` went out as `apple` against the iOS device's lease instead of being refused. The rule now runs once, right where the lease backend is settled and before the allocate payload is built, so the record, the flags the request carries, and the lease request all name the leaf the backend rents. The proxy path keeps its own source — the resolved device — and the special case is gone. Two readers still face records that were never rewritten: a state whose lease already matched was never rebuilt, and one saved by an older binary still says `apple` on disk. Both ask one shared predicate now, which is also what `connect` uses to decide whether a connection is reusable — previously the family alias made `--platform macos` look like the connection it wasn't. The selector rule alone answers family-vs-leaf as a match, which stays right for a selection and wrong for a decided record, so both readings live in that one function. The backend-to-leaf map is the inverse of the platform-to-backend map and sits beside it, so the two axes cannot drift apart. A backend that names no platform (`ios-simulator`, a runner guard) and a connection with no backend keep the alias: nothing has decided the family there, and inventing a leaf is the same axis mistake pointed the other way. Four tests, each with its own kill: the default-policy bind records, requests, and allocates as `ios` then refuses `macos`; a stored `apple` record refuses the other leaf and never touches the lease; `connect` refuses to reuse an `apple`-bound connection for the other leaf; and the predicate's own boundaries sit beside its module.
1 parent 0c95f56 commit cc4c340

6 files changed

Lines changed: 333 additions & 29 deletions

File tree

‎packages/kernel/src/contracts.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { DaemonError } from './errors.ts';
22

33
export type { AppErrorCode } from './errors.ts';
44
export { defaultHintForCode, normalizeError } from './errors.ts';
5-
import type { PlatformSelector } from './device.ts';
5+
import type { PlatformSelector, PublicPlatform } from './device.ts';
66

77
const SESSION_RUNTIME_PLATFORMS = ['ios', 'android', 'harmonyos'] as const;
88
export type SessionRuntimePlatform = (typeof SESSION_RUNTIME_PLATFORMS)[number];
@@ -83,6 +83,24 @@ export function leaseBackendForPlatform(
8383
return platform === undefined ? undefined : LEASE_BACKEND_BY_PLATFORM[platform];
8484
}
8585

86+
/**
87+
* The public leaf platform a lease backend rents devices on — the inverse of
88+
* {@link leaseBackendForPlatform} for the backends that name a platform rather than a runner guard.
89+
*
90+
* A connection binds a platform at the same moment it binds a lease, and the lease is the stronger
91+
* evidence: it names the backend that is actually holding the device. `ios-simulator` maps to no
92+
* leaf because it is a runner/process guard below device leases, not a platform a selector names.
93+
*/
94+
const PLATFORM_BY_LEASE_BACKEND: Partial<Record<LeaseBackend, PublicPlatform>> = {
95+
'ios-instance': 'ios',
96+
'android-instance': 'android',
97+
'harmonyos-instance': 'harmonyos',
98+
};
99+
100+
export function platformForLeaseBackend(backend: LeaseBackend): PublicPlatform | undefined {
101+
return PLATFORM_BY_LEASE_BACKEND[backend];
102+
}
103+
86104
const DAEMON_SERVER_MODES = ['socket', 'http', 'dual'] as const;
87105
export type DaemonServerMode = (typeof DAEMON_SERVER_MODES)[number];
88106
const DAEMON_TRANSPORT_PREFERENCES = ['auto', 'socket', 'http'] as const;

‎src/__tests__/remote-connection-platform-axis.test.ts‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
recordedLeaseAllocate,
2020
seedConnectionState,
2121
} from './remote-connection.fixtures.ts';
22+
import { connectCommand } from '../cli/commands/connection.ts';
2223
import { materializeRemoteConnectionForCommand } from '../cli/commands/connection-runtime.ts';
2324
import { AppError } from '@agent-device/kernel/errors';
2425
import { readRemoteConnectionState } from '../remote/remote-connection-state.ts';
@@ -409,3 +410,183 @@ test('a connection opened on the apple family collapses to the bound device leaf
409410
);
410411
fs.rmSync(tempRoot, { recursive: true, force: true });
411412
});
413+
414+
// The same rule on the policies that never resolve a device themselves. A `connect --platform apple
415+
// --lease-backend ios-instance` records the alias next to a backend that already rents only iOS
416+
// devices, and this is the one command that turns it into a leaf: without the collapse the next
417+
// `--platform macos` passed the guard, and its request went to the daemon as `apple` against the
418+
// `ios-instance` lease instead of being refused here.
419+
test('a default-policy connection collapses its recorded apple alias when the lease is bound', async () => {
420+
const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace(
421+
'agent-device-connect-default-apple-binding-',
422+
);
423+
fs.writeFileSync(remoteConfigPath, JSON.stringify({ daemonBaseUrl: 'https://daemon.example' }));
424+
seedConnectionState({
425+
stateDir,
426+
state: {
427+
session: 'adc-default',
428+
remoteConfigPath,
429+
daemon: { baseUrl: 'https://daemon.example' },
430+
tenant: 'acme',
431+
runId: 'run-9',
432+
leaseBackend: 'ios-instance',
433+
platform: 'apple',
434+
},
435+
});
436+
const allocate = recordedLeaseAllocate({ leaseId: 'default-lease-1', backend: 'ios-instance' });
437+
const command = (platform: 'apple' | 'ios' | 'macos') =>
438+
materializeRemoteConnectionForCommand({
439+
command: 'snapshot',
440+
flags: {
441+
json: true,
442+
help: false,
443+
version: false,
444+
stateDir,
445+
remoteConfig: remoteConfigPath,
446+
daemonBaseUrl: 'https://daemon.example',
447+
tenant: 'acme',
448+
runId: 'run-9',
449+
session: 'adc-default',
450+
platform,
451+
},
452+
client: createTestClient({ allocate: allocate.stub }),
453+
});
454+
455+
const materialized = await command('apple');
456+
assert.equal(materialized.flags.leaseId, 'default-lease-1');
457+
assert.equal(materialized.flags.platform, 'ios', 'the request names the leaf it leased on');
458+
assert.equal(allocate.request?.platform, 'ios', 'so does the allocate payload');
459+
assert.equal(
460+
readRemoteConnectionState({ stateDir, session: 'adc-default' })?.platform,
461+
'ios',
462+
'and so does the record the next command is guarded against',
463+
);
464+
465+
await assert.rejects(
466+
async () => await command('macos'),
467+
(error: unknown) =>
468+
error instanceof AppError &&
469+
error.code === 'INVALID_ARGS' &&
470+
error.details?.platform === 'ios',
471+
'a second leaf of the same family has to be refused, not retargeted',
472+
);
473+
fs.rmSync(tempRoot, { recursive: true, force: true });
474+
});
475+
476+
// A state file written before the collapse existed records `apple` next to the backend that settled
477+
// it, and a record that already matches its lease is never rewritten — so this connection stays as
478+
// it was saved. The guard has to read the leaf that record owes, or the second leaf of the family
479+
// still walks past it and the command goes out as `apple` on an `ios-instance` lease.
480+
test('a stored apple record refuses the other leaf even though nothing rewrote it', async () => {
481+
const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace(
482+
'agent-device-connect-apple-legacy-record-',
483+
);
484+
fs.writeFileSync(remoteConfigPath, JSON.stringify({ daemonBaseUrl: 'https://daemon.example' }));
485+
seedConnectionState({
486+
stateDir,
487+
state: {
488+
session: 'adc-legacy',
489+
remoteConfigPath,
490+
daemon: { baseUrl: 'https://daemon.example' },
491+
tenant: 'acme',
492+
runId: 'run-9',
493+
leaseId: 'legacy-lease-1',
494+
leaseBackend: 'ios-instance',
495+
deviceKey: 'ios:mobile:SIM-001',
496+
platform: 'apple',
497+
},
498+
});
499+
const heartbeats: string[] = [];
500+
const command = (platform: 'macos') =>
501+
materializeRemoteConnectionForCommand({
502+
command: 'snapshot',
503+
flags: {
504+
json: true,
505+
help: false,
506+
version: false,
507+
stateDir,
508+
remoteConfig: remoteConfigPath,
509+
daemonBaseUrl: 'https://daemon.example',
510+
tenant: 'acme',
511+
runId: 'run-9',
512+
session: 'adc-legacy',
513+
platform,
514+
},
515+
client: createTestClient({
516+
heartbeat: async (request) => {
517+
heartbeats.push(request.leaseId);
518+
return {
519+
leaseId: request.leaseId,
520+
tenantId: 'acme',
521+
runId: 'run-9',
522+
backend: 'ios-instance',
523+
};
524+
},
525+
}),
526+
});
527+
528+
await assert.rejects(
529+
async () => await command('macos'),
530+
(error: unknown) =>
531+
error instanceof AppError &&
532+
error.code === 'INVALID_ARGS' &&
533+
error.details?.platform === 'ios',
534+
);
535+
assert.deepEqual(heartbeats, [], 'the lease was never touched by the refused request');
536+
fs.rmSync(tempRoot, { recursive: true, force: true });
537+
});
538+
539+
// `connect` asks the same question a command does — is this the connection already bound? — and it
540+
// answers it before writing anything. A record saved as `apple` next to the `ios-instance` backend
541+
// that decided it counted as compatible with `--platform macos`, because a family and a leaf never
542+
// conflict, so the new selector was accepted onto the iOS device's connection with no `--force`.
543+
test('connect refuses to reuse an apple-bound connection for the other leaf', async () => {
544+
const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace(
545+
'agent-device-connect-apple-reuse-',
546+
);
547+
fs.writeFileSync(remoteConfigPath, JSON.stringify({ daemonBaseUrl: 'https://daemon.example' }));
548+
seedConnectionState({
549+
stateDir,
550+
state: {
551+
session: 'adc-apple-reuse',
552+
remoteConfigPath,
553+
daemon: { baseUrl: 'https://daemon.example' },
554+
tenant: 'acme',
555+
runId: 'run-9',
556+
leaseId: 'apple-lease-1',
557+
leaseBackend: 'ios-instance',
558+
platform: 'apple',
559+
},
560+
});
561+
const connect = (platform: 'apple' | 'ios' | 'macos') =>
562+
connectCommand({
563+
positionals: [],
564+
flags: {
565+
json: true,
566+
help: false,
567+
version: false,
568+
stateDir,
569+
remoteConfig: remoteConfigPath,
570+
daemonBaseUrl: 'https://daemon.example',
571+
tenant: 'acme',
572+
runId: 'run-9',
573+
session: 'adc-apple-reuse',
574+
platform,
575+
leaseBackend: 'ios-instance',
576+
},
577+
client: createTestClient(),
578+
});
579+
580+
await assert.rejects(
581+
async () => await connect('macos'),
582+
/A different remote connection is already active/,
583+
"the other leaf of the family can't ride along on this lease",
584+
);
585+
await connect('ios');
586+
assert.equal(
587+
readRemoteConnectionState({ stateDir, session: 'adc-apple-reuse' })?.platform,
588+
'ios',
589+
'the leaf the backend rents is what the reconnected record carries',
590+
);
591+
fs.rmSync(tempRoot, { recursive: true, force: true });
592+
});

‎src/cli/commands/connection-runtime.ts‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from '@agent-device/kernel/device';
1616
import { shouldAgentCdpUseRemoteBridgeUrl } from './agent-cdp.ts';
1717
import {
18+
boundConnectionPlatform,
1819
buildConnectionDeviceKey,
1920
buildRemoteConnectionDaemonState,
2021
buildRemoteConnectionRequestMetadata,
@@ -321,6 +322,17 @@ async function materializeLeaseForCommand(options: {
321322
preliminaryLeaseBackend ??
322323
requireRequestedLeaseBackend(nextFlags, command);
323324
assertRequestedConnectionScope(state, nextFlags, leaseBackend);
325+
// Binding a lease is the moment the platform family is decided, so every field this command
326+
// records or sends from here on — the allocate payload, the flags the request carries, the state
327+
// written below — names the leaf the backend rents, never the `apple` alias asked for.
328+
nextState = {
329+
...nextState,
330+
platform: boundConnectionPlatform({
331+
platform: nextState.platform ?? nextFlags.platform,
332+
leaseBackend,
333+
}),
334+
};
335+
nextFlags.platform = nextState.platform ?? nextFlags.platform;
324336
const materializedLease = await allocateOrReuseLease(
325337
client,
326338
nextState,
@@ -874,13 +886,7 @@ async function resolveProxyLeaseState(options: {
874886
...options.state,
875887
deviceKey: buildConnectionDeviceKey(scope),
876888
leaseBackend: options.state.leaseBackend ?? options.leaseBackend ?? scope.leaseBackend,
877-
// A recorded `apple` was a family selection made before any device was bound. Once this
878-
// command binds one, the record must name the leaf its own `deviceKey` speaks; keeping the
879-
// alias would let a later leaf on the same family pass the scope guard against this device.
880-
platform:
881-
options.state.platform === 'apple'
882-
? scope.platform
883-
: (options.state.platform ?? scope.platform),
889+
platform: scope.platform,
884890
target: options.state.target ?? scope.target,
885891
updatedAt: new Date().toISOString(),
886892
},
@@ -940,11 +946,19 @@ function assertRequestedConnectionScope(
940946
{ session: state.session, leaseBackend: state.leaseBackend },
941947
);
942948
}
943-
if (platformSelectorsConflict(flags.platform, state.platform)) {
949+
// A record saved before the collapse existed, or one whose lease already matched so nothing
950+
// rewrote it, still names the `apple` family beside the backend that decided it. The guard reads
951+
// the leaf that record owes; a connection that recorded no platform is bound to none, so a
952+
// selector cannot conflict with it.
953+
const boundPlatform = boundConnectionPlatform({
954+
platform: state.platform,
955+
leaseBackend: state.leaseBackend,
956+
});
957+
if (platformSelectorsConflict(flags.platform, boundPlatform)) {
944958
throw new AppError(
945959
'INVALID_ARGS',
946960
'Active remote connection is already bound to a different platform. Re-run connect --force to replace it.',
947-
{ session: state.session, platform: state.platform },
961+
{ session: state.session, platform: boundPlatform },
948962
);
949963
}
950964
if (state.target && flags.target && state.target !== flags.target) {

‎src/cli/commands/connection.ts‎

Lines changed: 2 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ import {
1111
readRemoteConnectionState,
1212
remoteConnectionLeaseIdentityMatches,
1313
removeRemoteConnectionState,
14+
connectionPlatformMatchesSelection,
1415
writeRemoteConnectionState,
1516
type RemoteConnectionState,
1617
type RemoteConnectionRequestMetadata,
1718
} from '../../remote/remote-connection-state.ts';
1819
import { AppError } from '@agent-device/kernel/errors';
19-
import { platformSelectorsConflict } from '@agent-device/kernel/device';
2020
import {
2121
connectProviderNamesForError,
2222
connectionProviderCapabilities,
@@ -425,31 +425,14 @@ function optionalConnectionFieldsMatch(
425425
state: RemoteConnectionState,
426426
options: Parameters<typeof isCompatibleConnection>[1],
427427
): boolean {
428-
if (!platformSelectionMatches(state.platform, options.flags.platform)) return false;
428+
if (!connectionPlatformMatchesSelection(state, options.flags.platform)) return false;
429429
const fieldsMatch = [
430430
[state.leaseBackend, options.desiredLeaseBackend],
431431
[state.target, options.flags.target],
432432
].every(([left, right]) => right === undefined || left === right);
433433
return fieldsMatch && remoteConnectionLeaseIdentityMatches(state, options.connection);
434434
}
435435

436-
/**
437-
* Whether a `connect --platform` names the platform the active connection is already bound to.
438-
*
439-
* The comparison goes through the selector rule rather than string equality: `--platform apple`
440-
* names the same devices as the `ios` a profile recorded, and treating those as two connections
441-
* forced a needless `--force` (#2962). A connection that recorded no platform stays bound to
442-
* nothing, so a request that names one still counts as a different connection.
443-
*/
444-
function platformSelectionMatches(
445-
bound: RemoteConnectionState['platform'],
446-
requested: CliFlags['platform'],
447-
): boolean {
448-
if (requested === undefined) return true;
449-
if (bound === undefined) return false;
450-
return !platformSelectorsConflict(requested, bound);
451-
}
452-
453436
function isSameDaemonState(
454437
a: RemoteConnectionState['daemon'],
455438
b: RemoteConnectionState['daemon'],

0 commit comments

Comments
 (0)