Open History to see the last commit
1import { DeviceToolVersions } from "../device/DeviceToolVersions";
2import { DeviceHostAvailability } from "../device/DeviceHostAvailability";
3import { useAtomValue } from "@effect/atom-react";
4import * as Option from "effect/Option";
5import { AsyncResult } from "effect/reactivity";
6import { AuthSettingsWriteScope } from "@t3tools/contracts";
7import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
8import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
9import { AppleIcon, AndroidIcon } from "../Icons";
10import { Spinner } from "../ui/spinner";
11import type { EnvironmentId, SshDeviceHostConfig } from "@t3tools/contracts";
12import { randomUUID } from "../../lib/utils";
13import { useState } from "react";
14import { deviceEnvironment } from "../../state/device";
15import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
16import { serverEnvironment } from "../../state/server";
17import { useAtomCommand } from "../../state/use-atom-command";
18import { Button, InlineButton } from "../ui/button";
19import {
20 CheckIcon,
21 ChevronDownIcon,
22 CircleIcon,
23 MoreVertical,
24 PlusIcon,
25 TriangleAlertIcon,
26} from "lucide-react";
27import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
28import { Menu, MenuTrigger, MenuPopup, MenuItem } from "../ui/menu";
29import { SettingsRow } from "./settingsLayout";
30
31import { useSettingsScope } from "./SettingsScopeContext";
32import { toastManager } from "../ui/toast";
33import {
34 groupDeviceHosts,
35 updateDeviceHosts,
36 type DeviceHostEnvironment,
37 type DeviceHostGroup,
38} from "./deviceHostsSettings.logic";
39import { FoldedSettingsSection } from "./FoldedSettingsSection";
40import { DeviceHostEditor } from "./DeviceHostEditor";
41import { useHostConnectionChecks } from "./useHostConnectionChecks";
42import { deviceHostConnectionKey } from "./deviceHostConnectionChecks";
43import { settingsScopeEnvironmentLabel, settingsScopeEnvironmentLabels } from "./settingsScopeAxis";
44import { DeviceHostDiagnostics } from "../device/DeviceSetup";
45
46export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null }) {
47 const { scope, environments, connectedEnvironments } = useSettingsScope();
48 const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
49 const projectScope = scope.kind === "project" || scope.kind === "checkout";
50 const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
51 const [editing, setEditing] = useState<SshDeviceHostConfig | null>(null);
52 const [originalHost, setOriginalHost] = useState<SshDeviceHostConfig | null>(null);
53 const [busy, setBusy] = useState(false);
54 const targets = environments.map((environment) => ({
55 environmentId: environment.environmentId,
56 label: settingsScopeEnvironmentLabel(environment, environments),
57 connected: environment.connection.phase === "connected",
58 }));
59 const { checks, testConnection } = useHostConnectionChecks(targets);
60 const hostEnvironments = connectedEnvironments.map((environment) => ({
61 environmentId: environment.environmentId,
62 label: environment.label,
63 labels: settingsScopeEnvironmentLabels(environment, connectedEnvironments),
64 hosts: environment.serverConfig?.settings.deviceHosts ?? [],
65 }));
66 const groupedHosts = groupDeviceHosts(hostEnvironments);
67 const save = async (host: SshDeviceHostConfig, remove = false, original = host) => {
68 if (!props.environmentId || projectScope) return;
69 setBusy(true);
70 const results = await Promise.allSettled(
71 environments.map(async (environment) => {
72 if (environment.connection.phase !== "connected" || !environment.serverConfig) {
73 throw new Error("Environment disconnected");
74 }
75 if (!readEnvironmentScope(environment.environmentId, AuthSettingsWriteScope)) {
76 throw new Error("This connection cannot change device settings.");
77 }
78 return update({
79 environmentId: environment.environmentId,
80 input: {
81 patch: {
82 deviceHosts: updateDeviceHosts(
83 environment.serverConfig.settings.deviceHosts,
84 host,
85 remove,
86 original,
87 ),
88 },
89 },
90 });
91 }),
92 );
93 setBusy(false);
94 const failed = environments.filter((_, index) => {
95 const result = results[index];
96 return result?.status !== "fulfilled" || result.value._tag === "Failure";
97 });
98 if (failed.length === 0) {
99 setEditing(null);
100 } else {
101 toastManager.add({
102 type: "error",
103 title: "Device hosts not saved on all environments",
104 description: `Could not update ${failed.map((environment) => environment.label).join(", ")}.`,
105 });
106 }
107 };
108 const listActions = {
109 busy: !canConfigure || projectScope || busy,
110 checks,
111 testConnection: async (host: SshDeviceHostConfig) => {
112 const results = await testConnection(host);
113 if (!results) return;
114 const failed = targets.filter((target) => results[target.environmentId]?.status === "failed");
115 toastManager.add({
116 type: failed.length ? "error" : "success",
117 title: failed.length
118 ? `${host.label}: ${failed.length} of ${targets.length} environments failed`
119 : `${host.label}: connection checks passed`,
120 description: failed.length
121 ? `Could not connect from ${failed.map((target) => target.label).join(", ")}.`
122 : "Connected or already available locally on each selected environment.",
123 });
124 return results;
125 },
126 onEdit: (host: SshDeviceHostConfig) => {
127 setOriginalHost(host);
128 setEditing(host);
129 },
130 onRemove: (host: SshDeviceHostConfig) => void save(host, true),
131 };
132 return (
133 <SettingsRow
134 id="device-hosts"
135 title="Device hosts"
136 serverScoped
137 settingKeys={["deviceHosts"]}
138 description="Add remote machines with simulator or emulator runtimes installed, and the selected environments will connect over SSH and set up device tools automatically."
139 control={
140 <Button
141 size="sm"
142 variant="outline"
143 disabled={
144 !canConfigure || projectScope || busy || !props.environmentId || editing !== null
145 }
146 onClick={() => {
147 setOriginalHost(null);
148 setEditing({ kind: "ssh", id: randomUUID(), label: "", target: "" });
149 }}
150 >
151 <PlusIcon className="size-3.5" /> Add host
152 </Button>
153 }
154 >
155 <div className="pt-3 pb-2">
156 {!props.environmentId ? (
157 <p className="text-sm text-muted-foreground">
158 Connect a selected environment to manage device hosts.
159 </p>
160 ) : (
161 <>
162 {hostEnvironments.length > 1 && groupedHosts === null ? (
163 <div className="space-y-2">
164 {hostEnvironments.map((environment) => (
165 <FoldedSettingsSection
166 key={environment.environmentId}
167 id={`device-hosts-${environment.environmentId}`}
168 title={
169 <>
170 <span className="block max-w-64 truncate">
171 {environment.labels.primary}
172 </span>
173 {environment.labels.secondary ? (
174 <span className="block max-w-64 truncate text-xs font-normal text-muted-foreground">
175 {environment.labels.secondary}
176 </span>
177 ) : null}
178 </>
179 }
180 summary={
181 summarizeLabels(environment.hosts.map((host) => host.label)) ||
182 "No device hosts"
183 }
184 >
185 <div className="px-3 sm:px-4 [&>div:first-child]:border-t-0">
186 <DeviceHostList environments={[environment]} {...listActions} />
187 </div>
188 </FoldedSettingsSection>
189 ))}
190 </div>
191 ) : (
192 <DeviceHostList
193 environments={hostEnvironments}
194 groups={groupedHosts ?? undefined}
195 compact={hostEnvironments.length > 1}
196 {...listActions}
197 />
198 )}
199 {editing ? (
200 <DeviceHostEditor
201 key={editing.id}
202 host={editing}
203 isNew={originalHost === null}
204 targets={targets}
205 busy={busy}
206 onSave={(host) => void save(host, false, originalHost ?? host)}
207 onClose={() => setEditing(null)}
208 />
209 ) : null}
210 </>
211 )}
212 </div>
213 </SettingsRow>
214 );
215}
216
217const deviceHostStatesAtom = environmentAtomList("web-device-host-states", (environmentId) =>
218 deviceEnvironment.state({ environmentId, input: {} }),
219);
220
221function DeviceHostList({
222 environments,
223 groups,
224 compact = false,
225 busy,
226 onEdit,
227 onRemove,
228 checks,
229 testConnection,
230}: {
231 environments: ReadonlyArray<DeviceHostEnvironment>;
232 groups?: ReadonlyArray<DeviceHostGroup> | undefined;
233 compact?: boolean;
234 busy: boolean;
235 onEdit: (host: SshDeviceHostConfig) => void;
236 onRemove: (host: SshDeviceHostConfig) => void;
237 checks: ReturnType<typeof useHostConnectionChecks>["checks"];
238 testConnection: ReturnType<typeof useHostConnectionChecks>["testConnection"];
239}) {
240 const { environments: scopeEnvironments } = useSettingsScope();
241 const environmentLabels = new Map(
242 scopeEnvironments.map((environment) => [
243 environment.environmentId,
244 settingsScopeEnvironmentLabels(environment, scopeEnvironments),
245 ]),
246 );
247 const environmentIds = environments.map(({ environmentId }) => environmentId);
248 const results = useAtomValue(deviceHostStatesAtom(environmentIdsKey(environmentIds)));
249 const states = new Map(
250 environmentIds.map(
251 (environmentId, index) =>
252 [environmentId, Option.getOrUndefined(AsyncResult.value(results[index]!))] as const,
253 ),
254 );
255 const retry = useAtomCommand(deviceEnvironment.list);
256 const [retrying, setRetrying] = useState<string | null>(null);
257 const retryHost = (environmentId: EnvironmentId, hostId: string, key = hostId) => {
258 setRetrying(key);
259 void retry({ environmentId, input: { retryHostId: hostId } }).finally(() => setRetrying(null));
260 };
261 const rows =
262 groups ??
263 environments.flatMap((environment) =>
264 environment.hosts.map((host) => ({
265 host,
266 members: [{ environmentId: environment.environmentId, label: environment.label, host }],
267 })),
268 );
269 return (
270 <>
271 {rows.length === 0 ? (
272 <p className="py-2 text-sm text-muted-foreground">No device hosts.</p>
273 ) : null}
274 {rows.map(({ host, members }) => {
275 const hostChecks = checks[deviceHostConnectionKey(host)];
276 const checkedMembers = scopeEnvironments.flatMap((environment) =>
277 hostChecks?.[environment.environmentId] &&
278 !members.some((member) => member.environmentId === environment.environmentId)
279 ? [{ environmentId: environment.environmentId, label: environment.label, host }]
280 : [],
281 );
282 const results = [...members, ...checkedMembers].map((member) => {
283 const state = states.get(member.environmentId);
284 const status = state?.hostStatuses[member.host.id];
285 const check = hostChecks?.[member.environmentId];
286 const summary = state?.hosts.find((value) => value.id === member.host.id);
287 const label = environmentLabels.get(member.environmentId)?.primary ?? member.label;
288 const address = environmentLabels.get(member.environmentId)?.secondary;
289 const error =
290 check?.status === "failed"
291 ? check.error
292 : check?.status === "local"
293 ? undefined
294 : status?.status === "failed"
295 ? status.detail
296 : undefined;
297 return {
298 ...member,
299 label,
300 address,
301 name: [label, address].filter(Boolean).join(" · "),
302 state,
303 status,
304 check,
305 summary,
306 error,
307 versions: (
308 <DeviceToolVersions
309 owner={label}
310 error={summary?.toolInspectionError}
311 tools={summary?.tools ?? (check?.status === "connected" ? check.tools : undefined)}
312 />
313 ),
314 };
315 });
316 const first = results[0];
317 if (!first) return null;
318 const { environmentId, status, check, summary, error } = first;
319 const platforms =
320 (check?.status === "connected" ? check.platforms : undefined) ?? summary?.platforms ?? [];
321 const progress =
322 check?.status === "pending"
323 ? "Checking connection…"
324 : status?.status === "installing"
325 ? "Installing device support…"
326 : status?.status === "starting"
327 ? "Connecting…"
328 : null;
329 const failed = results.filter(
330 (result) =>
331 result.check?.status === "failed" ||
332 (result.check?.status !== "local" && result.status?.status === "failed"),
333 );
334 const pending = results.some(
335 (result) =>
336 result.check?.status === "pending" ||
337 result.status?.status === "installing" ||
338 result.status?.status === "starting",
339 );
340 const ready = results.every(
341 (result) =>
342 result.check?.status === "connected" ||
343 result.check?.status === "local" ||
344 result.status?.status === "ready",
345 );
346 const retryable = results.filter(
347 (result) =>
348 result.status?.status === "failed" &&
349 result.state?.supportsHostRetry &&
350 result.state.hostStatus !== "disabled",
351 );
352 const canRetry = !compact && retryable.includes(first);
353 const indicators = compact
354 ? [
355 {
356 key: "connection",
357 label: failed.length
358 ? "Connection failed"
359 : pending
360 ? "Checking connections"
361 : ready
362 ? "Connected"
363 : "Connection not checked",
364 warning: failed.length > 0,
365 icon: failed.length ? (
366 <TriangleAlertIcon className="size-3.5" />
367 ) : pending ? (
368 <Spinner size="xs" />
369 ) : ready ? (
370 <CheckIcon className="size-3.5" />
371 ) : (
372 <CircleIcon className="size-3.5" />
373 ),
374 detail: failed.length ? (
375 <div className="space-y-1">
376 {failed.map((result) => (
377 <p key={result.environmentId}>
378 {result.name}: {result.error || "Connection failed"}
379 </p>
380 ))}
381 </div>
382 ) : pending ? (
383 "Checking connections…"
384 ) : ready ? (
385 "Connected or available locally on each listed machine"
386 ) : (
387 "Test the connection to check access from each machine"
388 ),
389 },
390 ]
391 : platforms
392 .filter((platform) => platform.available)
393 .map((platform) => ({
394 key: platform.platform,
395 label: platform.platform === "ios" ? "iOS available" : "Android available",
396 warning: false,
397 icon:
398 platform.platform === "ios" ? (
399 // The Apple mark is bottom-heavy; lift it so it does not dip under the label.
400 <AppleIcon className="size-3.5 -translate-y-px" />
401 ) : (
402 <AndroidIcon className="size-3.5" />
403 ),
404 }));
405 return (
406 <div key={host.id} className="flex items-center gap-2 border-t border-border/50 py-2.5">
407 <div className="min-w-0 flex-1">
408 <div className="flex min-w-0 items-center gap-2">
409 <p className="truncate text-sm font-medium">{host.label}</p>
410 {indicators.map((indicator) => (
411 <Tooltip key={indicator.key}>
412 <TooltipTrigger
413 render={
414 <span
415 tabIndex={0}
416 role="img"
417 aria-label={indicator.label}
418 className={
419 indicator.warning
420 ? "shrink-0 text-warning"
421 : "shrink-0 text-muted-foreground"
422 }
423 />
424 }
425 >
426 {indicator.icon}
427 </TooltipTrigger>
428 <TooltipPopup>
429 {"detail" in indicator ? indicator.detail : indicator.label}
430 </TooltipPopup>
431 </Tooltip>
432 ))}
433 </div>
434 <p className="truncate text-xs text-muted-foreground">{host.target}</p>
435 {results
436 .filter(
437 (result) =>
438 result.status?.status === "ready" && result.status.androidDiscoveryIncomplete,
439 )
440 .map((result) => (
441 <p key={result.environmentId} role="status" className="mt-1 text-xs text-warning">
442 {compact ? `${result.label}: ` : ""}
443 {result.status?.detail ??
444 "The Android device list may be incomplete. Refresh devices to try again."}
445 </p>
446 ))}
447 {compact ? (
448 <Collapsible>
449 <div className="min-w-0 text-xs [--inline-button-white-space:normal]">
450 <CollapsibleTrigger
451 aria-label={`${host.label} machine details`}
452 render={<InlineButton tone="muted" />}
453 >
454 <span className="line-clamp-1 break-all text-left">
455 {summarizeLabels(results.map((result) => result.name))}
456 </span>
457 <ChevronDownIcon className="size-3 shrink-0" />
458 </CollapsibleTrigger>
459 </div>
460 <CollapsiblePanel>
461 <div className="mt-2 space-y-2">
462 {results.map((result) => (
463 <div key={result.environmentId}>
464 <p className="text-xs text-muted-foreground">{result.label}</p>
465 {result.address ? (
466 <p className="truncate text-xs text-muted-foreground">
467 {result.address}
468 </p>
469 ) : null}
470 {result.error ? (
471 <p role="status" className="text-xs text-destructive">
472 {result.error}
473 </p>
474 ) : null}
475 {result.state ? (
476 <DeviceHostDiagnostics
477 hosts={[result.host]}
478 hostStatuses={result.state.hostStatuses}
479 />
480 ) : null}
481 {result.versions}
482 {result.check?.status === "local" ? (
483 <p className="text-xs text-muted-foreground">
484 Already available locally
485 </p>
486 ) : (
487 <DeviceHostAvailability
488 platforms={
489 (result.check?.status === "connected"
490 ? result.check.platforms
491 : result.summary?.platforms) ?? []
492 }
493 />
494 )}
495 </div>
496 ))}
497 </div>
498 </CollapsiblePanel>
499 </Collapsible>
500 ) : (
501 first.versions
502 )}
503 {!compact && check?.status === "local" ? (
504 <p className="mt-1 text-xs text-muted-foreground">Already available locally</p>
505 ) : null}
506 {!compact && error ? (
507 <div className="mt-1" role="status">
508 <details className="text-xs text-destructive">
509 <summary>Connection failed</summary>
510 <p className="mt-1 whitespace-pre-wrap break-words">{error}</p>
511 </details>
512 </div>
513 ) : null}
514 {!compact
515 ? results.map((result) =>
516 result.state ? (
517 <DeviceHostDiagnostics
518 key={result.environmentId}
519 className="mt-1"
520 hosts={[result.host]}
521 hostStatuses={result.state.hostStatuses}
522 />
523 ) : null,
524 )
525 : null}
526 </div>
527 {!compact && progress ? (
528 <span
529 role="status"
530 className="inline-flex items-center gap-1.5 text-xs text-muted-foreground"
531 >
532 <Spinner size="xs" />
533 {progress}
534 </span>
535 ) : null}
536 <Menu>
537 <MenuTrigger
538 render={
539 <Button
540 size="icon-sm"
541 variant="ghost-muted"
542 disabled={busy}
543 aria-label={host.label + " options"}
544 />
545 }
546 >
547 <MoreVertical />
548 </MenuTrigger>
549 <MenuPopup align="end">
550 <MenuItem onClick={() => onEdit(host)}>Edit</MenuItem>
551 <MenuItem variant="destructive" onClick={() => onRemove(host)}>
552 Remove
553 </MenuItem>
554 {compact
555 ? retryable.map((result) => (
556 <MenuItem
557 key={result.environmentId}
558 disabled={retrying !== null}
559 onClick={() =>
560 retryHost(result.environmentId, result.host.id, result.environmentId)
561 }
562 >
563 {retrying === result.environmentId ? "Retrying" : "Retry"} from{" "}
564 {result.label}
565 {result.address ? ` (${result.address})` : null}
566 </MenuItem>
567 ))
568 : null}
569 </MenuPopup>
570 </Menu>
571 <Button
572 size="sm"
573 variant="outline"
574 disabled={
575 busy || (canRetry ? retrying !== null : compact ? pending : progress !== null)
576 }
577 onClick={() => {
578 if (canRetry) retryHost(environmentId, host.id);
579 else void testConnection(host);
580 }}
581 >
582 {canRetry ? (retrying === host.id ? "Retrying…" : "Retry") : "Test connection"}
583 </Button>
584 </div>
585 );
586 })}
587 </>
588 );
589}
590
591function summarizeLabels(labels: ReadonlyArray<string>) {
592 return `${labels.slice(0, 2).join(", ")}${labels.length > 2 ? ` +${labels.length - 2}` : ""}`;
593}