Open History to see the last commit
1import { DeviceToolVersions } from "../device/DeviceToolVersions";
2import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
3import { AppleIcon, AndroidIcon } from "../Icons";
4import { Spinner } from "../ui/spinner";
5import type { EnvironmentId, SshDeviceHostConfig } from "@t3tools/contracts";
6import { randomUUID } from "../../lib/utils";
7import { useState } from "react";
8import { deviceEnvironment, useDeviceState } from "../../state/device";
9import { serverEnvironment } from "../../state/server";
10import { useAtomCommand } from "../../state/use-atom-command";
11import { Button } from "../ui/button";
12import { MoreVertical, PlusIcon } from "lucide-react";
13import { Menu, MenuTrigger, MenuPopup, MenuItem } from "../ui/menu";
14import { SettingsRow } from "./settingsLayout";
15
16import { useSettingsScope } from "./SettingsScopeContext";
17import { toastManager } from "../ui/toast";
18import { updateDeviceHosts } from "./deviceHostsSettings.logic";
19import { DeviceHostEditor } from "./DeviceHostEditor";
20import { useHostConnectionChecks } from "./useHostConnectionChecks";
21import { deviceHostConnectionKey } from "./deviceHostConnectionChecks";
22
23export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null }) {
24 const { scope, environments, connectedEnvironments } = useSettingsScope();
25 const projectScope = scope.kind === "project" || scope.kind === "checkout";
26 const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
27 const [editing, setEditing] = useState<SshDeviceHostConfig | null>(null);
28 const [originalHost, setOriginalHost] = useState<SshDeviceHostConfig | null>(null);
29 const [busy, setBusy] = useState(false);
30 const targets = environments.map((environment) => ({
31 environmentId: environment.environmentId,
32 label: environment.label,
33 connected: environment.connection.phase === "connected",
34 }));
35 const { checks, testConnection } = useHostConnectionChecks(targets);
36 const save = async (host: SshDeviceHostConfig, remove = false, original = host) => {
37 if (!props.environmentId || projectScope) return;
38 setBusy(true);
39 try {
40 const results = await Promise.allSettled(
41 environments.map(async (environment) => {
42 if (environment.connection.phase !== "connected" || !environment.serverConfig) {
43 throw new Error("Environment disconnected");
44 }
45 return update({
46 environmentId: environment.environmentId,
47 input: {
48 patch: {
49 deviceHosts: updateDeviceHosts(
50 environment.serverConfig.settings.deviceHosts,
51 host,
52 remove,
53 original,
54 ),
55 },
56 },
57 });
58 }),
59 );
60 const failed = environments.filter((_, index) => {
61 const result = results[index];
62 return result?.status !== "fulfilled" || result.value._tag === "Failure";
63 });
64 if (failed.length === 0) {
65 setEditing(null);
66 } else {
67 toastManager.add({
68 type: "error",
69 title: "Device hosts not saved on all environments",
70 description: `Could not update ${failed.map((environment) => environment.label).join(", ")}.`,
71 });
72 }
73 } finally {
74 setBusy(false);
75 }
76 };
77 return (
78 <SettingsRow
79 id="device-hosts"
80 title="Device hosts"
81 serverScoped
82 settingKeys={["deviceHosts"]}
83 description="Add remote machines with simulator or emulator runtimes installed, and the selected environments will connect over SSH and set up device tools automatically."
84 control={
85 <Button
86 size="sm"
87 variant="outline"
88 disabled={projectScope || busy || !props.environmentId || editing !== null}
89 onClick={() => {
90 setOriginalHost(null);
91 setEditing({ id: randomUUID(), label: "", target: "" });
92 }}
93 >
94 <PlusIcon className="size-3.5" /> Add host
95 </Button>
96 }
97 >
98 <div className="pt-3 pb-2">
99 {!props.environmentId ? (
100 <p className="text-sm text-muted-foreground">
101 Connect a selected environment to manage device hosts.
102 </p>
103 ) : (
104 <>
105 {connectedEnvironments.map((environment) => (
106 <div key={environment.environmentId}>
107 {connectedEnvironments.length > 1 ? (
108 <p className="pt-3 pb-1 text-xs font-medium text-muted-foreground">
109 {environment.label}
110 </p>
111 ) : null}
112 <DeviceHostList
113 environmentLabel={environment.label}
114 environmentId={environment.environmentId}
115 hosts={environment.serverConfig?.settings.deviceHosts ?? []}
116 busy={projectScope || busy}
117 checks={checks}
118 testConnection={async (host) => {
119 const results = await testConnection(host);
120 if (!results) return;
121 const failed = targets.filter(
122 (target) => results[target.environmentId]?.status === "failed",
123 );
124 toastManager.add({
125 type: failed.length ? "error" : "success",
126 title: failed.length
127 ? `${host.label}: ${failed.length} of ${targets.length} environments failed`
128 : `${host.label}: connection checks passed`,
129 description: failed.length
130 ? `Could not connect from ${failed.map((target) => target.label).join(", ")}.`
131 : "Connected or already available locally on each selected environment.",
132 });
133 return results;
134 }}
135 onEdit={(host) => {
136 setOriginalHost(host);
137 setEditing(host);
138 }}
139 onRemove={(host) => void save(host, true)}
140 />
141 </div>
142 ))}
143 {editing ? (
144 <DeviceHostEditor
145 key={editing.id}
146 host={editing}
147 isNew={originalHost === null}
148 targets={targets}
149 busy={busy}
150 onSave={(host) => void save(host, false, originalHost ?? host)}
151 onClose={() => setEditing(null)}
152 />
153 ) : null}
154 </>
155 )}
156 </div>
157 </SettingsRow>
158 );
159}
160
161function DeviceHostList({
162 environmentLabel,
163 environmentId,
164 hosts,
165 busy,
166 onEdit,
167 onRemove,
168 checks,
169 testConnection,
170}: {
171 environmentLabel: string;
172 environmentId: EnvironmentId;
173 hosts: ReadonlyArray<SshDeviceHostConfig>;
174 busy: boolean;
175 onEdit: (host: SshDeviceHostConfig) => void;
176 onRemove: (host: SshDeviceHostConfig) => void;
177 checks: ReturnType<typeof useHostConnectionChecks>["checks"];
178 testConnection: ReturnType<typeof useHostConnectionChecks>["testConnection"];
179}) {
180 const { state } = useDeviceState(environmentId);
181 const retry = useAtomCommand(deviceEnvironment.list);
182 const [retrying, setRetrying] = useState<string | null>(null);
183 return (
184 <>
185 {hosts.length === 0 ? (
186 <p className="py-2 text-sm text-muted-foreground">No device hosts.</p>
187 ) : null}
188 {hosts.map((host) => {
189 const status = state.hostStatuses[host.id];
190 const check = checks[deviceHostConnectionKey(host)]?.[environmentId];
191 const platforms =
192 (check?.status === "connected" ? check.platforms : undefined) ??
193 state.hosts.find((value) => value.id === host.id)?.platforms ??
194 [];
195 const progress =
196 check?.status === "pending"
197 ? "Checking connection…"
198 : status?.status === "installing"
199 ? "Installing device support…"
200 : status?.status === "starting"
201 ? "Connecting…"
202 : null;
203 const error =
204 check?.status === "failed"
205 ? check.error
206 : check?.status === "local"
207 ? undefined
208 : status?.status === "failed"
209 ? status.detail
210 : undefined;
211 return (
212 <div key={host.id} className="flex items-center gap-2 border-t border-border/50 py-2.5">
213 <div className="min-w-0 flex-1">
214 <div className="flex min-w-0 items-center gap-2">
215 <p className="truncate text-sm font-medium">{host.label}</p>
216 {platforms
217 .filter((platform) => platform.available)
218 .map((platform) => (
219 <Tooltip key={platform.platform}>
220 <TooltipTrigger
221 render={
222 <span
223 tabIndex={0}
224 role="img"
225 aria-label={
226 platform.platform === "ios" ? "iOS available" : "Android available"
227 }
228 className="shrink-0 text-muted-foreground"
229 />
230 }
231 >
232 {platform.platform === "ios" ? (
233 <AppleIcon className="size-3.5" />
234 ) : (
235 <AndroidIcon className="size-3.5" />
236 )}
237 </TooltipTrigger>
238 <TooltipPopup>
239 {platform.platform === "ios" ? "iOS available" : "Android available"}
240 </TooltipPopup>
241 </Tooltip>
242 ))}
243 </div>
244 <p className="truncate text-xs text-muted-foreground">{host.target}</p>
245 <DeviceToolVersions
246 owner={environmentLabel}
247 error={state.hosts.find((value) => value.id === host.id)?.toolInspectionError}
248 tools={
249 state.hosts.find((value) => value.id === host.id)?.tools ??
250 (check?.status === "connected" ? check.tools : undefined)
251 }
252 />
253 {check?.status === "local" ? (
254 <p className="mt-1 text-xs text-muted-foreground">Already available locally</p>
255 ) : null}
256 {error ? (
257 <div className="mt-1" role="status">
258 <details className="text-xs text-destructive">
259 <summary>Connection failed</summary>
260 <p className="mt-1 whitespace-pre-wrap break-words">{error}</p>
261 </details>
262 </div>
263 ) : null}
264 </div>
265 {progress ? (
266 <span
267 role="status"
268 className="inline-flex items-center gap-1.5 text-xs text-muted-foreground"
269 >
270 <Spinner size="xs" />
271 {progress}
272 </span>
273 ) : null}
274 <Menu>
275 <MenuTrigger
276 render={
277 <Button
278 size="icon-sm"
279 variant="ghost-muted"
280 disabled={busy}
281 aria-label={host.label + " options"}
282 />
283 }
284 >
285 <MoreVertical />
286 </MenuTrigger>
287 <MenuPopup align="end">
288 <MenuItem
289 onClick={() => {
290 onEdit(host);
291 }}
292 >
293 Edit
294 </MenuItem>
295 <MenuItem variant="destructive" onClick={() => onRemove(host)}>
296 Remove
297 </MenuItem>
298 </MenuPopup>
299 </Menu>
300 {status?.status === "failed" &&
301 state.supportsHostRetry &&
302 state.hostStatus !== "disabled" ? (
303 <Button
304 size="sm"
305 variant="outline"
306 disabled={busy || retrying !== null}
307 onClick={() => {
308 setRetrying(host.id);
309 void retry({ environmentId, input: { retryHostId: host.id } }).finally(() =>
310 setRetrying(null),
311 );
312 }}
313 >
314 {retrying === host.id ? "Retrying…" : "Retry"}
315 </Button>
316 ) : (
317 <Button
318 size="sm"
319 variant="outline"
320 disabled={busy || progress !== null}
321 onClick={() => void testConnection(host)}
322 >
323 Test connection
324 </Button>
325 )}
326 </div>
327 );
328 })}
329 </>
330 );
331}