Repository navigation
Expand file tree
/
Copy pathagent-device-client.ts
More file actions
672 lines (648 loc) · 26.9 KB
/
Copy pathagent-device-client.ts
File metadata and controls
672 lines (648 loc) · 26.9 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
import type { CommandFlags, InternalRequestOptions } from '@agent-device/contracts/command';
import {
readSerializedSnapshotCaptureAnnotations,
readSnapshotDiagnosticsSummary,
} from '@agent-device/contracts/capture';
import type {
AgentDeviceClientConfig,
AgentDeviceDaemonTransport,
AppCloseOptions,
AppDeployOptions,
AppInstallFromSourceOptions,
AppInstallOptions,
AppListOptions,
AppOpenOptions,
CaptureScreenshotOptions,
CaptureScreenshotResult,
CaptureSnapshotOptions,
CaptureSnapshotResult,
DragOptions,
FlingOptions,
MaterializationReleaseOptions,
PanOptions,
PinchOptions,
RotateGestureOptions,
SessionSaveScriptOptions,
SessionSaveScriptResult,
SwipeGestureOptions,
TransformGestureOptions,
} from '@agent-device/contracts/client';
import type { AgentArtifactsResult } from '@agent-device/contracts/observability';
import type { MetroPrepareOptions } from '@agent-device/contracts/remote';
import {
isNonDefaultResponseLevel,
type ResponseLevel,
type SessionRuntimeHints,
} from '@agent-device/kernel/contracts';
import { AppError, throwDaemonError } from '@agent-device/kernel/errors';
import { createRequestId } from '@agent-device/host-kit/diagnostics';
import {
buildMeta,
normalizeDeployResult,
normalizeDevice,
normalizeDeviceSelection,
normalizeOpenForegroundComposition,
normalizeInstallFromSourceResult,
normalizeMaterializationReleaseResult,
normalizeOpenDevice,
normalizeRuntimeHints,
normalizeSession,
normalizeStartupSample,
normalizeTargetShutdownResult,
readOptionalString,
readRequiredString,
readSnapshotNodes,
resolveSessionName,
} from './client/client-normalizers.ts';
import type { AgentDeviceClient, MetroPrepareResult } from './client/client-types.ts';
import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog';
import { buildRequestFlags } from './commands/command-flags.ts';
import {
prepareDaemonCommandRequest,
type DaemonCommandName,
} from './commands/command-projection.ts';
import type { CommandResult } from '@agent-device/command-registry/command-result';
import { sendToDaemon } from './daemon-client/daemon-client.ts';
import { resolveDaemonPaths } from './daemon-resolution.ts';
import { resolveMetroServerUrl } from './metro/metro-reload-endpoints.ts';
import { prepareMetroRuntime, reloadMetro } from './metro/client-metro.ts';
import {
clearMetroSessionHints,
readMetroSessionHints,
writeMetroSessionHints,
type MetroSessionHints,
} from './metro/metro-session-hints.ts';
import { asOptionalRecord, readSnapshotKeyboardBandFact } from '@agent-device/kernel/record';
import { readSnapshotViewportSize } from '@agent-device/kernel/rect';
import { readResponseWarnings } from '@agent-device/kernel/success-text';
import { createLeaseClient } from './client/lease-client.ts';
import { normalizeScreenshotCaptureResult } from './client/screenshot-result.ts';
import { createRequestGuard } from './daemon-client/daemon-client-transport.ts';
export function createAgentDeviceClient(
config: AgentDeviceClientConfig = {},
deps: { transport?: AgentDeviceDaemonTransport } = {},
): AgentDeviceClient {
const transport = deps.transport ?? sendToDaemon;
// A non-default responseLevel (digest/full) makes the daemon return a leveled
// shape; the per-command client normalizers assume the default shape, so the
// capture methods pass the leveled payload through unnormalized instead.
const isLeveledResponse = (options: { responseLevel?: ResponseLevel }): boolean =>
isNonDefaultResponseLevel(options.responseLevel ?? config.responseLevel);
const execute = async (
command: string,
positionals: string[] = [],
options: InternalRequestOptions = {},
metadataFlags?: Partial<CommandFlags>,
input?: Record<string, unknown>,
): Promise<Record<string, unknown>> => {
const merged = mergeClientOptions(config, options);
// The id is generated before the guard so a canceled call names itself in `request.meta`, and
// the daemon's diagnostics for the request the transport goes on to cancel carry the same id
// the caller's rejection carries.
const requestId = merged.requestId ?? createRequestId();
const cancellation = createRequestGuard({ signal: merged.signal, requestId });
cancellation.refuseIfAborted();
const request = {
session: resolveSessionName(merged.session),
command,
positionals,
...(input ? { input } : {}),
flags: buildRequestFlags(merged, metadataFlags),
runtime: merged.runtime,
meta: { ...buildMeta(merged), requestId },
};
// `signal` rides the transport context (it is a live object, never wire data), and the guard
// answers for a custom transport that ignores it: the caller's promise settles on abort either
// way. The built-in transport closes the request's connection, which is what makes the daemon
// mark the request canceled.
const response = await cancellation.guard(
async () =>
await transport(request, { authToken: merged.daemonAuthToken, signal: merged.signal }),
);
if (!response.ok) {
throwDaemonError(response.error);
}
return (response.data ?? {}) as Record<string, unknown>;
};
const listSessions = async (options = {}) => {
const data = await execute(INTERNAL_COMMANDS.sessionList, [], options);
const sessions = Array.isArray(data.sessions) ? data.sessions : [];
return sessions.map(normalizeSession);
};
const executeCommand = async <T>(
command: DaemonCommandName,
options: InternalRequestOptions = {},
): Promise<T> => {
const request = await prepareDaemonCommandRequest(command, options);
return (await execute(
request.command,
request.positionals,
request.options,
request.metadataFlags,
request.input,
)) as T;
};
const resolveRequestSession = (options: InternalRequestOptions = {}) =>
resolveSessionName(mergeClientOptions(config, options).session);
return {
command: {
wait: async (options) => await executeCommand<CommandResult<'wait'>>('wait', options),
alert: async (options = {}) => await executeCommand('alert', options),
appState: async (options = {}) =>
await executeCommand<CommandResult<'appstate'>>('appstate', options),
back: async (options = {}) => await executeCommand<CommandResult<'back'>>('back', options),
home: async (options = {}) => await executeCommand<CommandResult<'home'>>('home', options),
orientation: async (options) =>
await executeCommand<CommandResult<'orientation'>>('orientation', options),
fold: async (options) => await executeCommand<CommandResult<'fold'>>('fold', options),
appSwitcher: async (options = {}) =>
await executeCommand<CommandResult<'app-switcher'>>('app-switcher', options),
actionButton: async (options = {}) =>
await executeCommand<CommandResult<'action-button'>>('action-button', options),
keyboard: async (options = {}) =>
await executeCommand<CommandResult<'keyboard'>>('keyboard', options),
clipboard: async (options) =>
await executeCommand<CommandResult<'clipboard'>>('clipboard', options),
tvRemote: async (options) =>
await executeCommand<CommandResult<'tv-remote'>>('tv-remote', options),
reactNative: async (options) => await executeCommand('react-native', options),
doctor: async (options = {}) =>
await executeCommand<CommandResult<'doctor'>>('doctor', options),
prepare: async (options) =>
await executeCommand<CommandResult<'prepare'>>('prepare', options),
viewport: async (options) =>
await executeCommand<CommandResult<'viewport'>>('viewport', options),
},
devices: {
list: async (options = {}) => {
const data = await executeCommand<Record<string, unknown>>('devices', options);
const devices = Array.isArray(data.devices) ? data.devices : [];
return devices.map(normalizeDevice);
},
capabilities: async (options = {}) => {
const data = await executeCommand<Record<string, unknown>>('capabilities', options);
const availableCommands = Array.isArray(data.availableCommands)
? data.availableCommands.filter(
(command): command is string => typeof command === 'string',
)
: [];
return {
device: normalizeDevice(data.device),
availableCommands,
};
},
boot: async (options = {}) => await executeCommand<CommandResult<'boot'>>('boot', options),
shutdown: async (options = {}) =>
await executeCommand<CommandResult<'shutdown'>>('shutdown', options),
},
sessions: {
list: async (options = {}) => await listSessions(options),
// Pure local resolution; mirrors how the daemon client picks its state dir.
stateDir: async (options = {}) => {
const merged = mergeClientOptions(config, options);
return resolveDaemonPaths(merged.stateDir ?? process.env.AGENT_DEVICE_STATE_DIR).baseDir;
},
close: async (options = {}) => {
const session = resolveRequestSession(options);
try {
const data = await executeCommand<Record<string, unknown>>('close', options);
return {
session,
shutdown: normalizeTargetShutdownResult(data.shutdown),
provider: asOptionalRecord(data.provider),
savedScript: readOptionalString(data, 'savedScript'),
identifiers: { session },
};
} finally {
// Close is teardown intent: drop the dev-server binding even if the daemon call fails.
clearMetroSessionHintsQuietly(config, options);
}
},
saveScript: async (
options: SessionSaveScriptOptions = {},
): Promise<SessionSaveScriptResult> => {
const data = await execute(
INTERNAL_COMMANDS.sessionSaveScript,
options.path !== undefined ? [options.path] : [],
options,
{ force: options.force },
);
const actionCount = data.actionCount;
if (typeof actionCount !== 'number' || !Number.isInteger(actionCount) || actionCount < 0) {
throw new AppError(
'COMMAND_FAILED',
'Daemon returned an invalid saved-script action count.',
);
}
const publishedSession = readRequiredString(data, 'session');
return {
session: publishedSession,
savedScript: readRequiredString(data, 'savedScript'),
actionCount,
identifiers: { session: publishedSession },
};
},
artifacts: async (options = {}) =>
await executeCommand<AgentArtifactsResult>('artifacts', options),
},
apps: {
install: async (options: AppInstallOptions) =>
normalizeDeployResult(
await executeCommand('install', options),
resolveRequestSession(options),
),
reinstall: async (options: AppDeployOptions) =>
normalizeDeployResult(
await executeCommand('reinstall', options),
resolveRequestSession(options),
),
installFromSource: async (options: AppInstallFromSourceOptions) =>
normalizeInstallFromSourceResult(
await executeCommand('install-from-source', options),
resolveRequestSession(options),
),
list: async (options: AppListOptions = {}) => {
const data = await executeCommand<Record<string, unknown>>('apps', options);
return Array.isArray(data.apps)
? data.apps.filter((app): app is string => typeof app === 'string')
: [];
},
open: async (options: AppOpenOptions) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('open', options);
recordMetroSessionHintsAfterOpen({
config,
options,
runtime: mergeClientOptions(config, options).runtime,
sessionReused: data.sessionReused === true,
});
const device = normalizeOpenDevice(data);
const appBundleId = readOptionalString(data, 'appBundleId');
const appId = appBundleId;
const warnings = readResponseWarnings(data);
return {
session,
...(warnings.length > 0 ? { warnings } : {}),
sessionStateDir: readOptionalString(data, 'sessionStateDir'),
runnerLogPath: readOptionalString(data, 'runnerLogPath'),
requestLogPath: readOptionalString(data, 'requestLogPath'),
eventLogPath: readOptionalString(data, 'eventLogPath'),
appName: readOptionalString(data, 'appName'),
appBundleId,
appId,
selection: normalizeDeviceSelection(data.selection),
startup: normalizeStartupSample(data.startup),
runtime: normalizeRuntimeHints(data.runtime),
device,
...(data.launchConfirmation === 'accepted'
? { launchConfirmation: 'accepted' as const }
: {}),
...normalizeOpenForegroundComposition(data),
identifiers: {
session,
deviceId: device?.id,
deviceName: device?.name,
udid: device?.ios?.udid,
serial: device?.android?.serial,
appId,
appBundleId,
},
};
},
close: async (options: AppCloseOptions = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('close', options);
return {
session,
closedApp: options.app,
shutdown: normalizeTargetShutdownResult(data.shutdown),
savedScript: readOptionalString(data, 'savedScript'),
identifiers: { session },
};
},
push: async (options) => await executeCommand<CommandResult<'push'>>('push', options),
triggerEvent: async (options) =>
await executeCommand<CommandResult<'trigger-app-event'>>('trigger-app-event', options),
},
materializations: {
release: async (options: MaterializationReleaseOptions) =>
normalizeMaterializationReleaseResult(
await execute(INTERNAL_COMMANDS.releaseMaterializedPaths, [], {
...options,
materializationId: options.materializationId,
}),
),
},
leases: createLeaseClient(execute),
metro: {
prepare: async (options: MetroPrepareOptions) => {
const result = await prepareMetroRuntime({
projectRoot: options.projectRoot ?? config.cwd,
kind: options.kind,
publicBaseUrl: options.publicBaseUrl,
proxyBaseUrl: options.proxyBaseUrl,
proxyBearerToken: options.bearerToken,
bridgeScope: options.bridgeScope,
launchUrl: options.launchUrl,
companionProfileKey: options.companionProfileKey,
companionConsumerKey: options.companionConsumerKey,
metroPort: options.port,
listenHost: options.listenHost,
statusHost: options.statusHost,
startupTimeoutMs: options.startupTimeoutMs,
probeTimeoutMs: options.probeTimeoutMs,
reuseExisting: options.reuseExisting,
installDependenciesIfNeeded: options.installDependenciesIfNeeded,
runtimeFilePath: options.runtimeFilePath,
logPath: options.logPath,
});
persistMetroSessionHints(config, result);
return result;
},
reload: async (options = {}) =>
await reloadMetro({
metroHost: options.metroHost,
metroPort: options.metroPort,
bundleUrl: options.bundleUrl,
runtime: resolveMetroSessionHints(config) ?? config.runtime,
timeoutMs: options.timeoutMs,
}),
},
capture: {
snapshot: async (options: CaptureSnapshotOptions = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('snapshot', options);
// A non-default responseLevel returns the leveled snapshot digest
// ({ nodeCount, refs, … }); normalizeSnapshotResult expects the full
// `nodes` tree and would collapse it to an empty snapshot. Pass the
// leveled payload through verbatim. (Mirrors capture.screenshot; the
// caller opted into the level, so the runtime value is the leveled shape.)
if (isLeveledResponse(options)) return data as unknown as CaptureSnapshotResult;
return normalizeSnapshotResult(data, session);
},
screenshot: async (options: CaptureScreenshotOptions = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('screenshot', options);
// A non-default responseLevel returns a leveled (digest) screenshot shape
// — `overlayCount`, leveled `overlayRefs`, `artifacts` — that the default
// normalizer below would drop. Pass the leveled payload through verbatim.
// (The caller opted into a non-default level, so the static type is the
// default shape; the runtime value is the leveled payload.)
if (isLeveledResponse(options)) return data as unknown as CaptureScreenshotResult;
return normalizeScreenshotCaptureResult(data, session);
},
diff: async (options) => await executeCommand<CommandResult<'diff'>>('diff', options),
},
interactions: {
click: async (options) => await executeCommand('click', options),
press: async (options) => await executeCommand('press', options),
longPress: async (options) => await executeCommand('longpress', options),
hover: async (options) => await executeCommand('hover', options),
swipe: async (options) => await executeCommand('swipe', options),
pan: async (options) => await executeCommand('gesture', panGestureInput(options)),
drag: async (options) => await executeCommand('gesture', dragGestureInput(options)),
fling: async (options) => await executeCommand('gesture', flingGestureInput(options)),
swipeGesture: async (options) =>
await executeCommand('gesture', swipePresetGestureInput(options)),
focus: async (options) => await executeCommand('focus', options),
type: async (options) => await executeCommand('type', options),
fill: async (options) => await executeCommand('fill', options),
scroll: async (options) => await executeCommand('scroll', options),
pinch: async (options) =>
await executeCommand('gesture', centeredGestureInput('pinch', options)),
rotateGesture: async (options) =>
await executeCommand('gesture', centeredGestureInput('rotate', options)),
transformGesture: async (options) =>
await executeCommand('gesture', transformGestureInput(options)),
get: async (options) => await executeCommand('get', options),
is: async (options) => await executeCommand('is', options),
find: async (options) => await executeCommand('find', options),
},
replay: {
run: async (options) => await executeCommand<CommandResult<'replay'>>('replay', options),
test: async (options) => await executeCommand<CommandResult<'test'>>('test', options),
},
batch: {
run: async (options) => await executeCommand('batch', options),
},
observability: {
perf: async (options) => await executeCommand('perf', options),
logs: async (options = {}) => await executeCommand('logs', options),
events: async (options = {}) => await executeCommand('events', options),
network: async (options = {}) => await executeCommand('network', options),
audio: async (options = {}) => await executeCommand('audio', options),
},
debug: {
symbols: async (options) => {
const { symbolicateCrashArtifact } =
await import('@agent-device/platform-apple/debug-symbols');
return symbolicateCrashArtifact({ cwd: options.cwd ?? config.cwd, ...options });
},
},
recording: {
record: async (options) => await executeCommand<CommandResult<'record'>>('record', options),
trace: async (options) => await executeCommand<CommandResult<'trace'>>('trace', options),
},
settings: {
update: async (options) => await executeCommand('settings', options),
},
};
}
function panGestureInput(options: PanOptions): InternalRequestOptions & Record<string, unknown> {
const { x, y, dx, dy, ...common } = options;
return { ...common, kind: 'pan', origin: { x, y }, delta: { x: dx, y: dy } };
}
function dragGestureInput(options: DragOptions): InternalRequestOptions & Record<string, unknown> {
return { ...options, kind: 'drag' };
}
function flingGestureInput(
options: FlingOptions,
): InternalRequestOptions & Record<string, unknown> {
const { x, y, ...common } = options;
return { ...common, kind: 'fling', origin: { x, y } };
}
function swipePresetGestureInput(
options: SwipeGestureOptions,
): InternalRequestOptions & Record<string, unknown> {
return { ...options, kind: 'swipe' };
}
function centeredGestureInput(
kind: 'pinch' | 'rotate',
options: PinchOptions | RotateGestureOptions,
): InternalRequestOptions & Record<string, unknown> {
const { x, y, ...common } = options;
assertCompleteGestureCenter(x, y, kind);
return {
...common,
kind,
...(x === undefined && y === undefined ? {} : { origin: { x, y } }),
};
}
function transformGestureInput(
options: TransformGestureOptions,
): InternalRequestOptions & Record<string, unknown> {
const { x, y, dx, dy, ...common } = options;
return { ...common, kind: 'transform', origin: { x, y }, delta: { x: dx, y: dy } };
}
function assertCompleteGestureCenter(
x: number | undefined,
y: number | undefined,
gesture: 'pinch' | 'rotate',
): void {
if ((x === undefined) !== (y === undefined)) {
throw new AppError('INVALID_ARGS', `gesture ${gesture} center requires both x and y`);
}
}
function normalizeSnapshotResult(
data: Record<string, unknown>,
session: string | undefined,
): CaptureSnapshotResult {
const appBundleId = readOptionalString(data, 'appBundleId');
return {
nodes: readSnapshotNodes(data.nodes),
...(typeof data.truncated === 'boolean' ? { truncated: data.truncated } : {}),
appName: readOptionalString(data, 'appName'),
appBundleId,
...optionalSnapshotResponseFields(data),
identifiers: {
session,
appId: appBundleId,
appBundleId,
},
};
}
function optionalSnapshotResponseFields(
data: Record<string, unknown>,
): Partial<
Pick<
CaptureSnapshotResult,
| 'androidSnapshot'
| 'unchanged'
| 'visibility'
| 'keyboard'
| 'viewport'
| 'warnings'
| 'snapshotQuality'
| 'snapshotDiagnostics'
| 'fallbackScreenshotPath'
| 'refsGeneration'
>
> {
const visibility = asOptionalRecord(data.visibility);
const unchanged = asOptionalRecord(data.unchanged);
const keyboard = readSnapshotKeyboardBandFact(data.keyboard);
const viewport = readSnapshotViewportSize(data.viewport);
const snapshotDiagnostics = readSnapshotDiagnosticsSummary(data.snapshotDiagnostics);
return {
...(keyboard ? { keyboard } : {}),
...(viewport ? { viewport } : {}),
...(visibility ? { visibility: visibility as CaptureSnapshotResult['visibility'] } : {}),
...readSerializedSnapshotCaptureAnnotations(data),
...(unchanged ? { unchanged: unchanged as CaptureSnapshotResult['unchanged'] } : {}),
...(snapshotDiagnostics ? { snapshotDiagnostics } : {}),
...(typeof data.fallbackScreenshotPath === 'string'
? { fallbackScreenshotPath: data.fallbackScreenshotPath }
: {}),
// ADR 0014: keep the response-level ref-frame generation on Node.js results
// so callers can pin refs (`@e12~s<refsGeneration>`) before a mutation.
...(typeof data.refsGeneration === 'number' ? { refsGeneration: data.refsGeneration } : {}),
};
}
function mergeClientOptions(
config: AgentDeviceClientConfig,
options: InternalRequestOptions,
): InternalRequestOptions {
return { ...config, ...options };
}
function metroSessionHintsScope(
config: AgentDeviceClientConfig,
options: InternalRequestOptions = {},
): { stateDir: string; session: string } {
const merged = mergeClientOptions(config, options);
return {
stateDir: resolveDaemonPaths(merged.stateDir ?? process.env.AGENT_DEVICE_STATE_DIR).baseDir,
session: resolveSessionName(merged.session),
};
}
// The metro-sessions file is the session's dev-server binding; see MetroSessionHints.
function persistMetroSessionHints(
config: AgentDeviceClientConfig,
result: Pick<MetroPrepareResult, 'statusUrl' | 'iosRuntime' | 'androidRuntime'>,
): void {
try {
const deviceBaseUrls = new Set<string>();
for (const runtime of [result.iosRuntime, result.androidRuntime]) {
try {
const hints = metroHintsFromRuntime(runtime);
if (hints) deviceBaseUrls.add(hints.controlBaseUrl);
} catch {}
}
writeMetroSessionHints({
...metroSessionHintsScope(config),
hints: {
controlBaseUrl: new URL('.', result.statusUrl).toString(),
deviceBaseUrls: [...deviceBaseUrls],
},
});
} catch {
// Session-hint persistence is best-effort; reload still works with explicit flags.
}
}
function resolveMetroSessionHints(
config: AgentDeviceClientConfig,
): SessionRuntimeHints | undefined {
try {
const binding = readMetroSessionHints(metroSessionHintsScope(config));
return binding ? { bundleUrl: binding.controlBaseUrl } : undefined;
} catch {
return undefined;
}
}
function metroHintsFromRuntime(
runtime: SessionRuntimeHints | undefined,
): MetroSessionHints | undefined {
const { metroHost, metroPort, bundleUrl } = runtime ?? {};
if (metroHost === undefined && metroPort === undefined && bundleUrl === undefined)
return undefined;
return { controlBaseUrl: resolveMetroServerUrl({ runtime }).toString() };
}
// Hint flags rebind the session's dev server; a hintless open that created the session clears
// any leftover binding from a previous same-name session.
function recordMetroSessionHintsAfterOpen(params: {
config: AgentDeviceClientConfig;
options: InternalRequestOptions;
runtime: SessionRuntimeHints | undefined;
sessionReused: boolean;
}): void {
try {
const scope = metroSessionHintsScope(params.config, params.options);
const hints = metroHintsFromRuntime(params.runtime);
if (hints) {
const binding =
params.options.runtime === undefined ? readMetroSessionHints(scope) : undefined;
if (
binding &&
(params.sessionReused || binding.deviceBaseUrls?.includes(hints.controlBaseUrl))
)
return;
writeMetroSessionHints({ ...scope, hints });
return;
}
if (!params.sessionReused) {
clearMetroSessionHints(scope);
}
} catch {
// Session-hint sync is best-effort; reload still works with explicit flags.
}
}
function clearMetroSessionHintsQuietly(
config: AgentDeviceClientConfig,
options: InternalRequestOptions,
): void {
try {
clearMetroSessionHints(metroSessionHintsScope(config, options));
} catch {
// Session-hint cleanup is best-effort; close must not fail on local file state.
}
}
export type * from './client/client-types.ts';