Skip to content

Commit 924e202

Browse files
committed
refactor(limrun): simplify instance attach wiring
Build attached sessions in the runtime from the existing session constructors instead of two near-identical allocation helpers, fold the attached URLs into the runtime fingerprint directly, merge the attached verification connector, and derive the connect error from the one list of instance variables.
1 parent d0234a0 commit 924e202

9 files changed

Lines changed: 118 additions & 159 deletions

‎packages/provider-limrun/src/connection-verification.test.ts‎

Lines changed: 25 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -104,39 +104,33 @@ test('Limrun verification connects to an attached instance instead of the contro
104104
assert.equal(mockState.androidList.mock.calls.length, 0);
105105
});
106106

107-
test('Limrun verification reports a rejected instance token with the variables to check', async () => {
108-
instanceClients.createIos.mockRejectedValueOnce(new Error('Unexpected server response: 401'));
109-
110-
await assert.rejects(
111-
verifyLimrunConnection({
112-
instances: { ios: { apiUrl: 'https://attached.example/api', token: 'lim_st_secret' } },
113-
clientVersion: '1.2.3',
107+
test('Limrun verification names the variables to check when an instance rejects access', async () => {
108+
const cases = [
109+
{
114110
platform: 'ios',
115-
}),
116-
(error: unknown) => {
117-
assert.equal((error as { code?: string }).code, 'COMMAND_FAILED');
118-
assert.match(JSON.stringify(error), /LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN,/);
119-
assert.doesNotMatch(JSON.stringify(error), /lim_st_secret/);
120-
return true;
111+
instances: { ios: { apiUrl: 'https://attached/api', token: 'lim_st_secret' } },
112+
create: instanceClients.createIos,
113+
variables: /LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN,/,
121114
},
122-
);
123-
});
124-
125-
test('Limrun Android verification failure names the ADB URL variable too', async () => {
126-
instanceClients.createAndroid.mockRejectedValueOnce(new Error('adb endpoint refused'));
127-
128-
await assert.rejects(
129-
verifyLimrunConnection({
130-
instances: { android: { apiUrl: 'https://attached/api', token: 't', adbUrl: 'wss://adb' } },
131-
clientVersion: '1.2.3',
115+
{
132116
platform: 'android',
133-
}),
134-
(error: unknown) => {
135-
assert.match(
136-
JSON.stringify(error),
137-
/LIM_ANDROID_INSTANCE_TOKEN, and LIM_ANDROID_INSTANCE_ADB_URL/,
138-
);
139-
return true;
117+
instances: {
118+
android: { apiUrl: 'https://attached/api', token: 'lim_st_secret', adbUrl: 'wss://adb' },
119+
},
120+
create: instanceClients.createAndroid,
121+
variables: /LIM_ANDROID_INSTANCE_TOKEN, and LIM_ANDROID_INSTANCE_ADB_URL/,
140122
},
141-
);
123+
] as const;
124+
for (const { platform, instances, create, variables } of cases) {
125+
create.mockRejectedValueOnce(new Error('Unexpected server response: 401'));
126+
await assert.rejects(
127+
verifyLimrunConnection({ instances, clientVersion: '1.2.3', platform }),
128+
(error: unknown) => {
129+
assert.equal((error as { code?: string }).code, 'COMMAND_FAILED');
130+
assert.match(JSON.stringify(error), variables);
131+
assert.doesNotMatch(JSON.stringify(error), /lim_st_secret/);
132+
return true;
133+
},
134+
);
135+
}
142136
});

‎packages/provider-limrun/src/connection-verification.ts‎

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ export type LimrunConnectionVerificationOptions = {
3030
export async function verifyLimrunConnection(
3131
options: LimrunConnectionVerificationOptions,
3232
): Promise<LimrunConnectionVerification> {
33-
const connectAttached = attachedInstanceConnector(options);
34-
if (connectAttached) return await verifyAttachedInstance(options.platform, connectAttached);
33+
const attached = await verifyAttachedInstance(options);
34+
if (attached) return attached;
3535
if (!options.apiKey) {
3636
throw new AppError(
3737
'INVALID_ARGS',
@@ -89,47 +89,44 @@ function readStatus(error: unknown): number | undefined {
8989
return typeof status === 'number' ? status : undefined;
9090
}
9191

92-
type InstanceConnector = () => Promise<{ disconnect(): void }>;
93-
94-
function attachedInstanceConnector(
92+
function connectAttachedInstance(
9593
options: LimrunConnectionVerificationOptions,
96-
): InstanceConnector | undefined {
94+
): Promise<{ disconnect(): void }> | undefined {
9795
const clientOptions = { logLevel: 'none', maxReconnectAttempts: 0 } as const;
98-
const ios = options.instances?.ios;
99-
if (options.platform === 'ios' && ios) {
100-
return async () =>
101-
await (
102-
await import('@limrun/api/ios-client')
103-
).createInstanceClient({ ...clientOptions, ...ios });
104-
}
105-
const android = options.instances?.android;
106-
if (options.platform === 'android' && android) {
107-
return async () =>
108-
await (
109-
await import('@limrun/api/instance-client')
110-
).createInstanceClient({ ...clientOptions, ...android });
96+
const { ios, android } = options.instances ?? {};
97+
if (options.platform === 'android') {
98+
return (
99+
android &&
100+
import('@limrun/api/instance-client').then(({ createInstanceClient }) =>
101+
createInstanceClient({ ...clientOptions, ...android }),
102+
)
103+
);
111104
}
112-
return undefined;
105+
return (
106+
ios &&
107+
import('@limrun/api/ios-client').then(({ createInstanceClient }) =>
108+
createInstanceClient({ ...clientOptions, ...ios }),
109+
)
110+
);
113111
}
114112

115113
async function verifyAttachedInstance(
116-
platform: 'android' | 'ios',
117-
connect: InstanceConnector,
118-
): Promise<LimrunConnectionVerification> {
119-
const platformName = platform === 'android' ? 'Android' : 'iOS';
120-
const instanceVars =
121-
platform === 'android'
122-
? 'LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN, and LIM_ANDROID_INSTANCE_ADB_URL'
123-
: 'LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN';
114+
options: LimrunConnectionVerificationOptions,
115+
): Promise<LimrunConnectionVerification | undefined> {
116+
const connecting = connectAttachedInstance(options);
117+
if (!connecting) return undefined;
118+
const android = options.platform === 'android';
119+
const platformName = android ? 'Android' : 'iOS';
124120
try {
125-
const client = await connect();
126-
client.disconnect();
121+
(await connecting).disconnect();
127122
} catch (error) {
128123
throw new AppError(
129124
'COMMAND_FAILED',
130125
`Limrun ${platformName} instance access failed.`,
131126
{
132-
hint: `Check ${instanceVars}, and that the instance is still running.`,
127+
hint: android
128+
? 'Check LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN, and LIM_ANDROID_INSTANCE_ADB_URL, and that the instance is still running.'
129+
: 'Check LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN, and that the instance is still running.',
133130
},
134131
error,
135132
);
@@ -140,8 +137,8 @@ async function verifyAttachedInstance(
140137
verificationMessage: `Existing ${platformName} instance access verified. agent-device will not create or delete it.`,
141138
device: {
142139
status: 'verified',
143-
name: `Existing ${platformName} ${platform === 'android' ? 'emulator' : 'simulator'}`,
144-
platform,
140+
name: `Existing ${platformName} ${android ? 'emulator' : 'simulator'}`,
141+
platform: options.platform,
145142
},
146143
app: {
147144
status: 'missing',
Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,10 @@
11
import { expect, test } from 'vitest';
22
import { attachedLimrunInstanceId, isAttachedLimrunInstanceId } from './instance-access.ts';
33

4-
test('names an attached instance stably by its API URL', () => {
4+
test('names an attached instance stably by its API URL, apart from control-plane ids', () => {
55
const apiUrl = 'https://region.limrun.example/v1/ios_attached/api';
66
expect(attachedLimrunInstanceId(apiUrl)).toBe(attachedLimrunInstanceId(apiUrl));
7-
expect(attachedLimrunInstanceId(apiUrl)).toMatch(/^attached-[a-f0-9]{12}$/);
87
expect(attachedLimrunInstanceId(`${apiUrl}/other`)).not.toBe(attachedLimrunInstanceId(apiUrl));
9-
});
10-
11-
test('tells attached instance ids from ids the control plane assigned', () => {
12-
expect(isAttachedLimrunInstanceId(attachedLimrunInstanceId('https://x/api'))).toBe(true);
8+
expect(isAttachedLimrunInstanceId(attachedLimrunInstanceId(apiUrl))).toBe(true);
139
expect(isAttachedLimrunInstanceId('ios_euna_01m414fmjtfzb82wshkbcaa09c')).toBe(false);
1410
});

‎packages/provider-limrun/src/runtime-instance.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ export function resolveLimrunRuntimeInstance(options: {
2121
provider: 'limrun',
2222
region: options.region?.trim().toLowerCase() || 'default',
2323
apiKey: options.apiKey,
24-
attached: attachedInstanceUrls(options.instances),
24+
attachedIos: options.instances?.ios?.apiUrl,
25+
attachedAndroid: options.instances?.android?.apiUrl,
2526
});
2627
const fingerprint = scryptSync(principal, RUNTIME_INSTANCE_SALT, RUNTIME_INSTANCE_KEY_LENGTH, {
2728
N: RUNTIME_INSTANCE_SCRYPT_COST,
@@ -31,10 +32,3 @@ export function resolveLimrunRuntimeInstance(options: {
3132
});
3233
return `principal-${fingerprint.toString('hex')}`;
3334
}
34-
35-
function attachedInstanceUrls(
36-
instances: LimrunInstanceAccess | undefined,
37-
): Readonly<{ ios?: string; android?: string }> | undefined {
38-
if (!instances?.ios && !instances?.android) return undefined;
39-
return { ios: instances.ios?.apiUrl, android: instances.android?.apiUrl };
40-
}

‎packages/provider-limrun/src/runtime.ts‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,23 @@ import {
1818
cleanupLimrunAndroidAdbTunnel,
1919
configureLimrunAndroidPortReverse,
2020
createLimrunAndroidInteractor,
21+
createLimrunAndroidSession,
2122
installLimrunAndroidApp,
2223
type LimrunAndroidSession,
2324
} from './android.ts';
2425
import {
26+
buildLimrunDevice,
2527
LIMRUN_PROVIDER,
2628
parseLimrunDeviceId,
2729
platformForLimrunLeaseBackend,
2830
type LimrunPlatform,
2931
} from './device.ts';
30-
import { createLimrunIosInteractor, installLimrunIosApp, type LimrunIosSession } from './ios.ts';
32+
import {
33+
createLimrunIosInteractor,
34+
createLimrunIosSession,
35+
installLimrunIosApp,
36+
type LimrunIosSession,
37+
} from './ios.ts';
3138
import { createLimrunDeviceSession, type LimrunDeviceSession } from './device-session.ts';
3239
import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts';
3340
import type {
@@ -42,7 +49,11 @@ import { buildLimrunClientOptions, LIMRUN_CLIENT_HEADER } from './client-options
4249
import { resolveLimrunRuntimeInstance } from './runtime-instance.ts';
4350
import type { LimrunRequestOperationDrain } from './request-cancellation.ts';
4451
import type { LimrunAppAsset } from './app-catalog.ts';
45-
import { isAttachedLimrunInstanceId, type LimrunInstanceAccess } from './instance-access.ts';
52+
import {
53+
attachedLimrunInstanceId,
54+
isAttachedLimrunInstanceId,
55+
type LimrunInstanceAccess,
56+
} from './instance-access.ts';
4657

4758
type LimrunRuntimeSession = LimrunIosSession | LimrunAndroidSession;
4859

@@ -255,12 +266,22 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime {
255266
lease: DeviceLease,
256267
): Promise<LimrunRuntimeSession | undefined> {
257268
const { ios, android } = this.options.instances ?? {};
258-
const { attachLimrunAndroidSession, attachLimrunIosSession } =
259-
await import('./session-allocation.ts');
260-
if (platform === 'ios') {
261-
return ios && (await attachLimrunIosSession(lease, ios, this.dependencies));
269+
const target = (apiUrl: string) => {
270+
const instanceId = attachedLimrunInstanceId(apiUrl);
271+
return { lease, instanceId, device: buildLimrunDevice(platform, lease, instanceId) };
272+
};
273+
if (platform === 'android') {
274+
return (
275+
android &&
276+
(await createLimrunAndroidSession(
277+
{ ...target(android.apiUrl), ...android },
278+
this.dependencies,
279+
))
280+
);
262281
}
263-
return android && (await attachLimrunAndroidSession(lease, android, this.dependencies));
282+
return (
283+
ios && (await createLimrunIosSession({ ...target(ios.apiUrl), ...ios }, this.dependencies))
284+
);
264285
}
265286

266287
private async createSession(

‎packages/provider-limrun/src/session-allocation.ts‎

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,6 @@ import {
1111
type LimrunAppAsset,
1212
} from './app-catalog.ts';
1313
import { createLimrunDeviceSession } from './device-session.ts';
14-
import {
15-
attachedLimrunInstanceId,
16-
type LimrunAndroidInstanceAccess,
17-
type LimrunIosInstanceAccess,
18-
} from './instance-access.ts';
1914
import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts';
2015

2116
type LimrunInstance = {
@@ -107,43 +102,6 @@ export async function allocateLimrunIosSession(
107102
}
108103
}
109104

110-
export async function attachLimrunIosSession(
111-
lease: DeviceLease,
112-
access: LimrunIosInstanceAccess,
113-
dependencies: LimrunRuntimeDependencies,
114-
): Promise<LimrunIosSession> {
115-
const instanceId = attachedLimrunInstanceId(access.apiUrl);
116-
return await createLimrunIosSession(
117-
{
118-
lease,
119-
instanceId,
120-
device: buildLimrunDevice('ios', lease, instanceId),
121-
apiUrl: access.apiUrl,
122-
token: access.token,
123-
},
124-
dependencies,
125-
);
126-
}
127-
128-
export async function attachLimrunAndroidSession(
129-
lease: DeviceLease,
130-
access: LimrunAndroidInstanceAccess,
131-
dependencies: LimrunRuntimeDependencies,
132-
): Promise<LimrunAndroidSession> {
133-
const instanceId = attachedLimrunInstanceId(access.apiUrl);
134-
return await createLimrunAndroidSession(
135-
{
136-
lease,
137-
instanceId,
138-
device: buildLimrunDevice('android', lease, instanceId),
139-
apiUrl: access.apiUrl,
140-
token: access.token,
141-
adbUrl: access.adbUrl,
142-
},
143-
dependencies,
144-
);
145-
}
146-
147105
export async function allocateLimrunAndroidSession(
148106
params: SessionAllocationParams,
149107
): Promise<LimrunAndroidSession> {

‎src/__tests__/cloud-connect-profile.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ test('connect limrun attaches to an existing instance without storing its token'
219219
const state = readRequiredActiveState(stateDir);
220220
assert.equal(state.leaseBackend, 'ios-instance');
221221
assert.doesNotMatch(fs.readFileSync(state.remoteConfigPath, 'utf8'), /ios-instance-token/);
222-
assert.deepEqual(mockedVerifyLimrunConnection.mock.calls[0]?.[0].instances, { ios });
222+
assert.deepEqual(mockedVerifyLimrunConnection.mock.calls[0]?.[0].instances?.ios, ios);
223223
} finally {
224224
fs.rmSync(tempRoot, { recursive: true, force: true });
225225
}
@@ -301,7 +301,7 @@ test('connect limrun requires LIMRUN_API_KEY or access to an existing instance',
301301
},
302302
client: {} as AgentDeviceClient,
303303
}),
304-
/connect limrun requires LIMRUN_API_KEY, or LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN and LIM_ANDROID_INSTANCE_ADB_URL/,
304+
/connect limrun requires LIMRUN_API_KEY, or LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN, LIM_ANDROID_INSTANCE_ADB_URL/,
305305
);
306306
} finally {
307307
fs.rmSync(tempRoot, { recursive: true, force: true });

‎src/cli/connection/limrun-profile.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import { type EnvMap } from '@agent-device/kernel/source-value';
66
import { readMetroProfileFields } from './profile-fields.ts';
77
import { persistAndResolveGeneratedProfile } from './generated-config.ts';
88
import { resolveRequestedLeaseBackend } from '../commands/connection-runtime.ts';
9-
import { readLimrunCredentials } from '../../provider-limrun-credentials.ts';
9+
import {
10+
limrunInstanceVariables,
11+
readLimrunCredentials,
12+
} from '../../provider-limrun-credentials.ts';
1013

1114
const DEFAULT_LIMRUN_TENANT = 'limrun';
1215
export function resolveLimrunConnectProfile(options: {
@@ -20,13 +23,9 @@ export function resolveLimrunConnectProfile(options: {
2023
const credentials = readLimrunCredentials(env);
2124
const platform = profile.leaseBackend === 'ios-instance' ? 'ios' : 'android';
2225
if (!credentials?.apiKey && !credentials?.instances?.[platform]) {
23-
const instanceVars =
24-
platform === 'ios'
25-
? 'LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN'
26-
: 'LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN and LIM_ANDROID_INSTANCE_ADB_URL';
2726
throw new AppError(
2827
'INVALID_ARGS',
29-
`connect limrun requires LIMRUN_API_KEY, or ${instanceVars} for an existing instance.`,
28+
`connect limrun requires LIMRUN_API_KEY, or ${limrunInstanceVariables(platform).join(', ')} for an existing instance.`,
3029
{
3130
hint: 'Set the credentials in the environment before running agent-device connect limrun.',
3231
},

0 commit comments

Comments
 (0)