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