Repository navigation
Expand file tree
/
Copy pathlimrun-runtime.test.ts
More file actions
849 lines (771 loc) · 27.4 KB
/
Copy pathlimrun-runtime.test.ts
File metadata and controls
849 lines (771 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { afterEach, test, vi } from 'vitest';
import { createInstanceClient as createAndroidInstanceClient } from '@limrun/api/instance-client';
import { createInstanceClient as createIosInstanceClient } from '@limrun/api/ios-client';
import { LimrunRuntime } from '../sdk/limrun.ts';
import { createExpiredProviderLeaseReleaser } from '../daemon/provider-lease-expiry.ts';
import type { SimulatorLease } from '../daemon/lease-registry.ts';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { runCmd } from '@agent-device/host-kit/command';
import { readVersion } from '@agent-device/host-kit/version';
import { mkdtempForTestSync } from './test-utils/tmp-dir.ts';
type LimrunInstancePage = {
getPaginatedItems: () => Array<{ metadata: { id: string } }>;
};
const limrunMockState = vi.hoisted(() => {
const androidTunnelClose = vi.fn();
return {
constructorOptions: [] as Array<{ defaultHeaders?: Record<string, string> }>,
assetsGetOrUpload: vi.fn(async () => ({
signedDownloadUrl: 'https://assets.example/app',
md5: 'asset-md5',
})),
iosInstallApp: vi.fn(async () => ({
bundleId: 'com.example.ios',
url: 'https://assets.example/app',
})),
iosLaunchApp: vi.fn(async () => undefined),
iosOpenUrl: vi.fn(async () => undefined),
iosSetOrientation: vi.fn(async () => undefined),
iosListApps: vi.fn(async () => [
{ bundleId: 'com.apple.Preferences', name: 'Settings', installType: 'System' },
{ bundleId: 'com.example.ios', name: 'Example', installType: 'User' },
]),
androidOpenUrl: vi.fn(async () => undefined),
androidDisconnect: vi.fn(),
androidSendAsset: vi.fn(async () => undefined),
androidTunnelClose,
androidStartAdbTunnel: vi.fn(async () => ({
address: { address: '127.0.0.1', port: 62_001 },
close: androidTunnelClose,
})),
iosCreate: vi.fn(async () => ({
metadata: { id: 'ios-instance-1' },
status: { token: 'instance-token', apiUrl: 'https://ios.example' },
})),
iosList: vi.fn<() => Promise<LimrunInstancePage>>(async () => ({
getPaginatedItems: () => [],
})),
iosDelete: vi.fn(async () => undefined),
androidCreate: vi.fn(async () => ({
metadata: { id: 'android-instance-1' },
status: {
token: 'instance-token',
apiUrl: 'https://android.example',
adbWebSocketUrl: 'wss://adb.example',
},
})),
androidList: vi.fn<() => Promise<LimrunInstancePage>>(async () => ({
getPaginatedItems: () => [],
})),
androidDelete: vi.fn(async () => undefined),
};
});
vi.mock('@limrun/api', () => ({
default: class MockLimrun {
readonly iosInstances = {
create: limrunMockState.iosCreate,
list: limrunMockState.iosList,
delete: limrunMockState.iosDelete,
};
readonly androidInstances = {
create: limrunMockState.androidCreate,
list: limrunMockState.androidList,
delete: limrunMockState.androidDelete,
};
readonly assets = {
getOrUpload: limrunMockState.assetsGetOrUpload,
};
constructor(options: { defaultHeaders?: Record<string, string> }) {
limrunMockState.constructorOptions.push(options);
}
},
}));
vi.mock('@limrun/api/ios-client', () => ({
createInstanceClient: vi.fn(async () => ({
disconnect: vi.fn(),
installApp: limrunMockState.iosInstallApp,
launchApp: limrunMockState.iosLaunchApp,
openUrl: limrunMockState.iosOpenUrl,
setOrientation: limrunMockState.iosSetOrientation,
listApps: limrunMockState.iosListApps,
deviceInfo: {
udid: 'ios-device',
screenWidth: 402,
screenHeight: 874,
model: 'iPhone',
},
})),
}));
vi.mock('@limrun/api/instance-client', () => ({
createInstanceClient: vi.fn(async () => ({
disconnect: limrunMockState.androidDisconnect,
openUrl: limrunMockState.androidOpenUrl,
sendAsset: limrunMockState.androidSendAsset,
startAdbTunnel: limrunMockState.androidStartAdbTunnel,
})),
}));
vi.mock('@agent-device/host-kit/command', async (importOriginal) => {
const actual = await importOriginal<typeof import('@agent-device/host-kit/command')>();
return {
...actual,
runCmd: vi.fn(async () => ({ stdout: '', stderr: '', exitCode: 0 })),
};
});
afterEach(() => {
limrunMockState.constructorOptions.length = 0;
vi.clearAllMocks();
});
test('Limrun runtime identifies direct CLI usage to the Limrun API', async () => {
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
const lease: SimulatorLease = {
leaseId: 'lease-a',
tenantId: 'team-a',
runId: 'run-a',
backend: 'ios-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
try {
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
const allocation = await allocateLease(lease);
const device = allocation?.device as DeviceInfo | undefined;
if (!device) throw new Error('Limrun runtime must expose its allocated device');
const deviceSession = runtime.getDeviceSession(device);
assert.equal(deviceSession?.platform, 'ios');
assert.equal(deviceSession ? 'client' in deviceSession : true, false);
assert.deepEqual(limrunMockState.constructorOptions[0]?.defaultHeaders, {
'x-agent-device-client': 'agent-device-cli',
'x-agent-device-version': readVersion(),
});
const iosCreateCalls = limrunMockState.iosCreate.mock.calls as unknown as Array<
[{ metadata?: { labels?: Record<string, string> } }]
>;
assert.deepEqual(iosCreateCalls[0]?.[0].metadata?.labels, {
tenantId: 'team-a',
runId: 'run-a',
leaseId: 'lease-a',
provider: 'limrun',
source: 'agent-device-cli',
});
} finally {
await runtime.shutdown();
}
});
test('Limrun iOS uses shared deep-link classification', async () => {
const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' });
try {
const device = await allocateLimrunDevice(runtime, {
...androidLease(),
leaseId: 'lease-ios-deep-link',
backend: 'ios-instance',
});
const interactor = runtime.getInteractor(device);
if (!interactor) throw new Error('Limrun runtime must return an interactor');
await interactor.open('http:malformed');
await interactor.open('example://screen');
assert.deepEqual(limrunMockState.iosLaunchApp.mock.calls, [['http:malformed']]);
assert.deepEqual(limrunMockState.iosOpenUrl.mock.calls, [['example://screen']]);
} finally {
await runtime.shutdown();
}
});
test('Limrun reclaims a labeled iOS instance without an in-memory session', async () => {
const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' });
const lease: SimulatorLease = {
leaseId: 'lease-recovered-ios',
tenantId: 'team-a',
runId: 'run-a',
backend: 'ios-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
limrunMockState.iosList.mockResolvedValueOnce({
getPaginatedItems: () => [{ metadata: { id: 'ios-instance-recovered' } }],
});
try {
const releaseLease = runtime.leaseLifecycle.release;
if (!releaseLease) throw new Error('Limrun runtime must provide lease release');
await releaseLease(lease);
assert.deepEqual(limrunMockState.iosList.mock.calls, [
[{ labelSelector: 'provider=limrun,leaseId=lease-recovered-ios' }],
]);
assert.deepEqual(limrunMockState.iosDelete.mock.calls, [['ios-instance-recovered']]);
} finally {
await runtime.shutdown();
}
});
test('Limrun recovers a failed expired lease release after a daemon restart', async () => {
const stateDir = mkdtempForTestSync('agent-device-limrun-expiry-');
const lease: SimulatorLease = {
leaseId: 'lease-recovered-after-restart',
tenantId: 'team-a',
runId: 'run-a',
backend: 'ios-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
const firstRuntime = new LimrunRuntime({ apiKey: 'lim_test_key' });
const firstReleaser = createExpiredProviderLeaseReleaser({
recoverExpiredLease: firstRuntime.recoverExpiredLease,
recoverableProviderIds: ['limrun'],
stateDir,
});
let recoveredRuntime: LimrunRuntime | undefined;
let recoveredReleaser: ReturnType<typeof createExpiredProviderLeaseReleaser> | undefined;
try {
const allocateLease = firstRuntime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
await allocateLease(lease);
limrunMockState.iosDelete.mockRejectedValueOnce(new Error('temporary provider outage'));
await firstReleaser.release(lease);
assert.deepEqual(limrunMockState.iosDelete.mock.calls[0], ['ios-instance-1']);
firstReleaser.shutdown();
recoveredRuntime = new LimrunRuntime({ apiKey: 'lim_test_key' });
recoveredReleaser = createExpiredProviderLeaseReleaser({
recoverExpiredLease: recoveredRuntime.recoverExpiredLease,
recoverableProviderIds: ['limrun'],
stateDir,
});
limrunMockState.iosList.mockResolvedValueOnce({
getPaginatedItems: () => [{ metadata: { id: 'ios-instance-recovered' } }],
});
await recoveredReleaser.retryPending();
assert.deepEqual(limrunMockState.iosList.mock.calls[0], [
{ labelSelector: 'provider=limrun,leaseId=lease-recovered-after-restart' },
]);
assert.deepEqual(limrunMockState.iosDelete.mock.calls.at(-1), ['ios-instance-recovered']);
} finally {
// A crashed daemon cannot run the original runtime's graceful shutdown.
firstReleaser.shutdown();
recoveredReleaser?.shutdown();
await recoveredRuntime?.shutdown();
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
test('Limrun Android reverses localhost URL ports through the persistent ADB tunnel', async () => {
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
try {
vi.mocked(runCmd).mockImplementation(async (_command, args) => ({
stdout:
args[2] === 'reverse' && args[3] === '--list' ? '127.0.0.1:62001 tcp:8081 tcp:8081\n' : '',
stderr: '',
exitCode: 0,
}));
const device = await allocateLimrunDevice(runtime, androidLease());
const interactor = runtime.getInteractor(device);
if (!interactor) throw new Error('Limrun runtime must return an interactor');
await interactor.open('exp://127.0.0.1:8081');
await runtime.shutdown();
assertAndroidTunnelLifecycle('exp://127.0.0.1:8081');
} finally {
await runtime.shutdown();
}
});
function androidLease(): SimulatorLease {
return {
leaseId: 'lease-android',
tenantId: 'team-a',
runId: 'run-a',
backend: 'android-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
}
async function allocateLimrunDevice(
runtime: LimrunRuntime,
lease: SimulatorLease,
): Promise<DeviceInfo> {
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
const allocated = await allocateLease(lease);
const device = allocated?.device;
if (!device || typeof device !== 'object') {
throw new Error('Limrun runtime must return allocated device metadata');
}
return device as DeviceInfo;
}
function assertAndroidTunnelLifecycle(openUrl: string): void {
assert.equal(limrunMockState.androidStartAdbTunnel.mock.calls.length, 1);
assert.equal(limrunMockState.androidOpenUrl.mock.calls.length, 0);
assert.deepEqual(vi.mocked(runCmd).mock.calls[0]?.[1], [
'-s',
'127.0.0.1:62001',
'reverse',
'tcp:8081',
'tcp:8081',
]);
assert.deepEqual(vi.mocked(runCmd).mock.calls[1]?.[1], [
'-s',
'127.0.0.1:62001',
'shell',
'am',
'start',
'-W',
'-a',
'android.intent.action.VIEW',
'-d',
openUrl,
]);
assert.deepEqual(vi.mocked(runCmd).mock.calls[2]?.[1], [
'-s',
'127.0.0.1:62001',
'reverse',
'--list',
]);
assert.deepEqual(vi.mocked(runCmd).mock.calls[3]?.[1], [
'-s',
'127.0.0.1:62001',
'reverse',
'--remove',
'tcp:8081',
]);
assert.deepEqual(vi.mocked(runCmd).mock.calls[4]?.[1], ['disconnect', '127.0.0.1:62001']);
assert.equal(limrunMockState.androidTunnelClose.mock.calls.length, 1);
}
test('Limrun Android installs direct local artifacts through Limrun assets', async () => {
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
const lease: SimulatorLease = {
leaseId: 'lease-android',
tenantId: 'team-a',
runId: 'run-a',
backend: 'android-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
try {
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
const allocated = await allocateLease(lease);
const device = allocated?.device;
if (!device || typeof device !== 'object') {
throw new Error('Limrun runtime must return allocated device metadata');
}
const allocatedDevice = device as Parameters<LimrunRuntime['installApp']>[0];
assert.equal(allocatedDevice.platform, 'android');
assert.equal(allocatedDevice.id, 'limrun:android:lease-android');
const result = await runtime.installApp(
allocatedDevice,
'com.example.android',
'/tmp/app-debug.apk',
);
const assetCalls = limrunMockState.assetsGetOrUpload.mock.calls as unknown as Array<
[Record<string, unknown>]
>;
assert.deepEqual(assetCalls[0]?.[0], {
path: '/tmp/app-debug.apk',
name: 'com.example.android.apk',
});
assert.deepEqual(limrunMockState.androidSendAsset.mock.calls[0], [
'https://assets.example/app',
]);
assert.deepEqual(result, {
packageName: 'com.example.android',
launchTarget: 'com.example.android',
appName: 'Example',
});
} finally {
await runtime.shutdown();
}
});
test('Limrun Android shares an in-flight ADB tunnel across concurrent port reverse requests', async () => {
const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' });
try {
await allocateLimrunDevice(runtime, androidLease());
await Promise.all([
runtime.configurePortReverse({
leaseId: 'lease-android',
devicePort: 8081,
hostPort: 8081,
name: 'metro',
}),
runtime.configurePortReverse({
leaseId: 'lease-android',
devicePort: 8097,
hostPort: 8097,
name: 'react-devtools',
}),
]);
assert.equal(limrunMockState.androidStartAdbTunnel.mock.calls.length, 1);
} finally {
await runtime.shutdown();
}
});
test('Limrun iOS installs direct local artifacts through Limrun assets', async () => {
const tempRoot = mkdtempForTestSync('agent-device-limrun-install-');
const ipaPath = path.join(tempRoot, 'Demo.ipa');
fs.writeFileSync(ipaPath, 'demo');
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
const lease: SimulatorLease = {
leaseId: 'lease-ios',
tenantId: 'team-a',
runId: 'run-a',
backend: 'ios-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
try {
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
const allocated = await allocateLease(lease);
const device = allocated?.device;
if (!device || typeof device !== 'object') {
throw new Error('Limrun runtime must return allocated device metadata');
}
const result = await runtime.installApp(
device as Parameters<LimrunRuntime['installApp']>[0],
'com.example.ios',
ipaPath,
{ relaunch: true },
);
const assetCalls = limrunMockState.assetsGetOrUpload.mock.calls as unknown as Array<
[Record<string, unknown>]
>;
assert.deepEqual(assetCalls[0]?.[0], {
path: ipaPath,
name: 'Demo.ipa',
});
assert.deepEqual(limrunMockState.iosInstallApp.mock.calls[0], [
'https://assets.example/app',
{ md5: 'asset-md5', launchMode: 'RelaunchIfRunning' },
]);
assert.deepEqual(result, {
bundleId: 'com.example.ios',
launchTarget: 'com.example.ios',
appName: 'Demo',
});
} finally {
await runtime.shutdown();
fs.rmSync(tempRoot, { recursive: true, force: true });
}
});
test('Limrun iOS reads the bundle display name before uploading an app bundle', async () => {
const tempRoot = mkdtempForTestSync('agent-device-limrun-app-name-');
const appPath = path.join(tempRoot, 'Renamed.app');
fs.mkdirSync(appPath);
fs.writeFileSync(
path.join(appPath, 'Info.plist'),
[
'<?xml version="1.0" encoding="UTF-8"?>',
'<plist version="1.0"><dict>',
'<key>CFBundleDisplayName</key><string>Actual App Name</string>',
'</dict></plist>',
].join(''),
);
const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' });
try {
const device = await allocateLimrunDevice(runtime, {
...androidLease(),
leaseId: 'lease-ios-app-name',
backend: 'ios-instance',
});
const result = await runtime.installApp(
device as Parameters<LimrunRuntime['installApp']>[0],
'com.example.ios',
appPath,
);
assert.equal(result?.appName, 'Actual App Name');
} finally {
await runtime.shutdown();
fs.rmSync(tempRoot, { recursive: true, force: true });
}
});
test('Limrun iOS maps supported orientation and rejects unsupported upside-down orientation', async () => {
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
try {
const device = await allocateLimrunDevice(runtime, {
...androidLease(),
leaseId: 'lease-ios-orientation',
backend: 'ios-instance',
});
const interactor = runtime.getInteractor(device);
if (!interactor) throw new Error('Limrun runtime must return an interactor');
await interactor.setOrientation('landscape-left');
await assert.rejects(
() => interactor.setOrientation('portrait-upside-down'),
/not portrait upside-down/,
);
assert.deepEqual(limrunMockState.iosSetOrientation.mock.calls, [['Landscape']]);
} finally {
await runtime.shutdown();
}
});
test('Limrun Android configures an explicit port reverse', async () => {
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
const lease: SimulatorLease = {
leaseId: 'lease-android',
tenantId: 'team-a',
runId: 'run-a',
backend: 'android-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
try {
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
await allocateLease(lease);
assert.deepEqual(
await runtime.configurePortReverse({
leaseId: lease.leaseId,
devicePort: 8097,
hostPort: 8097,
name: 'react-devtools',
}),
{
leaseId: lease.leaseId,
devicePort: 8097,
hostPort: 8097,
name: 'react-devtools',
},
);
assert.deepEqual(vi.mocked(runCmd).mock.calls[0]?.[1], [
'-s',
'127.0.0.1:62001',
'reverse',
'tcp:8097',
'tcp:8097',
]);
} finally {
await runtime.shutdown();
}
});
test('Limrun Android preserves canonical ADB failure classification', async () => {
const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' });
try {
await allocateLimrunDevice(runtime, androidLease());
vi.mocked(runCmd).mockResolvedValueOnce({
stdout: '',
stderr: 'error: device offline',
exitCode: 1,
});
await assert.rejects(
() =>
runtime.configurePortReverse({
leaseId: 'lease-android',
devicePort: 8097,
hostPort: 8097,
name: 'react-devtools',
}),
(error) =>
typeof error === 'object' &&
error !== null &&
(error as { details?: { adbFailure?: unknown; retriable?: unknown } }).details
?.adbFailure === 'device_offline' &&
(error as { details?: { retriable?: unknown } }).details?.retriable === true,
);
} finally {
await runtime.shutdown();
}
});
test('Limrun deletes iOS instance when post-create validation fails', async () => {
limrunMockState.iosCreate.mockResolvedValueOnce({
metadata: { id: 'ios-instance-missing-api' },
status: { token: 'instance-token' },
} as never);
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
const lease: SimulatorLease = {
leaseId: 'lease-ios',
tenantId: 'team-a',
runId: 'run-a',
backend: 'ios-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
try {
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
await assert.rejects(() => allocateLease(lease), /did not expose apiUrl/);
assert.deepEqual(limrunMockState.iosDelete.mock.calls[0], ['ios-instance-missing-api']);
} finally {
await runtime.shutdown();
}
});
test('Limrun deletes Android instance when post-create validation fails', async () => {
limrunMockState.androidCreate.mockResolvedValueOnce({
metadata: { id: 'android-instance-missing-adb' },
status: {
token: 'instance-token',
apiUrl: 'https://android.example',
},
} as never);
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
const lease: SimulatorLease = {
leaseId: 'lease-android',
tenantId: 'team-a',
runId: 'run-a',
backend: 'android-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
try {
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation');
await assert.rejects(() => allocateLease(lease), /did not expose API and ADB/);
assert.deepEqual(limrunMockState.androidDelete.mock.calls[0], ['android-instance-missing-adb']);
} finally {
await runtime.shutdown();
}
});
test('Limrun keeps session tracked when release fails so release can be retried', async () => {
const runtime = new LimrunRuntime({
apiKey: 'lim_test_key',
});
const lease: SimulatorLease = {
leaseId: 'lease-android',
tenantId: 'team-a',
runId: 'run-a',
backend: 'android-instance',
leaseProvider: 'limrun',
createdAt: 1,
heartbeatAt: 1,
expiresAt: 60_001,
};
try {
const allocateLease = runtime.leaseLifecycle.allocate;
const releaseLease = runtime.leaseLifecycle.release;
if (!allocateLease || !releaseLease) {
throw new Error('Limrun runtime must provide lease lifecycle hooks');
}
await allocateLease(lease);
limrunMockState.androidDelete.mockRejectedValueOnce(new Error('temporary delete failure'));
await assert.rejects(() => releaseLease(lease), /temporary delete failure/);
assert.deepEqual(await releaseLease(lease), { limrunInstanceId: 'android-instance-1' });
} finally {
await runtime.shutdown();
}
});
const ATTACHED_IOS = {
apiUrl: 'https://region.limrun.example/v1/ios_attached/api',
token: 'ios-instance-token',
};
const ATTACHED_ANDROID = {
apiUrl: 'https://region.limrun.example/v1/android_attached/api',
token: 'android-instance-token',
adbUrl: 'wss://region.limrun.example/v1/android_attached/adb',
};
function iosLease(leaseId: string): SimulatorLease {
return { ...androidLease(), leaseId, backend: 'ios-instance' };
}
test('Limrun drives existing instances without an API key and never deletes them', async () => {
const runtime = new LimrunRuntime({
instances: { ios: ATTACHED_IOS, android: ATTACHED_ANDROID },
});
const releaseLease = runtime.leaseLifecycle.release;
const allocateLease = runtime.leaseLifecycle.allocate;
if (!allocateLease || !releaseLease) throw new Error('Limrun runtime must provide lease hooks');
try {
const ios = await allocateLease(iosLease('lease-attached-ios'), { initialApp: 'Example.ipa' });
await allocateLease({ ...androidLease(), leaseId: 'lease-attached-android' });
assert.match(String(ios?.limrunInstanceId), /^attached-[a-f0-9]{12}$/);
assert.deepEqual(vi.mocked(createIosInstanceClient).mock.calls, [
[{ ...ATTACHED_IOS, logLevel: 'warn' }],
]);
assert.deepEqual(vi.mocked(createAndroidInstanceClient).mock.calls, [
[{ ...ATTACHED_ANDROID, logLevel: 'warn' }],
]);
await releaseLease(iosLease('lease-attached-ios'));
await releaseLease({ ...androidLease(), leaseId: 'lease-attached-android' });
assert.equal(await releaseLease(iosLease('lease-before-daemon-restart')), undefined);
assert.equal(limrunMockState.androidDisconnect.mock.calls.length, 1);
} finally {
await runtime.shutdown();
}
assert.equal(limrunMockState.constructorOptions.length, 0);
for (const controlPlaneCall of [
limrunMockState.iosCreate,
limrunMockState.iosList,
limrunMockState.iosDelete,
limrunMockState.androidCreate,
limrunMockState.androidList,
limrunMockState.androidDelete,
]) {
assert.equal(controlPlaneCall.mock.calls.length, 0);
}
});
test('Limrun removes only its own port reverse mappings from an attached Android instance', async () => {
const runtime = new LimrunRuntime({ instances: { android: ATTACHED_ANDROID } });
const lease = { ...androidLease(), leaseId: 'lease-attached-android' };
vi.mocked(runCmd).mockImplementation(async (_command, args) => ({
stdout: args.includes('--list') ? 'host-7 tcp:8081 tcp:8081\nhost-9 tcp:8097 tcp:8097\n' : '',
stderr: '',
exitCode: 0,
}));
await allocateLimrunDevice(runtime, lease);
await runtime.configurePortReverse({
leaseId: lease.leaseId,
devicePort: 8097,
hostPort: 8097,
name: 'react-devtools',
});
await runtime.shutdown();
const removals = vi
.mocked(runCmd)
.mock.calls.map(([, args]) => args)
.filter((args) => args.includes('--remove'));
assert.deepEqual(removals, [['-s', '127.0.0.1:62001', 'reverse', '--remove', 'tcp:8097']]);
});
test('Limrun instance access wins over the API key for its platform only', async () => {
const runtime = new LimrunRuntime({ apiKey: 'lim_test_key', instances: { ios: ATTACHED_IOS } });
await allocateLimrunDevice(runtime, iosLease('lease-attached-ios'));
await allocateLimrunDevice(runtime, androidLease());
await runtime.shutdown();
assert.equal(limrunMockState.iosCreate.mock.calls.length, 0);
assert.equal(limrunMockState.iosDelete.mock.calls.length, 0);
assert.equal(limrunMockState.androidCreate.mock.calls.length, 1);
assert.deepEqual(limrunMockState.androidDelete.mock.calls, [['android-instance-1']]);
});
test('Limrun without an API key refuses operations that need one', async () => {
const runtime = new LimrunRuntime({ instances: { ios: ATTACHED_IOS } });
try {
const device = await allocateLimrunDevice(runtime, iosLease('lease-attached-ios'));
await assert.rejects(runtime.installInstallablePath(device, '/tmp/Example.app'), {
code: 'UNSUPPORTED_OPERATION',
message: 'Uploading an app requires a Limrun API key.',
});
await assert.rejects(allocateLimrunDevice(runtime, androidLease()), {
code: 'UNSUPPORTED_OPERATION',
message: 'Creating an instance requires a Limrun API key.',
});
assert.equal(limrunMockState.assetsGetOrUpload.mock.calls.length, 0);
} finally {
await runtime.shutdown();
}
assert.throws(() => new LimrunRuntime({}), /requires an apiKey or instance access/);
});