@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 520 lines 20.1 KB
Raw
1 import { DeviceHostUpdates } from "./DeviceHostUpdates";
2 import type {
3 DevicePlatform,
4 DeviceServiceState,
5 DeviceSummary,
6 ScopedThreadRef,
7 } from "@t3tools/contracts";
8 import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react";
9 import { useAtomMount } from "@effect/atom-react";
10 import { T, useGT, Var } from "gt-react";
11 import { type ReactNode, useState } from "react";
12
13 import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
14 import {
15 selectThreadRightPanelState,
16 useRightPanelStore,
17 type RightPanelSurface,
18 } from "~/rightPanelStore";
19 import { Button } from "~/components/ui/button";
20 import { DiscoveryList } from "~/components/ui/discovery-list";
21 import { Dialog } from "~/components/ui/dialog";
22 import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
23 import { WizardPopup } from "~/components/ui/wizard";
24 import { Spinner } from "~/components/ui/spinner";
25 import { cn } from "~/lib/utils";
26 import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";
27 import {
28 deviceEnvironment,
29 deviceHostProbeAtom,
30 NO_DEVICE_PROBE_ATOM,
31 useDeviceState,
32 } from "~/state/device";
33 import { formatEnvironmentQueryError } from "~/state/query";
34 import { useAtomCommand } from "~/state/use-atom-command";
35 import { DeviceLoadingView } from "./DeviceLoadingView";
36 import {
37 DeviceSetup,
38 deviceHubReadiness,
39 incompleteListings,
40 isAndroidDiscoveryUncertain,
41 } from "./DeviceSetup";
42 import { DeviceWorkspace } from "./DeviceWorkspace";
43 import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
44
45 const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
46 `${device.hostId}\u0000${device.id}`;
47
48 export function DevicePanel(props: {
49 readonly mode: PreviewPanelMode;
50 readonly threadRef: ScopedThreadRef;
51 readonly surface: Extract<RightPanelSurface, { kind: "device" }>;
52 readonly visible: boolean;
53 readonly onDismissSetup: () => void;
54 }) {
55 const { environmentId, threadId } = props.threadRef;
56 const gt = useGT();
57 const { state, loaded, error: stateError, refresh: refreshState } = useDeviceState(environmentId);
58 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
59 const open = useAtomCommand(deviceEnvironment.open);
60 const close = useAtomCommand(deviceEnvironment.close);
61 // The panel stays mounted across thread switches, so an in-flight open or
62 // power-off is tagged with the thread it belongs to and only shown there.
63 const scope = `${environmentId}\u0000${threadId}`;
64 const [operation, setOperation] = useState<{
65 readonly scope: string;
66 readonly pending: DeviceSummary | null;
67 readonly error: string | null;
68 } | null>(null);
69 const pendingDevice = operation?.scope === scope ? operation.pending : null;
70 const operationError = operation?.scope === scope ? operation.error : null;
71 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
72
73 const hostDisabled = state.hostStatus === "disabled";
74
75 useAtomMount(
76 props.visible && loaded && !hostDisabled
77 ? deviceHostProbeAtom(environmentId)
78 : NO_DEVICE_PROBE_ATOM,
79 );
80
81 const sessions = state.sessions.filter((session) => session.threadId === threadId);
82 const activeSession = props.surface.target
83 ? sessions.find(
84 (session) =>
85 session.deviceId === props.surface.target?.deviceId &&
86 session.hostId === props.surface.target.hostId,
87 )
88 : undefined;
89 const activeDevice = activeSession
90 ? state.devices.find(
91 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
92 )
93 : undefined;
94 const activeHost = activeDevice
95 ? state.hosts.find((host) => host.id === activeDevice.hostId)
96 : undefined;
97
98 const grouped = groupDevices(state);
99
100 const startOperation = (pending: DeviceSummary | null) => {
101 const started = { scope, pending, error: null };
102 setOperation(started);
103 // Returning to the same thread can start a newer operation before this one settles.
104 return (error: string | null) =>
105 setOperation((current) =>
106 current === started ? { ...started, pending: null, error } : current,
107 );
108 };
109
110 const selectDevice = async (value: string) => {
111 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
112 if (!device) return;
113 const settleOperation = startOperation(device);
114 const result = await open({
115 environmentId,
116 input: {
117 threadId,
118 hostId: device.hostId,
119 deviceId: device.id,
120 platform: device.platform,
121 },
122 });
123 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
124 else {
125 // The server opened the device for the starting thread, so its tab opens there.
126 useRightPanelStore.getState().openDevice(props.threadRef, {
127 hostId: result.value.hostId,
128 deviceId: result.value.deviceId,
129 platform: device.platform,
130 name: device.name,
131 });
132 settleOperation(null);
133 }
134 };
135
136 const floatActive = () => {
137 if (!activeDevice) return;
138 usePreviewMiniPlayerStore.getState().open(props.threadRef, {
139 kind: "device",
140 hostId: activeDevice.hostId,
141 deviceId: activeDevice.id,
142 platform: activeDevice.platform,
143 name: activeDevice.name,
144 });
145 useRightPanelStore.getState().close(props.threadRef);
146 };
147
148 const closeSurface = () => {
149 const store = useRightPanelStore.getState();
150 const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef);
151 store.closeSurface(props.threadRef, props.surface.id);
152 focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId);
153 };
154
155 const closeActive = (powerOff: boolean) => {
156 if (!powerOff) {
157 closeSurface();
158 return;
159 }
160 if (!activeSession) return;
161 const settleOperation = startOperation(null);
162 void close({
163 environmentId,
164 input: {
165 threadId,
166 hostId: activeSession.hostId,
167 deviceId: activeSession.deviceId,
168 shutdown: powerOff,
169 },
170 }).then((result) => {
171 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
172 else closeSurface();
173 });
174 };
175
176 const bootingDevices =
177 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
178 const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
179 const loading = !activeDevice && (pendingDevice !== null || hostBusy || !loaded);
180 // Without a first snapshot a failed subscription never settles on its own.
181 const loadError = loaded ? null : stateError;
182 const diagnostics = state.hosts.flatMap((host) => {
183 const status = state.hostStatuses[host.id];
184 const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined);
185 return detail && (status?.status ?? state.hostStatus) === "ready"
186 ? [
187 {
188 hostId: host.id,
189 label: host.label,
190 detail,
191 incompletePlatforms: incompleteListings(status),
192 },
193 ]
194 : [];
195 });
196 const unavailablePlatforms = state.hosts.flatMap((host) =>
197 host.platforms
198 .filter((platform) => !platform.available)
199 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
200 );
201
202 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
203 return (
204 <Dialog
205 open={props.visible}
206 onOpenChange={(isOpen) => {
207 if (!isOpen) props.onDismissSetup();
208 }}
209 >
210 <WizardPopup>
211 <DeviceSetup environmentId={environmentId} state={state} />
212 </WizardPopup>
213 </Dialog>
214 );
215 }
216
217 return (
218 <PreviewPanelShell mode={props.mode}>
219 <div className="relative flex min-h-0 flex-1 flex-col">
220 <div
221 className={cn(
222 "shrink-0 bg-background",
223 loading && "absolute inset-x-0 top-0 z-10 max-h-[40%] overflow-y-auto",
224 )}
225 >
226 <div hidden={!!activeDevice}>
227 {diagnostics.map((diagnostic) => (
228 <DeviceDiscoveryWarning
229 key={`${environmentId}\u0000${diagnostic.hostId}`}
230 label={diagnostic.label}
231 detail={diagnostic.detail}
232 incompletePlatforms={diagnostic.incompletePlatforms}
233 onRetry={() => list({ environmentId, input: {} })}
234 />
235 ))}
236 </div>
237 <DeviceHostUpdates state={state} environmentId={environmentId} />
238 {bootingDevices.length > 0 ? (
239 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
240 <T>
241 Starting <Var>{bootingDevices.map((device) => device.name).join(", ")}</Var>… This
242 can take a minute.
243 </T>
244 </div>
245 ) : null}
246 {operationError ? (
247 <DeviceNotice onDismiss={() => setOperation(null)}>{operationError}</DeviceNotice>
248 ) : null}
249 </div>
250 <div className="@container relative flex min-h-0 flex-1">
251 {activeDevice && activeSession ? (
252 <DeviceWorkspace
253 key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
254 environmentId={environmentId}
255 device={activeDevice}
256 hostLabel={activeHost?.label ?? gt("Device host")}
257 hostKind={activeHost?.kind}
258 hostDiagnostics={
259 diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail
260 }
261 visible={props.visible}
262 onFloat={floatActive}
263 onClose={() => closeActive(false)}
264 onPowerOff={() => closeActive(true)}
265 />
266 ) : loading ? (
267 <DeviceLoadingView
268 name={pendingDevice?.name ?? gt("Devices")}
269 description={
270 pendingDevice
271 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? gt("Device host")} · ${pendingDevice.version}`
272 : ""
273 }
274 stage="opening"
275 message={
276 loadError ??
277 (pendingDevice
278 ? pendingDevice.booted
279 ? gt("Opening device…")
280 : gt("Starting device…")
281 : state.hostStatus === "installing"
282 ? (state.hostStatusDetail ?? gt("Installing device support…"))
283 : gt("Finding devices…"))
284 }
285 error={loadError !== null}
286 >
287 {loadError !== null ? (
288 <Button size="sm" variant="outline" onClick={refreshState}>
289 <T>Retry</T>
290 </Button>
291 ) : null}
292 </DeviceLoadingView>
293 ) : (
294 <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
295 <div
296 className={cn(
297 "mx-auto flex w-full max-w-xl flex-col gap-6",
298 grouped.length === 0 && "my-auto items-center text-center",
299 )}
300 >
301 {grouped.length === 0 ? (
302 <>
303 <Smartphone className="size-6 opacity-60" />
304 <p
305 className="max-h-32 w-full max-w-sm overflow-y-auto whitespace-pre-line break-words"
306 tabIndex={state.hostStatus === "failed" ? 0 : undefined}
307 >
308 {state.hostStatus === "failed"
309 ? (state.hostStatusDetail ?? gt("The device hub failed to start."))
310 : gt("No simulators or emulators were found on this environment.")}
311 </p>
312 </>
313 ) : null}
314 {hostReady && grouped.length > 0 ? (
315 <div className="w-full space-y-6 text-left">
316 {grouped.map((group) => (
317 <section key={group.platform} className="space-y-3">
318 <div className="flex items-center gap-2 text-sm text-muted-foreground">
319 <Smartphone className="size-4 shrink-0" />
320 <h3 className="font-medium">
321 {group.platform === "ios"
322 ? gt("iOS Simulators")
323 : gt("Android Emulators")}
324 </h3>
325 </div>
326 <DiscoveryList>
327 {group.devices.map((device) => (
328 <div
329 key={deviceKey(device)}
330 className="flex items-center gap-3 px-3 py-3"
331 >
332 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
333 <Smartphone className="size-4" />
334 </span>
335 <div className="flex min-w-0 flex-1 flex-col">
336 <span className="truncate text-sm font-medium text-foreground">
337 {device.name}
338 </span>
339 <span className="truncate text-xs text-muted-foreground">
340 {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? gt("Running", { $context: "device state" }) : gt("Stopped", { $context: "device state" })}`}
341 </span>
342 </div>
343 <Button
344 variant="outline"
345 size="sm"
346 disabled={pendingDeviceKey !== null}
347 aria-label={
348 device.booted
349 ? gt("Open {name}", { name: device.name })
350 : gt("Start {name}", { name: device.name })
351 }
352 onClick={() => void selectDevice(deviceKey(device))}
353 >
354 {pendingDeviceKey === deviceKey(device) ? (
355 <Spinner size="xs" />
356 ) : device.booted ? (
357 <ArrowUpRight />
358 ) : (
359 <Play />
360 )}
361 {device.booted
362 ? gt("Open", { $context: "verb, opens a running device" })
363 : gt("Start", { $context: "verb, boots a device" })}
364 </Button>
365 </div>
366 ))}
367 </DiscoveryList>
368 </section>
369 ))}
370 </div>
371 ) : null}
372 {hostReady &&
373 !isAndroidDiscoveryUncertain(state) &&
374 !state.devices.some((device) => device.platform === "android") &&
375 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
376 <p className="max-w-sm text-xs">
377 <T>
378 No Android virtual devices found. Create one in Android Studio's Device
379 Manager, then refresh.
380 </T>
381 </p>
382 ) : null}
383 {loaded && !hostBusy ? (
384 <Button
385 className={grouped.length > 0 ? "self-start" : "self-center"}
386 variant="outline"
387 size="sm"
388 onClick={() => void list({ environmentId, input: {} })}
389 >
390 <T>Refresh devices</T>
391 </Button>
392 ) : null}
393 </div>
394 </div>
395 )}
396 </div>
397 </div>
398 </PreviewPanelShell>
399 );
400 }
401
402 function DeviceNotice(props: { readonly onDismiss: () => void; readonly children: ReactNode }) {
403 const gt = useGT();
404 return (
405 <div
406 role="alert"
407 className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
408 >
409 <CircleAlert className="mt-1 size-3.5 shrink-0" />
410 <div
411 className="max-h-32 min-w-0 flex-1 overflow-y-auto whitespace-pre-wrap break-words"
412 tabIndex={0}
413 >
414 {props.children}
415 </div>
416 <Button
417 size="icon-xs"
418 variant="ghost"
419 aria-label={gt("Dismiss device error")}
420 onClick={props.onDismiss}
421 >
422 <X />
423 </Button>
424 </div>
425 );
426 }
427
428 function DeviceDiscoveryWarning(props: {
429 readonly label: string;
430 readonly detail: string;
431 readonly incompletePlatforms: readonly DevicePlatform[];
432 readonly onRetry: () => Promise<unknown>;
433 }) {
434 const gt = useGT();
435 const [open, setOpen] = useState(false);
436 const [retrying, setRetrying] = useState(false);
437 const [dismissedCause, setDismissedCause] = useState<string | null>(null);
438 const cause = `${props.incompletePlatforms.join()}\u0000${props.detail}`;
439 // A dismissal hides one occurrence; a cause that returns later shows again.
440 if (dismissedCause !== null && dismissedCause !== cause) setDismissedCause(null);
441 if (dismissedCause === cause) return null;
442 const platforms = props.incompletePlatforms.map((platform) =>
443 platform === "ios" ? "iOS" : "Android",
444 );
445 return (
446 <div
447 role="status"
448 className="flex flex-wrap items-center gap-x-2 gap-y-0.5 border-b px-3 py-1 text-xs text-muted-foreground"
449 >
450 <span className="flex min-w-0 flex-1 basis-56 items-start gap-2">
451 <CircleAlert className="mt-px size-3.5 shrink-0 text-warning-foreground" />
452 <span className="min-w-0">
453 {platforms.length > 1
454 ? gt("{first} and {second} lists on {host} may be incomplete.", {
455 first: platforms[0],
456 second: platforms[1],
457 host: props.label,
458 })
459 : platforms.length === 1
460 ? gt("{platform} list on {host} may be incomplete.", {
461 platform: platforms[0],
462 host: props.label,
463 })
464 : gt("Device discovery on {host} reported a warning.", { host: props.label })}
465 </span>
466 </span>
467 <span className="ml-auto flex shrink-0 items-center gap-0.5">
468 {platforms.length > 0 ? (
469 <Button
470 size="micro"
471 variant="ghost"
472 disabled={retrying}
473 aria-label={gt("Retry device discovery on {host}", { host: props.label })}
474 onClick={() => {
475 setRetrying(true);
476 void props.onRetry().finally(() => setRetrying(false));
477 }}
478 >
479 {retrying ? gt("Retrying…") : gt("Retry")}
480 </Button>
481 ) : null}
482 <Popover open={open} onOpenChange={setOpen}>
483 <PopoverTrigger
484 aria-label={gt("Details for {host}", { host: props.label })}
485 render={<Button size="micro" variant="ghost" />}
486 >
487 <T>Details</T>
488 </PopoverTrigger>
489 <PopoverPopup side="bottom" align="end" width="lg" padding="compact">
490 <p className="whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground">
491 {props.detail}
492 </p>
493 </PopoverPopup>
494 </Popover>
495 <Button
496 size="icon-micro"
497 variant="ghost"
498 aria-label={gt("Dismiss device warning for {host}", { host: props.label })}
499 onClick={() => {
500 setOpen(false);
501 setDismissedCause(cause);
502 }}
503 >
504 <X />
505 </Button>
506 </span>
507 </div>
508 );
509 }
510
511 function groupDevices(state: DeviceServiceState) {
512 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
513 for (const platform of ["ios", "android"] as const) {
514 const devices = state.devices
515 .filter((device) => device.platform === platform)
516 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
517 if (devices.length > 0) groups.push({ platform, devices });
518 }
519 return groups;
520 }