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
130export const DeviceSimlockIdentityInput = Schema.Struct({
131 /** Without one, the gateway this machine's agent-device points at. */
132 gatewayUrl: Schema.optional(TrimmedString),
133 /** A saved Simlock host whose stored token is checked when no new token is given. */
134 hostId: Schema.optional(DeviceHostId),
135 agentToken: Schema.optional(TrimmedString),
136});
137export type DeviceSimlockIdentityInput = typeof DeviceSimlockIdentityInput.Type;
138
139export const DeviceSimlockIdentity = Schema.Struct({
140 gatewayUrl: Schema.String,
141 /** The label the gateway gave the token. */
142 signedInAs: Schema.String,
143 /** `env`: this machine's AGENT_DEVICE_DAEMON_AUTH_TOKEN, used because it targets this gateway. */
144 tokenSource: Schema.Literals(["entered", "settings", "env"]),
145});
146export type DeviceSimlockIdentity = typeof DeviceSimlockIdentity.Type;
147
148export class DeviceSimlockIdentityError extends Schema.TaggedError<DeviceSimlockIdentityError>()(
149 "DeviceSimlockIdentityError",
150 { reason: Schema.String },
151) {
152 override get message(): string {
153 return this.reason;
154 }
155}
156
157/** Checking an Expo credential failed; no device host is involved yet. */
158export class DeviceEasAccountError extends Schema.TaggedError<DeviceEasAccountError>()(
159 "DeviceEasAccountError",
160 // No cause: this error reaches the browser, and the reason already says what Expo answered.
161 { reason: Schema.String },
162) {
163 override get message(): string {
164 return this.reason;
165 }
166}
167
168export const DeviceId = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
169export type DeviceId = typeof DeviceId.Type;
170
171export const DeviceSummary = Schema.Struct({
172 hostId: DeviceHostId,
173 id: DeviceId,
174 platform: DevicePlatform,
175 name: TrimmedNonEmptyString,
176 version: Schema.String,
177 booted: Schema.Boolean,
178 physical: Schema.Boolean,
179});
180export type DeviceSummary = typeof DeviceSummary.Type;
181
182export const DevicePlatformAvailability = Schema.Struct({
183 platform: DevicePlatform,
184 available: Schema.Boolean,
185 reason: Schema.optional(Schema.String),
186});
187export type DevicePlatformAvailability = typeof DevicePlatformAvailability.Type;
188
189export const DeviceToolVersion = Schema.Struct({
190 requiredVersion: Schema.String,
191 installedVersions: Schema.Array(Schema.String),
192 runningVersion: Schema.NullOr(Schema.String),
193});
194export type DeviceToolVersion = typeof DeviceToolVersion.Type;
195
196export const DeviceToolVersions = Schema.Struct({
197 hub: DeviceToolVersion,
198 agent: DeviceToolVersion,
199});
200export type DeviceToolVersions = typeof DeviceToolVersions.Type;
201
202const deviceHostSummaryFields = {
203 id: DeviceHostId,
204 label: TrimmedNonEmptyString,
205 platforms: Schema.Array(DevicePlatformAvailability),
206 tools: Schema.optional(DeviceToolVersions),
207 toolInspectionError: Schema.optional(Schema.String),
208 hubInstalled: Schema.Boolean,
209 agentDeviceInstalled: Schema.Boolean,
210};
211const MachineDeviceHostSummary = Schema.Struct({
212 ...deviceHostSummaryFields,
213 kind: Schema.Literals(["local", "ssh"]),
214});
215const EasDeviceHostSummary = Schema.Struct({
216 ...deviceHostSummaryFields,
217 kind: Schema.Literal("eas"),
218});
219const SimlockDeviceHostSummary = Schema.Struct({
220 ...deviceHostSummaryFields,
221 kind: Schema.Literal("simlock"),
222});
223export const DeviceHostSummary = Schema.Union([
224 MachineDeviceHostSummary,
225 EasDeviceHostSummary,
226 SimlockDeviceHostSummary,
227]);
228export type DeviceHostSummary = typeof DeviceHostSummary.Type;
229
230export const DeviceHostStatus = Schema.Literals([
231 "disabled",
232 "idle",
233 "installing",
234 "starting",
235 "ready",
236 "failed",
237]);
238export type DeviceHostStatus = typeof DeviceHostStatus.Type;
239
240export const DeviceSession = Schema.Struct({
241 threadId: ThreadId,
242 hostId: DeviceHostId,
243 deviceId: DeviceId,
244 platform: DevicePlatform,
245 openedAt: Schema.String,
246});
247export type DeviceSession = typeof DeviceSession.Type;
248
249export const DeviceHostStatuses = Schema.Record(
250 DeviceHostId,
251 Schema.Struct({
252 status: DeviceHostStatus,
253 detail: Schema.optional(Schema.String),
254 androidDiscoveryIncomplete: Schema.optional(Schema.Boolean),
255 }),
256);
257
258const deviceServiceStateFields = {
259 supportsHostRetry: Schema.optional(Schema.Boolean),
260 supportsToolUpdate: Schema.optional(Schema.Boolean),
261 supportsToolInspection: Schema.optional(Schema.Boolean),
262 /** Servers from before EAS hosts ignore `easDeviceHosts`, so clients offer them only when set. */
263 supportsEasHosts: Schema.optional(Schema.Boolean),
264 /** Servers from before Simlock hosts ignore `simlockDeviceHosts`. */
265 supportsSimlockHosts: Schema.optional(Schema.Boolean),
266 hostStatus: DeviceHostStatus,
267 hostStatusDetail: Schema.optional(Schema.String),
268 hostStatuses: DeviceHostStatuses,
269 devices: Schema.Array(DeviceSummary),
270 sessions: Schema.Array(DeviceSession),
271 bootingDevices: Schema.optional(
272 Schema.Array(Schema.Struct({ ...DeviceSummary.fields, threadId: ThreadId })),
273 ),
274 onboardingCompleted: Schema.Boolean,
275 agentAccessEnabled: Schema.Boolean,
276 hubBasePath: Schema.String,
277 revision: Schema.Int,
278};
279
280/**
281 * EAS host summaries travel as `easHosts`: clients from before EAS hosts
282 * decode `hosts` with a `local | ssh` kind and would reject the whole state.
283 * Decoded, every host is in `hosts`.
284 */
285const DeviceServiceStateWire = Schema.Struct({
286 ...deviceServiceStateFields,
287 hosts: Schema.Array(MachineDeviceHostSummary),
288 easHosts: Schema.optional(Schema.Array(EasDeviceHostSummary)),
289 simlockHosts: Schema.optional(Schema.Array(SimlockDeviceHostSummary)),
290});
291const DeviceServiceStateDecoded = Schema.Struct({
292 ...deviceServiceStateFields,
293 hosts: Schema.Array(DeviceHostSummary),
294});
295
296export const DeviceServiceState = DeviceServiceStateWire.pipe(
297 Schema.decodeTo(
298 Schema.toType(DeviceServiceStateDecoded),
299 SchemaTransformation.transform<
300 typeof DeviceServiceStateDecoded.Type,
301 typeof DeviceServiceStateWire.Type
302 >({
303 decode: ({ easHosts, simlockHosts, ...state }) => ({
304 ...state,
305 hosts: [...state.hosts, ...(easHosts ?? []), ...(simlockHosts ?? [])],
306 }),
307 encode: (state) => ({
308 ...state,
309 hosts: state.hosts.filter(
310 (host): host is typeof MachineDeviceHostSummary.Type =>
311 host.kind === "local" || host.kind === "ssh",
312 ),
313 easHosts: state.hosts.filter(
314 (host): host is typeof EasDeviceHostSummary.Type => host.kind === "eas",
315 ),
316 simlockHosts: state.hosts.filter(
317 (host): host is typeof SimlockDeviceHostSummary.Type => host.kind === "simlock",
318 ),
319 }),
320 }),
321 ),
322);
323export type DeviceServiceState = typeof DeviceServiceState.Type;
324
325export const DeviceListInput = Schema.Struct({
326 updateTool: Schema.optional(Schema.Literals(["hub", "agent"])),
327 inspectOnly: Schema.optional(Schema.Boolean),
328 retryHostId: Schema.optional(DeviceHostId),
329});
330export type DeviceListInput = typeof DeviceListInput.Type;
331
332export const DeviceConfigureInput = Schema.Struct({
333 enabled: Schema.optional(Schema.Boolean),
334 agentAccessEnabled: Schema.optional(Schema.Boolean),
335 onboardingCompleted: Schema.optional(Schema.Boolean),
336});
337export type DeviceConfigureInput = typeof DeviceConfigureInput.Type;
338
339export const DeviceOpenInput = Schema.Struct({
340 threadId: ThreadId,
341 hostId: Schema.optional(DeviceHostId),
342 deviceId: DeviceId,
343 platform: DevicePlatform,
344 /** Boot the simulator or emulator when it is not running. Defaults to true. */
345 boot: Schema.optional(Schema.Boolean),
346});
347export type DeviceOpenInput = typeof DeviceOpenInput.Type;
348
349export const DeviceCloseInput = Schema.Struct({
350 hostId: Schema.optional(DeviceHostId),
351 threadId: ThreadId,
352 /** Omit to close every device session for the thread. */
353 deviceId: Schema.optional(DeviceId),
354 /** Also shut the simulator or emulator down. Defaults to false. */
355 shutdown: Schema.optional(Schema.Boolean),
356});
357export type DeviceCloseInput = typeof DeviceCloseInput.Type;
358
359export const DeviceShutdownInput = Schema.Struct({
360 hostId: Schema.optional(DeviceHostId),
361 deviceId: DeviceId,
362 platform: DevicePlatform,
363});
364export type DeviceShutdownInput = typeof DeviceShutdownInput.Type;
365
366export const DeviceAppearance = Schema.Literals(["light", "dark"]);
367export type DeviceAppearance = typeof DeviceAppearance.Type;
368
369export const DeviceTextSize = Schema.Literals(["small", "default", "large", "extra-large"]);
370export type DeviceTextSize = typeof DeviceTextSize.Type;
371
372export const DeviceColorFilter = Schema.Literals([
373 "none",
374 "grayscale",
375 "red-green",
376 "green-red",
377 "blue-yellow",
378]);
379export type DeviceColorFilter = typeof DeviceColorFilter.Type;
380
381export const DeviceOrientation = Schema.Literals([
382 "portrait",
383 "landscape_left",
384 "portrait_upside_down",
385 "landscape_right",
386]);
387export type DeviceOrientation = typeof DeviceOrientation.Type;
388
389export const DeviceSettings = Schema.Struct({
390 appearance: Schema.optional(DeviceAppearance),
391 textSize: Schema.optional(DeviceTextSize),
392 reduceMotion: Schema.optional(Schema.Boolean),
393 increaseContrast: Schema.optional(Schema.Boolean),
394 reduceTransparency: Schema.optional(Schema.Boolean),
395 showBorders: Schema.optional(Schema.Boolean),
396 voiceOver: Schema.optional(Schema.Boolean),
397 liquidGlass: Schema.optional(Schema.Literals(["clear", "tinted"])),
398 colorFilter: Schema.optional(DeviceColorFilter),
399 networkEnabled: Schema.optional(Schema.Boolean),
400 location: Schema.optional(
401 Schema.NullOr(Schema.Struct({ latitude: Schema.Number, longitude: Schema.Number })),
402 ),
403});
404export type DeviceSettings = typeof DeviceSettings.Type;
405
406export const DeviceForegroundApp = Schema.Struct({
407 id: Schema.String,
408 name: Schema.optional(Schema.String),
409 version: Schema.optional(Schema.String),
410});
411export type DeviceForegroundApp = typeof DeviceForegroundApp.Type;
412
413export const DeviceDetail = Schema.Struct({
414 hostId: DeviceHostId,
415 deviceId: DeviceId,
416 settings: DeviceSettings,
417 foregroundApp: Schema.NullOr(DeviceForegroundApp),
418 readAt: Schema.String,
419});
420export type DeviceDetail = typeof DeviceDetail.Type;
421
422export const DevicePermission = Schema.Literals([
423 "camera",
424 "microphone",
425 "photos",
426 "contacts",
427 "calendar",
428 "reminders",
429 "location",
430 "notifications",
431 "motion",
432 "media-library",
433 "faceid",
434]);
435export type DevicePermission = typeof DevicePermission.Type;
436
437const DeviceTarget = {
438 hostId: Schema.optional(DeviceHostId),
439 deviceId: DeviceId,
440};
441
442export const DeviceActionInput = Schema.Union([
443 Schema.Struct({
444 ...DeviceTarget,
445 type: Schema.Literal("setAppearance"),
446 value: DeviceAppearance,
447 }),
448 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("setTextSize"), value: DeviceTextSize }),
449 Schema.Struct({
450 ...DeviceTarget,
451 type: Schema.Literal("setToggle"),
452 setting: Schema.Literals([
453 "reduceMotion",
454 "increaseContrast",
455 "reduceTransparency",
456 "showBorders",
457 "voiceOver",
458 "networkEnabled",
459 ]),
460 value: Schema.Boolean,
461 }),
462 Schema.Struct({
463 ...DeviceTarget,
464 type: Schema.Literal("setLiquidGlass"),
465 value: Schema.Literals(["clear", "tinted"]),
466 }),
467 Schema.Struct({
468 ...DeviceTarget,
469 type: Schema.Literal("setColorFilter"),
470 value: DeviceColorFilter,
471 }),
472 Schema.Struct({
473 ...DeviceTarget,
474 type: Schema.Literal("setOrientation"),
475 value: DeviceOrientation,
476 }),
477 Schema.Struct({
478 ...DeviceTarget,
479 type: Schema.Literal("setLocation"),
480 latitude: Schema.Number.check(Schema.isBetween({ minimum: -90, maximum: 90 })),
481 longitude: Schema.Number.check(Schema.isBetween({ minimum: -180, maximum: 180 })),
482 }),
483 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("clearLocation") }),
484 Schema.Struct({
485 ...DeviceTarget,
486 type: Schema.Literal("setPermission"),
487 appId: TrimmedNonEmptyString,
488 permission: DevicePermission,
489 decision: Schema.Literals(["grant", "revoke", "reset"]),
490 }),
491 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("openUrl"), url: TrimmedNonEmptyString }),
492 Schema.Struct({
493 ...DeviceTarget,
494 type: Schema.Literal("launchApp"),
495 appId: TrimmedNonEmptyString,
496 }),
497 Schema.Struct({
498 ...DeviceTarget,
499 type: Schema.Literal("terminateApp"),
500 appId: TrimmedNonEmptyString,
501 }),
502 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("shake") }),
503 Schema.Struct({
504 ...DeviceTarget,
505 type: Schema.Literal("sendPush"),
506 appId: TrimmedNonEmptyString,
507 payload: Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.Unknown)]),
508 }),
509]);
510export type DeviceActionInput = typeof DeviceActionInput.Type;
511export type DeviceActionType = DeviceActionInput["type"];
512
513export const DeviceDetailInput = Schema.Struct(DeviceTarget);
514export type DeviceDetailInput = typeof DeviceDetailInput.Type;
515
516export class DeviceHostUnavailableError extends Schema.TaggedError<DeviceHostUnavailableError>()(
517 "DeviceHostUnavailableError",
518 {
519 hostId: DeviceHostId,
520 /** The host's name in Settings, which the message shows instead of its id. */
521 hostLabel: Schema.optional(Schema.String),
522 reason: Schema.String,
523 cause: Schema.optional(Schema.Defect()),
524 },
525) {
526 override get message(): string {
527 return `${this.hostLabel ?? `Device host ${this.hostId}`} is unavailable: ${this.reason}`;
528 }
529}
530
531export class DevicePlatformUnavailableError extends Schema.TaggedError<DevicePlatformUnavailableError>()(
532 "DevicePlatformUnavailableError",
533 {
534 hostId: DeviceHostId,
535 platform: DevicePlatform,
536 reason: Schema.String,
537 },
538) {
539 override get message(): string {
540 return `${this.platform} devices are unavailable on host ${this.hostId}: ${this.reason}`;
541 }
542}
543
544export class DeviceNotFoundError extends Schema.TaggedError<DeviceNotFoundError>()(
545 "DeviceNotFoundError",
546 {
547 hostId: DeviceHostId,
548 deviceId: DeviceId,
549 },
550) {
551 override get message(): string {
552 return `Device ${this.deviceId} was not found on host ${this.hostId}.`;
553 }
554}
555
556export class DeviceBootError extends Schema.TaggedError<DeviceBootError>()("DeviceBootError", {
557 hostId: DeviceHostId,
558 deviceId: DeviceId,
559 reason: Schema.Literals(["disk_space", "timeout", "launch_failed"]),
560 diagnostics: Schema.optional(Schema.String.check(Schema.isMaxLength(2_000))),
561 cause: Schema.Defect(),
562}) {
563 override get message(): string {
564 const explanation = {
565 disk_space: "There is not enough free disk space on its device host.",
566 timeout: "The device did not become ready in time.",
567 launch_failed: "The simulator or emulator could not start.",
568 }[this.reason];
569 const summary = `Device ${this.deviceId} failed to boot: ${explanation}`;
570 return this.diagnostics
571 ? `${summary}\n\n${this.diagnostics}`
572 : `${summary} The device host sent no details. Try again or open another device; if it keeps failing, check the device on that host.`;
573 }
574}
575
576export class DeviceOperationError extends Schema.TaggedError<DeviceOperationError>()(
577 "DeviceOperationError",
578 {
579 operation: Schema.String,
580 reason: Schema.Literals([
581 "command_failed",
582 "request_failed",
583 "invalid_payload",
584 "settings_failed",
585 "hub_rejected",
586 ]),
587 exitCode: Schema.optional(Schema.Number),
588 cause: Schema.Defect(),
589 },
590) {
591 override get message(): string {
592 const explanation = {
593 command_failed: `The device command failed${this.exitCode === undefined ? "" : ` (exit code ${this.exitCode})`}.`,
594 request_failed: "Could not communicate with device support. Try refreshing devices.",
595 invalid_payload: "The device request could not be encoded.",
596 settings_failed: "Could not read or save device settings.",
597 hub_rejected: "The device hub could not complete the request.",
598 }[this.reason];
599 return `Device ${this.operation} failed: ${explanation}`;
600 }
601}
602
603export class DeviceActionUnavailableError extends Schema.TaggedError<DeviceActionUnavailableError>()(
604 "DeviceActionUnavailableError",
605 {
606 operation: Schema.String,
607 platform: DevicePlatform,
608 reason: Schema.Literals(["unsupported", "helper_missing"]),
609 },
610) {
611 override get message(): string {
612 return this.reason === "helper_missing"
613 ? `Device ${this.operation} requires a helper missing from this install. Set up device support again.`
614 : `Device ${this.operation} is not supported on ${this.platform}.`;
615 }
616}
617
618export const DeviceError = Schema.Union([
619 DeviceHostUnavailableError,
620 DevicePlatformUnavailableError,
621 DeviceNotFoundError,
622 DeviceBootError,
623 DeviceOperationError,
624 DeviceActionUnavailableError,
625]);
626export type DeviceError = typeof DeviceError.Type;
627
628export const DeviceToolListResult = Schema.Struct({
629 hostStatuses: DeviceHostStatuses,
630 hosts: Schema.Array(DeviceHostSummary),
631 devices: Schema.Array(DeviceSummary),
632 open: Schema.Array(Schema.Struct({ hostId: DeviceHostId, deviceId: DeviceId })),
633});
634export type DeviceToolListResult = typeof DeviceToolListResult.Type;
635
636export const DeviceToolOpenInput = Schema.Struct({
637 deviceId: Schema.optional(
638 DeviceId.annotate({
639 description: "Device id from `device_list`. Default: the booted or last used device.",
640 }),
641 ),
642 platform: Schema.optional(
643 DevicePlatform.annotate({
644 description: "Needed with no `deviceId` when both platforms exist.",
645 }),
646 ),
647 hostId: Schema.optional(
648 DeviceHostId.annotate({ description: "Host from `device_list`. Default local." }),
649 ),
650});
651export type DeviceToolOpenInput = typeof DeviceToolOpenInput.Type;
652
653export const DeviceToolOpenResult = Schema.Struct({
654 device: DeviceSummary,
655 agentDevice: Schema.Struct({
656 command: Schema.String,
657 targetArgs: Schema.Array(Schema.String),
658 session: Schema.String,
659 }),
660 quickStart: Schema.String,
661});
662export type DeviceToolOpenResult = typeof DeviceToolOpenResult.Type;
663
664export const DeviceToolTargetInput = Schema.Struct({
665 deviceId: Schema.optional(
666 DeviceId.annotate({
667 description: "Device. Default: the last one opened here.",
668 }),
669 ),
670 hostId: Schema.optional(DeviceHostId),
671});
672export type DeviceToolTargetInput = typeof DeviceToolTargetInput.Type;
673
674export const DeviceToolScreenshotResult = Schema.Struct({
675 device: DeviceSummary,
676 screenshot: Schema.Struct({
677 mimeType: Schema.Literal("image/png"),
678 data: Schema.String,
679 width: Schema.Int,
680 height: Schema.Int,
681 }),
682});
683export type DeviceToolScreenshotResult = typeof DeviceToolScreenshotResult.Type;
684
685export const DeviceToolCloseInput = Schema.Struct({
686 deviceId: Schema.optional(
687 DeviceId.annotate({
688 description: "Device to close. None: close all here.",
689 }),
690 ),
691 hostId: Schema.optional(DeviceHostId),
692 shutdown: Schema.optional(
693 Schema.Boolean.annotate({
694 description: "Also turn it off. Default false.",
695 }),
696 ),
697});
698export type DeviceToolCloseInput = typeof DeviceToolCloseInput.Type;
699
700export class DeviceToolUnavailableError extends Schema.TaggedError<DeviceToolUnavailableError>()(
701 "DeviceToolUnavailableError",
702 {
703 reason: Schema.String,
704 cause: Schema.optional(Schema.Defect()),
705 },
706) {
707 override get message(): string {
708 return this.reason;
709 }
710}
711
712export const DeviceToolError = Schema.Union([
713 DeviceToolUnavailableError,
714 DeviceHostUnavailableError,
715 DevicePlatformUnavailableError,
716 DeviceNotFoundError,
717 DeviceBootError,
718 DeviceOperationError,
719 DeviceActionUnavailableError,
720]);
721export type DeviceToolError = typeof DeviceToolError.Type;
722
723export function deviceToolInstallMessage(name: string, tool: DeviceToolVersion | undefined) {
724 if (!tool) return `Installing ${name}…`;
725 const previous =
726 tool.runningVersion ??
727 [...tool.installedVersions].sort((a, b) => a.localeCompare(b, "en", { numeric: true })).at(-1);
728 return previous && !tool.installedVersions.includes(tool.requiredVersion)
729 ? `Updating ${name} from ${previous} to ${tool.requiredVersion}…`
730 : `Installing ${name} ${tool.requiredVersion}…`;
731}