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

DeviceHostsSettings.tsx

560 lines22.0 KB

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