Repository navigation
Expand file tree
/
Copy pathruntime.ts
More file actions
461 lines (440 loc) · 16.8 KB
/
Copy pathruntime.ts
File metadata and controls
461 lines (440 loc) · 16.8 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
import { setTimeout as sleep } from 'node:timers/promises';
import { createProviderAppLogOperations } from '@agent-device/capture-kit/provider-app-log';
import { APP_LOG_RESOURCE_KIND } from '@agent-device/contracts/app-log-runtime';
import {
applicationLifecycleOperationFacts,
availableApplicationLifecycleOperations,
} from '@agent-device/contracts/application-lifecycle-runtime';
import {
bindDirectApplicationLifecycle,
bindProviderApplicationLifecycleInteractor,
} from '@agent-device/contracts/application-lifecycle-interaction';
import { backRuntimeOperationFacts } from '@agent-device/contracts/back-runtime';
import type { DeviceLease, LeaseLifecycleContext } from '@agent-device/contracts/device';
import type { DurableDescriptorCodec } from '@agent-device/contracts/durable-resource-envelope';
import {
bindProviderFocusInteractor,
focusRuntimeOperationFacts,
} from '@agent-device/contracts/focus-runtime';
import { bindAdmittedProviderInteractorOperations } from '@agent-device/contracts/interactor-operation-catalog';
import type { Interactor } from '@agent-device/contracts/interactor-types';
import {
providerRuntimeOwner,
sameRuntimeOwner,
unavailableFact,
type DeviceBinding,
type RuntimeFacts,
} from '@agent-device/contracts/platform-runtime';
import type {
PlatformRuntimeHost,
PlatformRuntimeOperations,
PlatformRuntimeOwner,
} from '@agent-device/contracts/platform-runtime-operations';
import { createUnavailablePlatformRuntimeFacts } from '@agent-device/contracts/platform-runtime-unavailable';
import { perfRuntimeOperationFacts } from '@agent-device/contracts/perf-runtime';
import {
missingPerfAppMetric,
settlePerfMetric,
} from '@agent-device/contracts/perf-runtime-operation-builder';
import {
bindProviderScreenshotInteractor,
screenshotRuntimeOperationFacts,
} from '@agent-device/contracts/screenshot-runtime';
import {
bindProviderScrollInteractor,
scrollRuntimeOperationFacts,
} from '@agent-device/contracts/scroll-runtime';
import {
bindProviderSnapshotInteractor,
snapshotRuntimeOperationFacts,
} from '@agent-device/contracts/snapshot-runtime';
import {
bindProviderTouchInteractor,
touchRuntimeOperationFacts,
} from '@agent-device/contracts/touch-runtime';
import { systemButtonRuntimeOperationFacts } from '@agent-device/contracts/system-button-runtime';
import { tvRemoteRuntimeOperationFacts } from '@agent-device/contracts/tv-remote-runtime';
import {
bindProviderTypeTextInteractor,
typeTextRuntimeOperationFacts,
} from '@agent-device/contracts/type-text-runtime';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { createAres, type HostEnv } from './ares.ts';
import type { CdpSession } from './cdp.ts';
import { createWebosInteractor, detachApp, type WebosSession } from './interactor.ts';
import { SUPPORTED_REMOTE_BUTTONS } from './keys.ts';
import { PROVIDER, type WebosOptions } from './provider.ts';
import { createSsap } from './ssap.ts';
const DEVICE_ID_PREFIX = 'webos:';
const INSTANCE = 'local';
const available = Object.freeze({ available: true } as const);
const notOnWebos = unavailableFact('unsupported-provider-mode', 'Not supported on webOS.');
// agent-device has a fixed platform list and leases only ios/android/harmonyos devices, so a
// webOS TV enters as an Android TV device that this provider owns end to end.
function webosDevice(name: string): DeviceInfo {
return {
platform: 'android',
id: `${DEVICE_ID_PREFIX}${name}`,
name,
kind: 'device',
target: 'tv',
booted: true,
};
}
function webosFacts(device: DeviceInfo, owner: ReturnType<typeof providerRuntimeOwner>) {
const refusedByDefault = createUnavailablePlatformRuntimeFacts(device, owner, {
appLog: notOnWebos,
network: notOnWebos,
screenshot: notOnWebos,
viewport: notOnWebos,
focus: notOnWebos,
gesture: notOnWebos,
scroll: notOnWebos,
typeText: notOnWebos,
touch: notOnWebos,
elementText: notOnWebos,
back: notOnWebos,
orientation: notOnWebos,
fold: notOnWebos,
telephony: notOnWebos,
tvRemote: notOnWebos,
keyboard: notOnWebos,
clipboard: notOnWebos,
systemButton: notOnWebos,
triggerAppEvent: notOnWebos,
settings: notOnWebos,
readAlert: notOnWebos,
awaitAlert: notOnWebos,
acceptAlert: notOnWebos,
dismissAlert: notOnWebos,
audioProbeCapture: notOnWebos,
audioProbeQuery: notOnWebos,
lifecycle: applicationLifecycleOperationFacts({
resolveOpenTarget: available,
prepareApplicationOpen: available,
openApplication: available,
applyRuntimeHints: notOnWebos,
clearRuntimeHints: notOnWebos,
closeApplication: available,
finalizeApplicationClose: available,
prepareAppleRunner: notOnWebos,
configureProviderPortReverse: notOnWebos,
}),
});
return Object.freeze({
device: refusedByDefault.device,
operations: Object.freeze({
...refusedByDefault.operations,
...snapshotRuntimeOperationFacts({
capture: available,
customActions: notOnWebos,
withoutActiveApp: notOnWebos,
}),
...screenshotRuntimeOperationFacts({ capture: available }),
...touchFacts,
...focusRuntimeOperationFacts({ focus: available }),
...typeTextRuntimeOperationFacts({ type: available }),
...scrollRuntimeOperationFacts({ scroll: available }),
...backRuntimeOperationFacts({ back: available }),
...tvRemoteRuntimeOperationFacts({
tvRemote: available,
buttonSupport: { supported: SUPPORTED_REMOTE_BUTTONS, unsupported: notOnWebos },
}),
...perfRuntimeOperationFacts({
frames: notOnWebos,
memorySample: available,
memorySnapshot: notOnWebos,
nativeCapture: notOnWebos,
profileReport: notOnWebos,
}),
...systemButtonRuntimeOperationFacts({ unsupported: notOnWebos, home: available }),
appLogInspect: available,
appLogDoctor: available,
appLogStart: available,
appLogReattach: available,
appLogCleanup: available,
networkDump: available,
listApps: available,
appState: available,
deployApp: available,
uninstallApp: available,
ensureReady: available,
bootTarget: available,
}),
}) satisfies RuntimeFacts<PlatformRuntimeOperations>;
}
const touchFacts = touchRuntimeOperationFacts({
unsupported: notOnWebos,
tap: available,
longPress: available,
hover: available,
fill: available,
});
export function createWebosRuntime(options: WebosOptions, host: PlatformRuntimeHostLike) {
const ares = createAres(options.aresBin, host.env);
const ssap = createSsap(host.env, options.ssapKeyFile);
const tvs = new Map<string, WebosSession>();
const leases = new Map<string, string>();
const owner = providerRuntimeOwner(PROVIDER, INSTANCE);
const ownsDevice = (device: DeviceInfo) => device.id.startsWith(DEVICE_ID_PREFIX);
const sessionFor = (device: DeviceInfo) =>
ownsDevice(device) ? tvs.get(tvName(device)) : undefined;
const getInteractor = (device: DeviceInfo): Interactor | undefined => {
const session = sessionFor(device);
return session && createWebosInteractor(session);
};
async function allocate(lease: DeviceLease, context?: LeaseLifecycleContext) {
if (lease.leaseProvider !== PROVIDER) return undefined;
const leased = leases.get(lease.leaseId);
if (leased) return { device: webosDevice(leased) };
const flagDevice = context?.flags?.device;
const requested = typeof flagDevice === 'string' ? flagDevice : options.device;
const available = await ares.listDevices();
const tv = requested
? available.find((candidate) => candidate.name === requested)
: (available.find((candidate) => candidate.isDefault) ?? available[0]);
if (!tv) {
throw host.createError(
'DEVICE_NOT_FOUND',
`No webOS TV ${requested ? `named ${requested} ` : ''}in ares-setup-device`,
{
available: available.map((candidate) => candidate.name),
hint: 'Add the TV with ares-setup-device, or pass --device <name>.',
},
);
}
const holder = [...leases].find(([id, name]) => name === tv.name && id !== lease.leaseId);
if (holder) {
throw host.createError('DEVICE_IN_USE', `webOS TV ${tv.name} is held by another lease`, {
hint: 'Disconnect the session that holds the TV, or wait for its lease to expire.',
});
}
if (!tvs.has(tv.name)) {
tvs.set(tv.name, {
tv,
ares: ares.forDevice(tv.name),
ssap: ssap.forTv(tv.ip),
logs: new Map(),
});
}
leases.set(lease.leaseId, tv.name);
return { device: webosDevice(tv.name) };
}
async function release(lease: DeviceLease) {
return leases.delete(lease.leaseId) ? {} : undefined;
}
const runtime = {
provider: PROVIDER,
leaseLifecycle: { allocate, release },
deviceInventoryProvider: async (request: { leaseProvider?: string; leaseId?: string }) => {
if (request.leaseProvider !== PROVIDER || !request.leaseId) return null;
const name = leases.get(request.leaseId);
return name ? [webosDevice(name)] : null;
},
ownsDevice,
getInteractor,
shutdown: async () => {
for (const session of tvs.values()) detachApp(session);
tvs.clear();
leases.clear();
},
};
const platformModule = Object.freeze({
owner,
loadRuntime: async (platformHost: PlatformRuntimeHost): Promise<PlatformRuntimeOwner> =>
createWebosPlatformRuntime({ owner, ownsDevice, getInteractor, sessionFor }, platformHost),
});
return { runtime, platformModule };
}
type PlatformRuntimeHostLike = Readonly<{
env: HostEnv;
createError(code: string, message: string, details?: Record<string, unknown>): Error;
}>;
const tvName = (device: DeviceInfo) => device.id.slice(DEVICE_ID_PREFIX.length);
type WebosAppLogDescriptor = Readonly<{
transport: 'webos-cdp';
tv: string;
appBundleId: string;
outputPath: string;
}>;
const appLogDescriptorCodec: DurableDescriptorCodec<
WebosAppLogDescriptor,
typeof APP_LOG_RESOURCE_KIND
> = Object.freeze({
resourceKind: APP_LOG_RESOURCE_KIND,
version: 1,
encode: (descriptor) => ({ ...descriptor }),
decode: (body) =>
body.transport === 'webos-cdp' &&
typeof body.tv === 'string' &&
typeof body.appBundleId === 'string' &&
typeof body.outputPath === 'string'
? {
status: 'decoded',
descriptor: {
transport: 'webos-cdp',
tv: body.tv,
appBundleId: body.appBundleId,
outputPath: body.outputPath,
},
}
: { status: 'invalid', message: 'Invalid webOS app-log descriptor' },
});
type WebosRuntimeContext = Readonly<{
owner: ReturnType<typeof providerRuntimeOwner>;
ownsDevice(device: DeviceInfo): boolean;
getInteractor(device: DeviceInfo): Interactor | undefined;
sessionFor(device: DeviceInfo): WebosSession | undefined;
}>;
function createWebosPlatformRuntime(
{ owner, ownsDevice, getInteractor, sessionFor }: WebosRuntimeContext,
host: PlatformRuntimeHost,
): PlatformRuntimeOwner {
return Object.freeze({
owner,
ownsDevice,
inspectFacts: async (device) => webosFacts(device, owner),
bind: async (request) => {
if (request.intent.kind === 'exact-owner' && !sameRuntimeOwner(request.intent.owner, owner)) {
throw new AppError('UNSUPPORTED_OPERATION', 'webOS runtime owner identity does not match');
}
const { device } = request;
const { signal } = request.scope;
const facts = webosFacts(device, owner);
const resolveInteractor = () => getInteractor(device);
const requireSession = () => {
const session = sessionFor(device);
if (!session) {
throw new AppError('COMMAND_FAILED', `webOS TV ${tvName(device)} has no active session`, {
hint: 'Run connect webos, then open <appId>.',
});
}
return session;
};
const logReader = (session: WebosSession) => ({
readLogs: async (appBundleId: string, lineLimit: number) =>
session.logs.get(appBundleId)?.tail(lineLimit) ?? '',
[Symbol.asyncDispose]: async () => undefined,
});
const appLogs = createProviderAppLogOperations({
host,
device,
owner,
signal,
provider: 'webOS',
backend: 'android',
sessionCheck: 'webosSessionAvailable',
unavailableMessage: 'webOS app logs require an active session. Run open <appId> first.',
codec: appLogDescriptorCodec,
openCurrent: async () => {
const session = sessionFor(device);
return session?.page ? logReader(session) : undefined;
},
describe: (_reader, target) => ({
transport: 'webos-cdp' as const,
tv: tvName(device),
appBundleId: target.appBundleId,
outputPath: target.outputPath,
}),
matchesDevice: (descriptor) => descriptor.tv === tvName(device),
reconnect: async (descriptor) => {
const session = sessionFor(device);
return session?.page && session.appId === descriptor.appBundleId
? { status: 'opened', reader: logReader(session) }
: { status: 'missing' };
},
});
const lifecycle = bindDirectApplicationLifecycle({
owner: 'webOS',
openTargetIdentity: 'bundle-id',
binding: bindProviderApplicationLifecycleInteractor({ device, signal, resolveInteractor }),
});
const appOperations: Pick<
PlatformRuntimeOperations,
'listApps' | 'appState' | 'deployApp' | 'uninstallApp' | 'perfMemorySample'
> = {
listApps: async () => await requireSession().ares.listApps(),
appState: async () => ({ package: await requireSession().ssap.foregroundAppId() }),
deployApp: async ({ app, appPath }) => {
await requireSession().ares.install(appPath);
return { packageName: app };
},
uninstallApp: async ({ app }) => {
const { ares } = requireSession();
const installed = await ares.listApps();
if (!installed.some((candidate) => candidate.id === app)) return { wasInstalled: false };
await ares.remove(app);
return { wasInstalled: true, packageName: app };
},
perfMemorySample: async ({ appId }) => {
const page = sessionFor(device)?.page;
return {
metric: page
? await settlePerfMetric(sampleMemory(page))
: missingPerfAppMetric('webOS', appId ? `${appId} page` : 'page'),
sampling: {
method: 'cdp-performance-getmetrics',
description:
'JS heap and DOM counters of the attached page from Performance.getMetrics. Heap values are in kilobytes.',
unit: 'kB',
},
};
},
};
return Object.freeze({
device,
owner,
facts,
operations: Object.freeze({
ensureReady: async () => device,
bootTarget: async () => device,
...appLogs,
...appOperations,
...availableApplicationLifecycleOperations(lifecycle, facts.operations),
...bindProviderSnapshotInteractor({
device,
signal,
resolveInteractor,
presentIosAcquisition: host.snapshot.presentIosAcquisition,
}),
...bindProviderScreenshotInteractor({ device, signal, resolveInteractor }),
...bindProviderTouchInteractor({
device,
signal,
resolveInteractor,
facts: touchFacts,
pause: async (milliseconds) => await sleep(milliseconds, undefined, { signal }),
}),
...bindProviderFocusInteractor({ device, signal, resolveInteractor }),
...bindProviderTypeTextInteractor({ device, signal, resolveInteractor }),
...bindProviderScrollInteractor({ device, signal, resolveInteractor }),
...bindAdmittedProviderInteractorOperations({
device,
signal,
resolveInteractor,
facts: facts.operations,
}),
}),
[Symbol.asyncDispose]: async () => undefined,
}) satisfies DeviceBinding<PlatformRuntimeOperations>;
},
shutdown: async () => undefined,
});
}
async function sampleMemory(page: CdpSession) {
await page.send('Performance.enable');
const { metrics } = await page.send<{ metrics: { name: string; value: number }[] }>(
'Performance.getMetrics',
);
const metric = (name: string) => metrics.find((candidate) => candidate.name === name)?.value;
const kilobytes = (value: number | undefined) =>
value === undefined ? undefined : Math.round(value / 1024);
return {
jsHeapUsedKb: kilobytes(metric('JSHeapUsedSize')),
jsHeapTotalKb: kilobytes(metric('JSHeapTotalSize')),
nodes: metric('Nodes'),
documents: metric('Documents'),
jsEventListeners: metric('JSEventListeners'),
};
}