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