Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3import * as SchemaTransformation from "effect/SchemaTransformation";
4
5import { ThreadId, TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
6
7export const DevicePlatform = Schema.Literals(["ios", "android"]);
8export type DevicePlatform = typeof DevicePlatform.Type;
9
10export const DeviceHostId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
11export type DeviceHostId = typeof DeviceHostId.Type;
12
13export const LOCAL_DEVICE_HOST_ID = "local" as DeviceHostId;
14export const LOCAL_DEVICE_HOST_LABEL = "This machine";
15
16const ConfiguredDeviceHostId = DeviceHostId.check(
17 Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/),
18 Schema.makeFilter((id) => id !== "local" || "The local host id is reserved."),
19);
20
21export const SshDeviceHostConfig = Schema.Struct({
22 // Hosts saved before EAS hosts existed carry no kind.
23 kind: Schema.Literal("ssh").pipe(Schema.withDecodingDefaultKey(Effect.succeed("ssh" as const))),
24 id: ConfiguredDeviceHostId,
25 label: TrimmedNonEmptyString,
26 target: TrimmedNonEmptyString.check(Schema.isPattern(/^[^\s-][^\s]*$/)),
27 identityFile: Schema.optional(TrimmedNonEmptyString),
28 port: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
29});
30export type SshDeviceHostConfig = typeof SshDeviceHostConfig.Type;
31
32/**
33 * Cloud simulators from EAS Simulator. Sessions bill the Expo account until
34 * they stop, so every one is bounded. The Expo credential is not stored here.
35 */
36export const EasDeviceHostConfig = Schema.Struct({
37 kind: Schema.Literal("eas"),
38 id: ConfiguredDeviceHostId,
39 label: TrimmedNonEmptyString,
40 /** EAS project that sessions run under, when the project's app config does not name one. */
41 appId: Schema.optional(TrimmedNonEmptyString),
42 /**
43 * Expo access token, kept in the secret store. When empty the server uses
44 * EXPO_TOKEN, then the `eas login` session. This is `secretSetting` from
45 * settings.ts, which imports this module.
46 */
47 accessToken: TrimmedString.pipe(
48 Schema.withDecodingDefaultKey(Effect.succeed("")),
49 Schema.annotateKey({ settingsSecret: true }),
50 ),
51 /** EAS allows at most 40 minutes on free accounts and 115 on paid ones. */
52 maxSessionMinutes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 115 })).pipe(
53 Schema.withDecodingDefaultKey(Effect.succeed(30)),
54 ),
55 idleMinutes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 60 })).pipe(
56 Schema.withDecodingDefaultKey(Effect.succeed(10)),
57 ),
58 maxConcurrentSessions: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 20 })).pipe(
59 Schema.withDecodingDefaultKey(Effect.succeed(2)),
60 ),
61}).check(
62 // EAS requires the idle limit to be smaller than the session limit.
63 Schema.makeFilter(
64 (host: { readonly idleMinutes: number; readonly maxSessionMinutes: number }) =>
65 host.idleMinutes < host.maxSessionMinutes ||
66 "Idle minutes must be smaller than session minutes.",
67 ),
68);
69export type EasDeviceHostConfig = typeof EasDeviceHostConfig.Type;
70
71/**
72 * Alpha: devices leased from a Simlock gateway (https://incubator.callstack.com/simlock).
73 * T3 never installs Simlock; the gateway and its workers are the user's own.
74 */
75export const SimlockDeviceHostConfig = Schema.Struct({
76 kind: Schema.Literal("simlock"),
77 id: ConfiguredDeviceHostId,
78 label: TrimmedNonEmptyString,
79 /** The gateway's origin, such as https://gateway.example.ts.net:4700. */
80 gatewayUrl: TrimmedNonEmptyString.check(Schema.isPattern(/^https?:\/\/[^\s/]+\/?$/)),
81 /** Leases, drives, watches, and takes input on its own leases. Kept in the secret store. */
82 agentToken: TrimmedString.pipe(
83 Schema.withDecodingDefaultKey(Effect.succeed("")),
84 Schema.annotateKey({ settingsSecret: true }),
85 ),
86 maxLeases: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 20 })).pipe(
87 Schema.withDecodingDefaultKey(Effect.succeed(2)),
88 ),
89 /** A lease the Device panel keeps alive ends this long after it started. */
90 maxLeaseMinutes: Schema.Int.check(Schema.isBetween({ minimum: 5, maximum: 240 })).pipe(
91 Schema.withDecodingDefaultKey(Effect.succeed(60)),
92 ),
93});
94export type SimlockDeviceHostConfig = typeof SimlockDeviceHostConfig.Type;
95
96export type DeviceHostConfig = SshDeviceHostConfig | EasDeviceHostConfig | SimlockDeviceHostConfig;
97
98const uniqueHostIds = Schema.makeFilter(
99 (hosts: ReadonlyArray<{ readonly id: string }>) =>
100 new Set(hosts.map((host) => host.id)).size === hosts.length ||
101 "Device host ids must be unique.",
102);
103
104export const SshDeviceHostConfigs = Schema.Array(SshDeviceHostConfig).check(uniqueHostIds);
105
106/**
107 * Kept apart from the SSH hosts in settings: servers and clients from before
108 * EAS hosts decode `deviceHosts` as SSH hosts and would reject the whole file
109 * or snapshot over one EAS entry.
110 */
111export const EasDeviceHostConfigs = Schema.Array(EasDeviceHostConfig).check(uniqueHostIds);
112
113/** Kept apart from the other host lists for the same reason as EAS hosts. */
114export const SimlockDeviceHostConfigs = Schema.Array(SimlockDeviceHostConfig).check(uniqueHostIds);
115
116export const DeviceEasAccountInput = Schema.Struct({
117 /** A saved EAS host whose stored token is checked when no new token is given. */
118 hostId: Schema.optional(DeviceHostId),
119 accessToken: Schema.optional(TrimmedString),
120});
121export type DeviceEasAccountInput = typeof DeviceEasAccountInput.Type;
122
123export const DeviceEasAccount = Schema.Struct({
124 signedInAs: Schema.String,
125 credentialSource: Schema.Literals(["settings", "env", "eas-login"]),
126 apps: Schema.Array(Schema.Struct({ id: Schema.String, fullName: Schema.String })),
127});
128export type DeviceEasAccount = typeof DeviceEasAccount.Type;
129
130/** Checking an Expo credential failed; no device host is involved yet. */
131export class DeviceEasAccountError extends Schema.TaggedError<DeviceEasAccountError>()(
132 "DeviceEasAccountError",
133 // No cause: this error reaches the browser, and the reason already says what Expo answered.
134 { reason: Schema.String },
135) {
136 override get message(): string {
137 return this.reason;
138 }
139}
140
141export const DeviceId = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
142export type DeviceId = typeof DeviceId.Type;
143
144export const DeviceSummary = Schema.Struct({
145 hostId: DeviceHostId,
146 id: DeviceId,
147 platform: DevicePlatform,
148 name: TrimmedNonEmptyString,
149 version: Schema.String,
150 booted: Schema.Boolean,
151 physical: Schema.Boolean,
152});
153export type DeviceSummary = typeof DeviceSummary.Type;
154
155export const DevicePlatformAvailability = Schema.Struct({
156 platform: DevicePlatform,
157 available: Schema.Boolean,
158 reason: Schema.optional(Schema.String),
159});
160export type DevicePlatformAvailability = typeof DevicePlatformAvailability.Type;
161
162export const DeviceToolVersion = Schema.Struct({
163 requiredVersion: Schema.String,
164 installedVersions: Schema.Array(Schema.String),
165 runningVersion: Schema.NullOr(Schema.String),
166});
167export type DeviceToolVersion = typeof DeviceToolVersion.Type;
168
169export const DeviceToolVersions = Schema.Struct({
170 hub: DeviceToolVersion,
171 agent: DeviceToolVersion,
172});
173export type DeviceToolVersions = typeof DeviceToolVersions.Type;
174
175const deviceHostSummaryFields = {
176 id: DeviceHostId,
177 label: TrimmedNonEmptyString,
178 platforms: Schema.Array(DevicePlatformAvailability),
179 tools: Schema.optional(DeviceToolVersions),
180 toolInspectionError: Schema.optional(Schema.String),
181 hubInstalled: Schema.Boolean,
182 agentDeviceInstalled: Schema.Boolean,
183};
184const MachineDeviceHostSummary = Schema.Struct({
185 ...deviceHostSummaryFields,
186 kind: Schema.Literals(["local", "ssh"]),
187});
188const EasDeviceHostSummary = Schema.Struct({
189 ...deviceHostSummaryFields,
190 kind: Schema.Literal("eas"),
191});
192const SimlockDeviceHostSummary = Schema.Struct({
193 ...deviceHostSummaryFields,
194 kind: Schema.Literal("simlock"),
195});
196export const DeviceHostSummary = Schema.Union([
197 MachineDeviceHostSummary,
198 EasDeviceHostSummary,
199 SimlockDeviceHostSummary,
200]);
201export type DeviceHostSummary = typeof DeviceHostSummary.Type;
202
203export const DeviceHostStatus = Schema.Literals([
204 "disabled",
205 "idle",
206 "installing",
207 "starting",
208 "ready",
209 "failed",
210]);
211export type DeviceHostStatus = typeof DeviceHostStatus.Type;
212
213export const DeviceSession = Schema.Struct({
214 threadId: ThreadId,
215 hostId: DeviceHostId,
216 deviceId: DeviceId,
217 platform: DevicePlatform,
218 openedAt: Schema.String,
219});
220export type DeviceSession = typeof DeviceSession.Type;
221
222export const DeviceHostStatuses = Schema.Record(
223 DeviceHostId,
224 Schema.Struct({
225 status: DeviceHostStatus,
226 detail: Schema.optional(Schema.String),
227 androidDiscoveryIncomplete: Schema.optional(Schema.Boolean),
228 }),
229);
230
231const deviceServiceStateFields = {
232 supportsHostRetry: Schema.optional(Schema.Boolean),
233 supportsToolUpdate: Schema.optional(Schema.Boolean),
234 supportsToolInspection: Schema.optional(Schema.Boolean),
235 /** Servers from before EAS hosts ignore `easDeviceHosts`, so clients offer them only when set. */
236 supportsEasHosts: Schema.optional(Schema.Boolean),
237 /** Servers from before Simlock hosts ignore `simlockDeviceHosts`. */
238 supportsSimlockHosts: Schema.optional(Schema.Boolean),
239 hostStatus: DeviceHostStatus,
240 hostStatusDetail: Schema.optional(Schema.String),
241 hostStatuses: DeviceHostStatuses,
242 devices: Schema.Array(DeviceSummary),
243 sessions: Schema.Array(DeviceSession),
244 bootingDevices: Schema.optional(
245 Schema.Array(Schema.Struct({ ...DeviceSummary.fields, threadId: ThreadId })),
246 ),
247 onboardingCompleted: Schema.Boolean,
248 agentAccessEnabled: Schema.Boolean,
249 hubBasePath: Schema.String,
250 revision: Schema.Int,
251};
252
253/**
254 * EAS host summaries travel as `easHosts`: clients from before EAS hosts
255 * decode `hosts` with a `local | ssh` kind and would reject the whole state.
256 * Decoded, every host is in `hosts`.
257 */
258const DeviceServiceStateWire = Schema.Struct({
259 ...deviceServiceStateFields,
260 hosts: Schema.Array(MachineDeviceHostSummary),
261 easHosts: Schema.optional(Schema.Array(EasDeviceHostSummary)),
262 simlockHosts: Schema.optional(Schema.Array(SimlockDeviceHostSummary)),
263});
264const DeviceServiceStateDecoded = Schema.Struct({
265 ...deviceServiceStateFields,
266 hosts: Schema.Array(DeviceHostSummary),
267});
268
269export const DeviceServiceState = DeviceServiceStateWire.pipe(
270 Schema.decodeTo(
271 Schema.toType(DeviceServiceStateDecoded),
272 SchemaTransformation.transform<
273 typeof DeviceServiceStateDecoded.Type,
274 typeof DeviceServiceStateWire.Type
275 >({
276 decode: ({ easHosts, simlockHosts, ...state }) => ({
277 ...state,
278 hosts: [...state.hosts, ...(easHosts ?? []), ...(simlockHosts ?? [])],
279 }),
280 encode: (state) => ({
281 ...state,
282 hosts: state.hosts.filter(
283 (host): host is typeof MachineDeviceHostSummary.Type =>
284 host.kind === "local" || host.kind === "ssh",
285 ),
286 easHosts: state.hosts.filter(
287 (host): host is typeof EasDeviceHostSummary.Type => host.kind === "eas",
288 ),
289 simlockHosts: state.hosts.filter(
290 (host): host is typeof SimlockDeviceHostSummary.Type => host.kind === "simlock",
291 ),
292 }),
293 }),
294 ),
295);
296export type DeviceServiceState = typeof DeviceServiceState.Type;
297
298export const DeviceListInput = Schema.Struct({
299 updateTool: Schema.optional(Schema.Literals(["hub", "agent"])),
300 inspectOnly: Schema.optional(Schema.Boolean),
301 retryHostId: Schema.optional(DeviceHostId),
302});
303export type DeviceListInput = typeof DeviceListInput.Type;
304
305export const DeviceConfigureInput = Schema.Struct({
306 enabled: Schema.optional(Schema.Boolean),
307 agentAccessEnabled: Schema.optional(Schema.Boolean),
308 onboardingCompleted: Schema.optional(Schema.Boolean),
309});
310export type DeviceConfigureInput = typeof DeviceConfigureInput.Type;
311
312export const DeviceOpenInput = Schema.Struct({
313 threadId: ThreadId,
314 hostId: Schema.optional(DeviceHostId),
315 deviceId: DeviceId,
316 platform: DevicePlatform,
317 /** Boot the simulator or emulator when it is not running. Defaults to true. */
318 boot: Schema.optional(Schema.Boolean),
319});
320export type DeviceOpenInput = typeof DeviceOpenInput.Type;
321
322export const DeviceCloseInput = Schema.Struct({
323 hostId: Schema.optional(DeviceHostId),
324 threadId: ThreadId,
325 /** Omit to close every device session for the thread. */
326 deviceId: Schema.optional(DeviceId),
327 /** Also shut the simulator or emulator down. Defaults to false. */
328 shutdown: Schema.optional(Schema.Boolean),
329});
330export type DeviceCloseInput = typeof DeviceCloseInput.Type;
331
332export const DeviceShutdownInput = Schema.Struct({
333 hostId: Schema.optional(DeviceHostId),
334 deviceId: DeviceId,
335 platform: DevicePlatform,
336});
337export type DeviceShutdownInput = typeof DeviceShutdownInput.Type;
338
339export const DeviceAppearance = Schema.Literals(["light", "dark"]);
340export type DeviceAppearance = typeof DeviceAppearance.Type;
341
342export const DeviceTextSize = Schema.Literals(["small", "default", "large", "extra-large"]);
343export type DeviceTextSize = typeof DeviceTextSize.Type;
344
345export const DeviceColorFilter = Schema.Literals([
346 "none",
347 "grayscale",
348 "red-green",
349 "green-red",
350 "blue-yellow",
351]);
352export type DeviceColorFilter = typeof DeviceColorFilter.Type;
353
354export const DeviceOrientation = Schema.Literals([
355 "portrait",
356 "landscape_left",
357 "portrait_upside_down",
358 "landscape_right",
359]);
360export type DeviceOrientation = typeof DeviceOrientation.Type;
361
362export const DeviceSettings = Schema.Struct({
363 appearance: Schema.optional(DeviceAppearance),
364 textSize: Schema.optional(DeviceTextSize),
365 reduceMotion: Schema.optional(Schema.Boolean),
366 increaseContrast: Schema.optional(Schema.Boolean),
367 reduceTransparency: Schema.optional(Schema.Boolean),
368 showBorders: Schema.optional(Schema.Boolean),
369 voiceOver: Schema.optional(Schema.Boolean),
370 liquidGlass: Schema.optional(Schema.Literals(["clear", "tinted"])),
371 colorFilter: Schema.optional(DeviceColorFilter),
372 networkEnabled: Schema.optional(Schema.Boolean),
373 location: Schema.optional(
374 Schema.NullOr(Schema.Struct({ latitude: Schema.Number, longitude: Schema.Number })),
375 ),
376});
377export type DeviceSettings = typeof DeviceSettings.Type;
378
379export const DeviceForegroundApp = Schema.Struct({
380 id: Schema.String,
381 name: Schema.optional(Schema.String),
382 version: Schema.optional(Schema.String),
383});
384export type DeviceForegroundApp = typeof DeviceForegroundApp.Type;
385
386export const DeviceDetail = Schema.Struct({
387 hostId: DeviceHostId,
388 deviceId: DeviceId,
389 settings: DeviceSettings,
390 foregroundApp: Schema.NullOr(DeviceForegroundApp),
391 readAt: Schema.String,
392});
393export type DeviceDetail = typeof DeviceDetail.Type;
394
395export const DevicePermission = Schema.Literals([
396 "camera",
397 "microphone",
398 "photos",
399 "contacts",
400 "calendar",
401 "reminders",
402 "location",
403 "notifications",
404 "motion",
405 "media-library",
406 "faceid",
407]);
408export type DevicePermission = typeof DevicePermission.Type;
409
410const DeviceTarget = {
411 hostId: Schema.optional(DeviceHostId),
412 deviceId: DeviceId,
413};
414
415export const DeviceActionInput = Schema.Union([
416 Schema.Struct({
417 ...DeviceTarget,
418 type: Schema.Literal("setAppearance"),
419 value: DeviceAppearance,
420 }),
421 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("setTextSize"), value: DeviceTextSize }),
422 Schema.Struct({
423 ...DeviceTarget,
424 type: Schema.Literal("setToggle"),
425 setting: Schema.Literals([
426 "reduceMotion",
427 "increaseContrast",
428 "reduceTransparency",
429 "showBorders",
430 "voiceOver",
431 "networkEnabled",
432 ]),
433 value: Schema.Boolean,
434 }),
435 Schema.Struct({
436 ...DeviceTarget,
437 type: Schema.Literal("setLiquidGlass"),
438 value: Schema.Literals(["clear", "tinted"]),
439 }),
440 Schema.Struct({
441 ...DeviceTarget,
442 type: Schema.Literal("setColorFilter"),
443 value: DeviceColorFilter,
444 }),
445 Schema.Struct({
446 ...DeviceTarget,
447 type: Schema.Literal("setOrientation"),
448 value: DeviceOrientation,
449 }),
450 Schema.Struct({
451 ...DeviceTarget,
452 type: Schema.Literal("setLocation"),
453 latitude: Schema.Number.check(Schema.isBetween({ minimum: -90, maximum: 90 })),
454 longitude: Schema.Number.check(Schema.isBetween({ minimum: -180, maximum: 180 })),
455 }),
456 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("clearLocation") }),
457 Schema.Struct({
458 ...DeviceTarget,
459 type: Schema.Literal("setPermission"),
460 appId: TrimmedNonEmptyString,
461 permission: DevicePermission,
462 decision: Schema.Literals(["grant", "revoke", "reset"]),
463 }),
464 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("openUrl"), url: TrimmedNonEmptyString }),
465 Schema.Struct({
466 ...DeviceTarget,
467 type: Schema.Literal("launchApp"),
468 appId: TrimmedNonEmptyString,
469 }),
470 Schema.Struct({
471 ...DeviceTarget,
472 type: Schema.Literal("terminateApp"),
473 appId: TrimmedNonEmptyString,
474 }),
475 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("shake") }),
476 Schema.Struct({
477 ...DeviceTarget,
478 type: Schema.Literal("sendPush"),
479 appId: TrimmedNonEmptyString,
480 payload: Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.Unknown)]),
481 }),
482]);
483export type DeviceActionInput = typeof DeviceActionInput.Type;
484export type DeviceActionType = DeviceActionInput["type"];
485
486export const DeviceDetailInput = Schema.Struct(DeviceTarget);
487export type DeviceDetailInput = typeof DeviceDetailInput.Type;
488
489export class DeviceHostUnavailableError extends Schema.TaggedError<DeviceHostUnavailableError>()(
490 "DeviceHostUnavailableError",
491 {
492 hostId: DeviceHostId,
493 /** The host's name in Settings, which the message shows instead of its id. */
494 hostLabel: Schema.optional(Schema.String),
495 reason: Schema.String,
496 cause: Schema.optional(Schema.Defect()),
497 },
498) {
499 override get message(): string {
500 return `${this.hostLabel ?? `Device host ${this.hostId}`} is unavailable: ${this.reason}`;
501 }
502}
503
504export class DevicePlatformUnavailableError extends Schema.TaggedError<DevicePlatformUnavailableError>()(
505 "DevicePlatformUnavailableError",
506 {
507 hostId: DeviceHostId,
508 platform: DevicePlatform,
509 reason: Schema.String,
510 },
511) {
512 override get message(): string {
513 return `${this.platform} devices are unavailable on host ${this.hostId}: ${this.reason}`;
514 }
515}
516
517export class DeviceNotFoundError extends Schema.TaggedError<DeviceNotFoundError>()(
518 "DeviceNotFoundError",
519 {
520 hostId: DeviceHostId,
521 deviceId: DeviceId,
522 },
523) {
524 override get message(): string {
525 return `Device ${this.deviceId} was not found on host ${this.hostId}.`;
526 }
527}
528
529export class DeviceBootError extends Schema.TaggedError<DeviceBootError>()("DeviceBootError", {
530 hostId: DeviceHostId,
531 deviceId: DeviceId,
532 reason: Schema.Literals(["disk_space", "timeout", "launch_failed"]),
533 diagnostics: Schema.optional(Schema.String.check(Schema.isMaxLength(2_000))),
534 cause: Schema.Defect(),
535}) {
536 override get message(): string {
537 const explanation = {
538 disk_space: "There is not enough free disk space on its device host.",
539 timeout: "The device did not become ready in time.",
540 launch_failed: "The simulator or emulator could not start.",
541 }[this.reason];
542 const summary = `Device ${this.deviceId} failed to boot: ${explanation}`;
543 return this.diagnostics
544 ? `${summary}\n\n${this.diagnostics}`
545 : `${summary} The device host sent no details. Try again or open another device; if it keeps failing, check the device on that host.`;
546 }
547}
548
549export class DeviceOperationError extends Schema.TaggedError<DeviceOperationError>()(
550 "DeviceOperationError",
551 {
552 operation: Schema.String,
553 reason: Schema.Literals([
554 "command_failed",
555 "request_failed",
556 "invalid_payload",
557 "settings_failed",
558 "hub_rejected",
559 ]),
560 exitCode: Schema.optional(Schema.Number),
561 cause: Schema.Defect(),
562 },
563) {
564 override get message(): string {
565 const explanation = {
566 command_failed: `The device command failed${this.exitCode === undefined ? "" : ` (exit code ${this.exitCode})`}.`,
567 request_failed: "Could not communicate with device support. Try refreshing devices.",
568 invalid_payload: "The device request could not be encoded.",
569 settings_failed: "Could not read or save device settings.",
570 hub_rejected: "The device hub could not complete the request.",
571 }[this.reason];
572 return `Device ${this.operation} failed: ${explanation}`;
573 }
574}
575
576export class DeviceActionUnavailableError extends Schema.TaggedError<DeviceActionUnavailableError>()(
577 "DeviceActionUnavailableError",
578 {
579 operation: Schema.String,
580 platform: DevicePlatform,
581 reason: Schema.Literals(["unsupported", "helper_missing"]),
582 },
583) {
584 override get message(): string {
585 return this.reason === "helper_missing"
586 ? `Device ${this.operation} requires a helper missing from this install. Set up device support again.`
587 : `Device ${this.operation} is not supported on ${this.platform}.`;
588 }
589}
590
591export const DeviceError = Schema.Union([
592 DeviceHostUnavailableError,
593 DevicePlatformUnavailableError,
594 DeviceNotFoundError,
595 DeviceBootError,
596 DeviceOperationError,
597 DeviceActionUnavailableError,
598]);
599export type DeviceError = typeof DeviceError.Type;
600
601export const DeviceToolListResult = Schema.Struct({
602 hostStatuses: DeviceHostStatuses,
603 hosts: Schema.Array(DeviceHostSummary),
604 devices: Schema.Array(DeviceSummary),
605 open: Schema.Array(Schema.Struct({ hostId: DeviceHostId, deviceId: DeviceId })),
606});
607export type DeviceToolListResult = typeof DeviceToolListResult.Type;
608
609export const DeviceToolOpenInput = Schema.Struct({
610 deviceId: Schema.optional(
611 DeviceId.annotate({
612 description: "Device id from `device_list`. Default: the booted or last used device.",
613 }),
614 ),
615 platform: Schema.optional(
616 DevicePlatform.annotate({
617 description: "Needed with no `deviceId` when both platforms exist.",
618 }),
619 ),
620 hostId: Schema.optional(
621 DeviceHostId.annotate({ description: "Host from `device_list`. Default local." }),
622 ),
623});
624export type DeviceToolOpenInput = typeof DeviceToolOpenInput.Type;
625
626export const DeviceToolOpenResult = Schema.Struct({
627 device: DeviceSummary,
628 agentDevice: Schema.Struct({
629 command: Schema.String,
630 targetArgs: Schema.Array(Schema.String),
631 session: Schema.String,
632 }),
633 quickStart: Schema.String,
634});
635export type DeviceToolOpenResult = typeof DeviceToolOpenResult.Type;
636
637export const DeviceToolTargetInput = Schema.Struct({
638 deviceId: Schema.optional(
639 DeviceId.annotate({
640 description: "Device. Default: the last one opened here.",
641 }),
642 ),
643 hostId: Schema.optional(DeviceHostId),
644});
645export type DeviceToolTargetInput = typeof DeviceToolTargetInput.Type;
646
647export const DeviceToolScreenshotResult = Schema.Struct({
648 device: DeviceSummary,
649 screenshot: Schema.Struct({
650 mimeType: Schema.Literal("image/png"),
651 data: Schema.String,
652 width: Schema.Int,
653 height: Schema.Int,
654 }),
655});
656export type DeviceToolScreenshotResult = typeof DeviceToolScreenshotResult.Type;
657
658export const DeviceToolCloseInput = Schema.Struct({
659 deviceId: Schema.optional(
660 DeviceId.annotate({
661 description: "Device to close. None: close all here.",
662 }),
663 ),
664 hostId: Schema.optional(DeviceHostId),
665 shutdown: Schema.optional(
666 Schema.Boolean.annotate({
667 description: "Also turn it off. Default false.",
668 }),
669 ),
670});
671export type DeviceToolCloseInput = typeof DeviceToolCloseInput.Type;
672
673export class DeviceToolUnavailableError extends Schema.TaggedError<DeviceToolUnavailableError>()(
674 "DeviceToolUnavailableError",
675 {
676 reason: Schema.String,
677 cause: Schema.optional(Schema.Defect()),
678 },
679) {
680 override get message(): string {
681 return this.reason;
682 }
683}
684
685export const DeviceToolError = Schema.Union([
686 DeviceToolUnavailableError,
687 DeviceHostUnavailableError,
688 DevicePlatformUnavailableError,
689 DeviceNotFoundError,
690 DeviceBootError,
691 DeviceOperationError,
692 DeviceActionUnavailableError,
693]);
694export type DeviceToolError = typeof DeviceToolError.Type;
695
696export function deviceToolInstallMessage(name: string, tool: DeviceToolVersion | undefined) {
697 if (!tool) return `Installing ${name}…`;
698 const previous =
699 tool.runningVersion ??
700 [...tool.installedVersions].sort((a, b) => a.localeCompare(b, "en", { numeric: true })).at(-1);
701 return previous && !tool.installedVersions.includes(tool.requiredVersion)
702 ? `Updating ${name} from ${previous} to ${tool.requiredVersion}…`
703 : `Installing ${name} ${tool.requiredVersion}…`;
704}