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

DeviceHostsSettings.tsx

299 lines11.3 KB

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