Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

device.ts

529 lines16.9 KB

1import { Schema } from "effect";
2​
3import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4​
5export const DevicePlatform = Schema.Literals(["ios", "android"]);
6export type DevicePlatform = typeof DevicePlatform.Type;
7​
8export const DeviceHostId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
9export type DeviceHostId = typeof DeviceHostId.Type;
10​
11export const LOCAL_DEVICE_HOST_ID = "local" as DeviceHostId;
12​
13export const SshDeviceHostConfig = Schema.Struct({
14 id: DeviceHostId.check(
15 Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/),
16 Schema.makeFilter((id) => id !== "local" || "The local host id is reserved."),
17 ),
18 label: TrimmedNonEmptyString,
19 target: TrimmedNonEmptyString.check(Schema.isPattern(/^[^\s-][^\s]*$/)),
20 identityFile: Schema.optional(TrimmedNonEmptyString),
21 port: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
22});
23export type SshDeviceHostConfig = typeof SshDeviceHostConfig.Type;
24​
25export const SshDeviceHostConfigs = Schema.Array(SshDeviceHostConfig).check(
26 Schema.makeFilter(
27 (hosts) =>
28 new Set(hosts.map((host) => host.id)).size === hosts.length ||
29 "Device host ids must be unique.",
30 ),
31);
32​
33export const DeviceId = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
34export type DeviceId = typeof DeviceId.Type;
35​
36export const DeviceSummary = Schema.Struct({
37 hostId: DeviceHostId,
38 id: DeviceId,
39 platform: DevicePlatform,
40 name: TrimmedNonEmptyString,
41 version: Schema.String,
42 booted: Schema.Boolean,
43 physical: Schema.Boolean,
44});
45export type DeviceSummary = typeof DeviceSummary.Type;
46​
47export const DevicePlatformAvailability = Schema.Struct({
48 platform: DevicePlatform,
49 available: Schema.Boolean,
50 reason: Schema.optional(Schema.String),
51});
52export type DevicePlatformAvailability = typeof DevicePlatformAvailability.Type;
53​
54export const DeviceToolVersion = Schema.Struct({
55 requiredVersion: Schema.String,
56 installedVersions: Schema.Array(Schema.String),
57 runningVersion: Schema.NullOr(Schema.String),
58});
59export type DeviceToolVersion = typeof DeviceToolVersion.Type;
60​
61export const DeviceToolVersions = Schema.Struct({
62 hub: DeviceToolVersion,
63 agent: DeviceToolVersion,
64});
65export type DeviceToolVersions = typeof DeviceToolVersions.Type;
66​
67export const DeviceHostSummary = Schema.Struct({
68 id: DeviceHostId,
69 kind: Schema.Literals(["local", "ssh"]),
70 label: TrimmedNonEmptyString,
71 platforms: Schema.Array(DevicePlatformAvailability),
72 tools: Schema.optional(DeviceToolVersions),
73 toolInspectionError: Schema.optional(Schema.String),
74 hubInstalled: Schema.Boolean,
75 agentDeviceInstalled: Schema.Boolean,
76});
77export type DeviceHostSummary = typeof DeviceHostSummary.Type;
78​
79export const DeviceHostStatus = Schema.Literals([
80 "disabled",
81 "idle",
82 "installing",
83 "starting",
84 "ready",
85 "failed",
86]);
87export type DeviceHostStatus = typeof DeviceHostStatus.Type;
88​
89export const DeviceSession = Schema.Struct({
90 threadId: ThreadId,
91 hostId: DeviceHostId,
92 deviceId: DeviceId,
93 platform: DevicePlatform,
94 openedAt: Schema.String,
95});
96export type DeviceSession = typeof DeviceSession.Type;
97​
98export const DeviceServiceState = Schema.Struct({
99 supportsHostRetry: Schema.optional(Schema.Boolean),
100 supportsToolUpdate: Schema.optional(Schema.Boolean),
101 supportsToolInspection: Schema.optional(Schema.Boolean),
102 hosts: Schema.Array(DeviceHostSummary),
103 hostStatus: DeviceHostStatus,
104 hostStatusDetail: Schema.optional(Schema.String),
105 hostStatuses: Schema.Record(
106 DeviceHostId,
107 Schema.Struct({
108 status: DeviceHostStatus,
109 detail: Schema.optional(Schema.String),
110 }),
111 ),
112 devices: Schema.Array(DeviceSummary),
113 sessions: Schema.Array(DeviceSession),
114 bootingDevices: Schema.optional(
115 Schema.Array(Schema.Struct({ ...DeviceSummary.fields, threadId: ThreadId })),
116 ),
117 onboardingCompleted: Schema.Boolean,
118 agentAccessEnabled: Schema.Boolean,
119 hubBasePath: Schema.String,
120 revision: Schema.Int,
121});
122export type DeviceServiceState = typeof DeviceServiceState.Type;
123​
124export const DeviceListInput = Schema.Struct({
125 updateTool: Schema.optional(Schema.Literals(["hub", "agent"])),
126 inspectOnly: Schema.optional(Schema.Boolean),
127 retryHostId: Schema.optional(DeviceHostId),
128});
129export type DeviceListInput = typeof DeviceListInput.Type;
130​
131export const DeviceConfigureInput = Schema.Struct({
132 enabled: Schema.optional(Schema.Boolean),
133 agentAccessEnabled: Schema.optional(Schema.Boolean),
134 onboardingCompleted: Schema.optional(Schema.Boolean),
135});
136export type DeviceConfigureInput = typeof DeviceConfigureInput.Type;
137​
138export const DeviceOpenInput = Schema.Struct({
139 threadId: ThreadId,
140 hostId: Schema.optional(DeviceHostId),
141 deviceId: DeviceId,
142 platform: DevicePlatform,
143 /** Boot the simulator or emulator when it is not running. Defaults to true. */
144 boot: Schema.optional(Schema.Boolean),
145});
146export type DeviceOpenInput = typeof DeviceOpenInput.Type;
147​
148export const DeviceCloseInput = Schema.Struct({
149 hostId: Schema.optional(DeviceHostId),
150 threadId: ThreadId,
151 /** Omit to close every device session for the thread. */
152 deviceId: Schema.optional(DeviceId),
153 /** Also shut the simulator or emulator down. Defaults to false. */
154 shutdown: Schema.optional(Schema.Boolean),
155});
156export type DeviceCloseInput = typeof DeviceCloseInput.Type;
157​
158export const DeviceShutdownInput = Schema.Struct({
159 hostId: Schema.optional(DeviceHostId),
160 deviceId: DeviceId,
161 platform: DevicePlatform,
162});
163export type DeviceShutdownInput = typeof DeviceShutdownInput.Type;
164​
165export const DeviceAppearance = Schema.Literals(["light", "dark"]);
166export type DeviceAppearance = typeof DeviceAppearance.Type;
167​
168export const DeviceTextSize = Schema.Literals(["small", "default", "large", "extra-large"]);
169export type DeviceTextSize = typeof DeviceTextSize.Type;
170​
171export const DeviceColorFilter = Schema.Literals([
172 "none",
173 "grayscale",
174 "red-green",
175 "green-red",
176 "blue-yellow",
177]);
178export type DeviceColorFilter = typeof DeviceColorFilter.Type;
179​
180export const DeviceOrientation = Schema.Literals([
181 "portrait",
182 "landscape_left",
183 "portrait_upside_down",
184 "landscape_right",
185]);
186export type DeviceOrientation = typeof DeviceOrientation.Type;
187​
188export const DeviceSettings = Schema.Struct({
189 appearance: Schema.optional(DeviceAppearance),
190 textSize: Schema.optional(DeviceTextSize),
191 reduceMotion: Schema.optional(Schema.Boolean),
192 increaseContrast: Schema.optional(Schema.Boolean),
193 reduceTransparency: Schema.optional(Schema.Boolean),
194 showBorders: Schema.optional(Schema.Boolean),
195 voiceOver: Schema.optional(Schema.Boolean),
196 liquidGlass: Schema.optional(Schema.Literals(["clear", "tinted"])),
197 colorFilter: Schema.optional(DeviceColorFilter),
198 networkEnabled: Schema.optional(Schema.Boolean),
199 location: Schema.optional(
200 Schema.NullOr(Schema.Struct({ latitude: Schema.Number, longitude: Schema.Number })),
201 ),
202});
203export type DeviceSettings = typeof DeviceSettings.Type;
204​
205export const DeviceForegroundApp = Schema.Struct({
206 id: Schema.String,
207 name: Schema.optional(Schema.String),
208 version: Schema.optional(Schema.String),
209});
210export type DeviceForegroundApp = typeof DeviceForegroundApp.Type;
211​
212export const DeviceDetail = Schema.Struct({
213 hostId: DeviceHostId,
214 deviceId: DeviceId,
215 settings: DeviceSettings,
216 foregroundApp: Schema.NullOr(DeviceForegroundApp),
217 readAt: Schema.String,
218});
219export type DeviceDetail = typeof DeviceDetail.Type;
220​
221export const DevicePermission = Schema.Literals([
222 "camera",
223 "microphone",
224 "photos",
225 "contacts",
226 "calendar",
227 "reminders",
228 "location",
229 "notifications",
230 "motion",
231 "media-library",
232 "faceid",
233]);
234export type DevicePermission = typeof DevicePermission.Type;
235​
236const DeviceTarget = {
237 hostId: Schema.optional(DeviceHostId),
238 deviceId: DeviceId,
239};
240​
241export const DeviceActionInput = Schema.Union([
242 Schema.Struct({
243 ...DeviceTarget,
244 type: Schema.Literal("setAppearance"),
245 value: DeviceAppearance,
246 }),
247 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("setTextSize"), value: DeviceTextSize }),
248 Schema.Struct({
249 ...DeviceTarget,
250 type: Schema.Literal("setToggle"),
251 setting: Schema.Literals([
252 "reduceMotion",
253 "increaseContrast",
254 "reduceTransparency",
255 "showBorders",
256 "voiceOver",
257 "networkEnabled",
258 ]),
259 value: Schema.Boolean,
260 }),
261 Schema.Struct({
262 ...DeviceTarget,
263 type: Schema.Literal("setLiquidGlass"),
264 value: Schema.Literals(["clear", "tinted"]),
265 }),
266 Schema.Struct({
267 ...DeviceTarget,
268 type: Schema.Literal("setColorFilter"),
269 value: DeviceColorFilter,
270 }),
271 Schema.Struct({
272 ...DeviceTarget,
273 type: Schema.Literal("setOrientation"),
274 value: DeviceOrientation,
275 }),
276 Schema.Struct({
277 ...DeviceTarget,
278 type: Schema.Literal("setLocation"),
279 latitude: Schema.Number.check(Schema.isBetween({ minimum: -90, maximum: 90 })),
280 longitude: Schema.Number.check(Schema.isBetween({ minimum: -180, maximum: 180 })),
281 }),
282 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("clearLocation") }),
283 Schema.Struct({
284 ...DeviceTarget,
285 type: Schema.Literal("setPermission"),
286 appId: TrimmedNonEmptyString,
287 permission: DevicePermission,
288 decision: Schema.Literals(["grant", "revoke", "reset"]),
289 }),
290 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("openUrl"), url: TrimmedNonEmptyString }),
291 Schema.Struct({
292 ...DeviceTarget,
293 type: Schema.Literal("launchApp"),
294 appId: TrimmedNonEmptyString,
295 }),
296 Schema.Struct({
297 ...DeviceTarget,
298 type: Schema.Literal("terminateApp"),
299 appId: TrimmedNonEmptyString,
300 }),
301 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("shake") }),
302 Schema.Struct({
303 ...DeviceTarget,
304 type: Schema.Literal("sendPush"),
305 appId: TrimmedNonEmptyString,
306 payload: Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.Unknown)]),
307 }),
308]);
309export type DeviceActionInput = typeof DeviceActionInput.Type;
310export type DeviceActionType = DeviceActionInput["type"];
311​
312export const DeviceDetailInput = Schema.Struct(DeviceTarget);
313export type DeviceDetailInput = typeof DeviceDetailInput.Type;
314​
315export class DeviceHostUnavailableError extends Schema.TaggedError<DeviceHostUnavailableError>()(
316 "DeviceHostUnavailableError",
317 {
318 hostId: DeviceHostId,
319 reason: Schema.String,
320 cause: Schema.optional(Schema.Defect()),
321 },
322) {
323 override get message(): string {
324 return `Device host ${this.hostId} is unavailable: ${this.reason}`;
325 }
327​
328export class DevicePlatformUnavailableError extends Schema.TaggedError<DevicePlatformUnavailableError>()(
329 "DevicePlatformUnavailableError",
330 {
331 hostId: DeviceHostId,
332 platform: DevicePlatform,
333 reason: Schema.String,
334 },
335) {
336 override get message(): string {
337 return `${this.platform} devices are unavailable on host ${this.hostId}: ${this.reason}`;
338 }
340​
341export class DeviceNotFoundError extends Schema.TaggedError<DeviceNotFoundError>()(
342 "DeviceNotFoundError",
343 {
344 hostId: DeviceHostId,
345 deviceId: DeviceId,
346 },
347) {
348 override get message(): string {
349 return `Device ${this.deviceId} was not found on host ${this.hostId}.`;
350 }
352​
353export class DeviceBootError extends Schema.TaggedError<DeviceBootError>()("DeviceBootError", {
354 hostId: DeviceHostId,
355 deviceId: DeviceId,
356 reason: Schema.Literals(["disk_space", "timeout", "launch_failed"]),
357 cause: Schema.Defect(),
358}) {
359 override get message(): string {
360 const explanation = {
361 disk_space: "There is not enough free disk space on the environment server.",
362 timeout: "The device did not become ready in time.",
363 launch_failed:
364 "The simulator or emulator could not start. Check its configuration on the environment server.",
365 }[this.reason];
366 return `Device ${this.deviceId} failed to boot: ${explanation}`;
367 }
369​
370export class DeviceOperationError extends Schema.TaggedError<DeviceOperationError>()(
371 "DeviceOperationError",
372 {
373 operation: Schema.String,
374 reason: Schema.Literals([
375 "command_failed",
376 "request_failed",
377 "invalid_payload",
378 "settings_failed",
379 "hub_rejected",
380 ]),
381 exitCode: Schema.optional(Schema.Number),
382 cause: Schema.Defect(),
383 },
384) {
385 override get message(): string {
386 const explanation = {
387 command_failed: `The device command failed${this.exitCode === undefined ? "" : ` (exit code ${this.exitCode})`}.`,
388 request_failed: "Could not communicate with device support. Try refreshing devices.",
389 invalid_payload: "The device request could not be encoded.",
390 settings_failed: "Could not read or save device settings.",
391 hub_rejected: "The device hub could not complete the request.",
392 }[this.reason];
393 return `Device ${this.operation} failed: ${explanation}`;
394 }
396​
397export class DeviceActionUnavailableError extends Schema.TaggedError<DeviceActionUnavailableError>()(
398 "DeviceActionUnavailableError",
399 {
400 operation: Schema.String,
401 platform: DevicePlatform,
402 reason: Schema.Literals(["unsupported", "helper_missing"]),
403 },
404) {
405 override get message(): string {
406 return this.reason === "helper_missing"
407 ? `Device ${this.operation} requires a helper missing from this install. Set up device support again.`
408 : `Device ${this.operation} is not supported on ${this.platform}.`;
409 }
411​
412export const DeviceError = Schema.Union([
413 DeviceHostUnavailableError,
414 DevicePlatformUnavailableError,
415 DeviceNotFoundError,
416 DeviceBootError,
417 DeviceOperationError,
418 DeviceActionUnavailableError,
419]);
420export type DeviceError = typeof DeviceError.Type;
421​
422export const DeviceToolListResult = Schema.Struct({
423 hostStatuses: DeviceServiceState.fields.hostStatuses,
424 hosts: Schema.Array(DeviceHostSummary),
425 devices: Schema.Array(DeviceSummary),
426 open: Schema.Array(Schema.Struct({ hostId: DeviceHostId, deviceId: DeviceId })),
427});
428export type DeviceToolListResult = typeof DeviceToolListResult.Type;
429​
430export const DeviceToolOpenInput = Schema.Struct({
431 deviceId: Schema.optional(
432 DeviceId.annotate({
433 description:
434 "Simulator udid or emulator serial from device_list. Omit to use the booted device for the platform, or the most recently used one.",
435 }),
436 ),
437 platform: Schema.optional(
438 DevicePlatform.annotate({
439 description: "Required when deviceId is omitted and both platforms are available.",
440 }),
441 ),
442 hostId: Schema.optional(
443 DeviceHostId.annotate({ description: "Device host from device_list. Defaults to local." }),
444 ),
445}).annotate({
446 description:
447 "Boots the device if needed, starts its live stream, and opens the Device panel so the user can watch. Returns how to drive it with the agent-device CLI.",
448});
449export type DeviceToolOpenInput = typeof DeviceToolOpenInput.Type;
450​
451export const DeviceToolOpenResult = Schema.Struct({
452 device: DeviceSummary,
453 agentDevice: Schema.Struct({
454 command: Schema.String,
455 targetArgs: Schema.Array(Schema.String),
456 }),
457 quickStart: Schema.String,
458});
459export type DeviceToolOpenResult = typeof DeviceToolOpenResult.Type;
460​
461export const DeviceToolTargetInput = Schema.Struct({
462 deviceId: Schema.optional(
463 DeviceId.annotate({
464 description:
465 "Device from device_list. Omit to use the device most recently opened in this thread.",
466 }),
467 ),
468 hostId: Schema.optional(DeviceHostId),
469});
470export type DeviceToolTargetInput = typeof DeviceToolTargetInput.Type;
471​
472export const DeviceToolScreenshotResult = Schema.Struct({
473 device: DeviceSummary,
474 screenshot: Schema.Struct({
475 mimeType: Schema.Literal("image/png"),
476 data: Schema.String,
477 width: Schema.Int,
478 height: Schema.Int,
479 }),
480});
481export type DeviceToolScreenshotResult = typeof DeviceToolScreenshotResult.Type;
482​
483export const DeviceToolCloseInput = Schema.Struct({
484 deviceId: Schema.optional(
485 DeviceId.annotate({
486 description: "Device to close. Omit to close every device in this thread.",
487 }),
488 ),
489 hostId: Schema.optional(DeviceHostId),
490 shutdown: Schema.optional(
491 Schema.Boolean.annotate({
492 description: "Also power the simulator or emulator off. Defaults to false.",
493 }),
494 ),
495});
496export type DeviceToolCloseInput = typeof DeviceToolCloseInput.Type;
497​
498export class DeviceToolUnavailableError extends Schema.TaggedError<DeviceToolUnavailableError>()(
499 "DeviceToolUnavailableError",
500 {
501 reason: Schema.String,
502 cause: Schema.optional(Schema.Defect()),
503 },
504) {
505 override get message(): string {
506 return this.reason;
507 }
509​
510export const DeviceToolError = Schema.Union([
511 DeviceToolUnavailableError,
512 DeviceHostUnavailableError,
513 DevicePlatformUnavailableError,
514 DeviceNotFoundError,
515 DeviceBootError,
516 DeviceOperationError,
517 DeviceActionUnavailableError,
518]);
519export type DeviceToolError = typeof DeviceToolError.Type;
520​
521export function deviceToolInstallMessage(name: string, tool: DeviceToolVersion | undefined) {
522 if (!tool) return `Installing ${name}…`;
523 const previous =
524 tool.runningVersion ??
525 [...tool.installedVersions].sort((a, b) => a.localeCompare(b, "en", { numeric: true })).at(-1);
526 return previous && !tool.installedVersions.includes(tool.requiredVersion)
527 ? `Updating ${name} from ${previous} to ${tool.requiredVersion}…`
528 : `Installing ${name} ${tool.requiredVersion}…`;