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

DeviceHostsSettings.tsx

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