Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
3import { Atom } from "effect/reactivity";
4import { TriangleAlertIcon } from "lucide-react";
5import {
6 type ComponentProps,
7 useCallback,
8 useEffect,
9 useId,
10 useMemo,
11 useRef,
12 useState,
13} from "react";
14import { flushSync } from "react-dom";
15import { isElectron } from "../../env";
16import { useMediaQuery } from "../../hooks/useMediaQuery";
17import { cn } from "../../lib/utils";
18import { ensureLocalApi } from "../../localApi";
19import { useDesktopUpdateState } from "../../state/desktopUpdate";
20import { serverEnvironment } from "../../state/server";
21import { stackedThreadToast, toastManager } from "../ui/toast";
22import {
23 canCheckForUpdate,
24 getArm64IntelBuildWarningDescription,
25 getDesktopUpdateActionError,
26 getDesktopUpdateButtonTooltip,
27 getDesktopUpdateDownloadedVersion,
28 getDesktopUpdateInstallConfirmationMessage,
29 isDesktopUpdateButtonDisabled,
30 resolveDesktopUpdateButtonAction,
31 shouldShowArm64IntelBuildWarning,
32 shouldToastDesktopUpdateActionResult,
33} from "../desktopUpdate.logic";
34import { showDesktopUpdateDownloadedToast } from "../desktopUpdate.toast";
35import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
36import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover";
37import { SidebarMenuItem } from "../ui/sidebar";
38import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
39import {
40 DesktopUpdateStatusIcon,
41 type DesktopUpdateStatusIconState,
42 shouldContinueDesktopUpdateCheckAnimation,
43 shouldShowDesktopUpdateCheckIcon,
44} from "./DesktopUpdateStatusIcon";
45import { SidebarUpdateReleaseNotes } from "./SidebarUpdateReleaseNotes";
46import { UpdateEverythingDialog } from "./UpdateEverythingDialog";
47import {
48 describeUpdateRun,
49 resolveUpdateRunMachineStatus,
50 type UpdateEverythingRun,
51} from "./updateEverything.logic";
52import { useUpdateEverythingRun } from "./updateEverythingRun";
53import { type ReportLocalUpdateError, useUpdateEverything } from "./useUpdateEverything";
54
55type SidebarUpdatePopoverChangeDetails = Parameters<
56 NonNullable<ComponentProps<typeof Popover>["onOpenChange"]>
57>[1];
58type SidebarUpdatePopoverHandle = ReturnType<typeof PopoverCreateHandle>;
59
60export function shouldUseSidebarUpdateReleaseNotesPopover(
61 showUpdateDetails: boolean,
62 state: DesktopUpdateState | null,
63): boolean {
64 return showUpdateDetails && state?.channel === "nightly" && state.releaseNotes.length > 0;
65}
66
67export function handleSidebarUpdateReleaseNotesPopoverOpenChange(
68 _open: boolean,
69 details: Pick<SidebarUpdatePopoverChangeDetails, "reason" | "cancel">,
70): void {
71 // The trigger is the update action, so its presses must not also toggle the Popover.
72 if (details.reason === "trigger-press") details.cancel();
73}
74
75export function openSidebarUpdateReleaseNotesPopoverOnForwardTab(
76 event: { readonly key: string; readonly shiftKey: boolean },
77 handle: Pick<SidebarUpdatePopoverHandle, "open">,
78 triggerId: string,
79): void {
80 if (event.key !== "Tab" || event.shiftKey) return;
81 // Hover-open popovers do not manage focus. Promote this one before native Tab runs.
82 flushSync(() => handle.open(triggerId));
83}
84
85function resolveSidebarUpdatePresentation({
86 action,
87 showsEverything,
88 run,
89 isDownloading,
90 showCheckIcon,
91}: {
92 readonly action: ReturnType<typeof resolveDesktopUpdateButtonAction>;
93 /** Remote work is waiting, and this app is not downloading. */
94 readonly showsEverything: boolean;
95 /** The running "update everything" pass. Its state sets the icon. */
96 readonly run: UpdateEverythingRun | null;
97 readonly isDownloading: boolean;
98 readonly showCheckIcon: boolean;
99}) {
100 const showUpdateDetails = action !== "none" || showsEverything || run !== null || isDownloading;
101 const iconStatus: DesktopUpdateStatusIconState = showCheckIcon
102 ? "checking"
103 : isDownloading
104 ? "downloading"
105 : run !== null
106 ? run.localVersion !== null && action === "install"
107 ? "downloaded"
108 : "everything"
109 : showsEverything
110 ? "everything"
111 : action === "install"
112 ? "downloaded"
113 : action === "download"
114 ? "available"
115 : "idle";
116
117 return {
118 iconStatus,
119 showUpdateDetails,
120 showUpdateIconState: showUpdateDetails && !showCheckIcon,
121 } as const;
122}
123
124export function SidebarUpdateArchitectureWarning() {
125 return isElectron ? <SidebarUpdateArchitectureWarningContent /> : null;
126}
127
128function SidebarUpdateArchitectureWarningContent() {
129 const state = useDesktopUpdateState();
130 const visible = shouldShowArm64IntelBuildWarning(state);
131 const description = state && visible ? getArm64IntelBuildWarningDescription(state) : null;
132
133 if (!visible || !description) return null;
134
135 return (
136 <Alert variant="warning">
137 <TriangleAlertIcon />
138 <AlertTitle>Intel build on Apple Silicon</AlertTitle>
139 <AlertDescription>{description}</AlertDescription>
140 </Alert>
141 );
142}
143
144const toastUpdateError: ReportLocalUpdateError = (title, description) => {
145 toastManager.add(stackedThreadToast({ type: "error", title, description }));
146};
147
148/** Downloads this app's update. Resolves true when it is ready to install;
149 failures go to `reportError` (a toast by default) and resolve false. */
150async function downloadLocalUpdate(
151 bridge: DesktopBridge,
152 {
153 notifyDownloaded,
154 reportError = toastUpdateError,
155 }: { readonly notifyDownloaded: boolean; readonly reportError?: ReportLocalUpdateError },
156): Promise<boolean> {
157 try {
158 const result = await bridge.downloadUpdate();
159 if (result.completed && notifyDownloaded) {
160 showDesktopUpdateDownloadedToast(bridge, result.state);
161 }
162 const actionError = shouldToastDesktopUpdateActionResult(result)
163 ? getDesktopUpdateActionError(result)
164 : null;
165 if (actionError) reportError("Could not download update", actionError);
166 return result.completed;
167 } catch (error) {
168 reportError(
169 "Could not start update download",
170 error instanceof Error ? error.message : "An unexpected error occurred.",
171 );
172 return false;
173 }
174}
175
176/** Installs this app's downloaded update, which relaunches the app. Resolves
177 true when the relaunch is under way. Failures go to `reportError` (a toast
178 by default). A refused install (the download is not marked ready yet)
179 leaves the restart to the user. */
180async function installLocalUpdate(
181 bridge: DesktopBridge,
182 reportError: ReportLocalUpdateError = toastUpdateError,
183): Promise<boolean> {
184 try {
185 const result = await bridge.installUpdate();
186 if (!result.accepted) {
187 showDesktopUpdateDownloadedToast(bridge, result.state);
188 return false;
189 }
190 const actionError = shouldToastDesktopUpdateActionResult(result)
191 ? getDesktopUpdateActionError(result)
192 : null;
193 if (!actionError) return true;
194 reportError("Could not install update", actionError);
195 return false;
196 } catch (error) {
197 reportError(
198 "Could not install update",
199 error instanceof Error ? error.message : "An unexpected error occurred.",
200 );
201 return false;
202 }
203}
204
205/** Tooltip lines for a running pass: this app first, then one per machine. */
206function useUpdateRunTooltip(
207 run: UpdateEverythingRun | null,
208 state: DesktopUpdateState | null,
209 localReady: boolean,
210): string | null {
211 const statusesAtom = useMemo(
212 () =>
213 Atom.make((get) =>
214 run === null
215 ? []
216 : run.machines.map((machine) => ({
217 label: machine.label,
218 status: resolveUpdateRunMachineStatus(
219 machine,
220 run.phase,
221 get(serverEnvironment.updateStateAtom(machine.environmentId)),
222 ),
223 })),
224 ),
225 [run],
226 );
227 const statuses = useAtomValue(statusesAtom);
228 if (run === null) return null;
229 const local =
230 run.localVersion === null
231 ? null
232 : state?.status === "downloading"
233 ? `downloading${state.downloadPercent === null ? "" : ` ${Math.floor(state.downloadPercent)}%`}`
234 : run.phase === "installing"
235 ? "restarting"
236 : localReady
237 ? "restarts last"
238 : "waiting";
239 return describeUpdateRun(statuses, local).join("\n");
240}
241
242/**
243 * The sidebar update button. With only a local app update it downloads, then
244 * installs. When other machines' servers or any providers are behind, one
245 * click updates everything: providers, then servers, then this app last. On
246 * web there is no local app, so the button shows only for remote updates.
247 */
248export function SidebarUpdatePill() {
249 return <SidebarUpdateControl />;
250}
251
252function SidebarUpdateControl() {
253 const state = useDesktopUpdateState();
254 const [isActionPending, setIsActionPending] = useState(false);
255 const [isConfirmingEverything, setIsConfirmingEverything] = useState(false);
256 const [checkAnimationKey, setCheckAnimationKey] = useState(0);
257 const [isCheckAnimationLatched, setIsCheckAnimationLatched] = useState(false);
258 const [releaseNotesPopoverHandle] = useState(() => PopoverCreateHandle());
259 const suppressReleaseNotesFocusOpen = useRef(false);
260 const releaseNotesPopupRef = useRef<HTMLDivElement>(null);
261 const releaseNotesTriggerId = useId();
262 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
263
264 useEffect(() => {
265 if (prefersReducedMotion) {
266 setIsCheckAnimationLatched(false);
267 } else if (state?.status === "checking") {
268 setIsCheckAnimationLatched(true);
269 }
270 }, [prefersReducedMotion, state?.status]);
271
272 const action = state ? resolveDesktopUpdateButtonAction(state) : "none";
273 const isDownloading = state?.status === "downloading";
274 // Remote servers follow this app to the version it is about to install.
275 const localUpdateVersion =
276 state && action !== "none" ? getDesktopUpdateDownloadedVersion(state) : null;
277 const everything = useUpdateEverything(localUpdateVersion);
278 const runsEverything = everything.hasUpdates && !isDownloading;
279 // Providers leave the list once queued, so the run keeps its own state.
280 const run = useUpdateEverythingRun();
281 const isRunningEverything = run !== null;
282 const runTooltip = useUpdateRunTooltip(run, state, action === "install");
283 const showCheckIcon = shouldShowDesktopUpdateCheckIcon({
284 isAnimationLatched: isCheckAnimationLatched,
285 isChecking: state?.status === "checking",
286 prefersReducedMotion,
287 });
288 const { iconStatus, showUpdateDetails, showUpdateIconState } = resolveSidebarUpdatePresentation({
289 action,
290 showsEverything: runsEverything,
291 run,
292 isDownloading,
293 showCheckIcon,
294 });
295 const tooltip =
296 runTooltip !== null
297 ? runTooltip
298 : runsEverything
299 ? everything.summary
300 : showUpdateDetails
301 ? state
302 ? getDesktopUpdateButtonTooltip(state)
303 : "Update available"
304 : showCheckIcon
305 ? "Checking for updates…"
306 : "Check for updates";
307 const disabled = showCheckIcon
308 ? true
309 : runsEverything
310 ? false
311 : showUpdateDetails
312 ? isDesktopUpdateButtonDisabled(state)
313 : !canCheckForUpdate(state);
314 const isInteractionDisabled = disabled || isActionPending || isRunningEverything;
315 // During a run the tooltip shows its progress instead of release notes.
316 const showReleaseNotesPopover =
317 !isRunningEverything && shouldUseSidebarUpdateReleaseNotesPopover(showUpdateDetails, state);
318
319 useEffect(() => {
320 if (!showReleaseNotesPopover) {
321 releaseNotesPopoverHandle.close();
322 return;
323 }
324
325 const trigger = document.getElementById(releaseNotesTriggerId);
326 if (trigger?.matches(":focus-visible")) {
327 releaseNotesPopoverHandle.open(releaseNotesTriggerId);
328 }
329 }, [releaseNotesPopoverHandle, releaseNotesTriggerId, showReleaseNotesPopover]);
330
331 const handleAction = useCallback(async () => {
332 const bridge = window.desktopBridge;
333 if (isInteractionDisabled) return;
334
335 if (runsEverything) {
336 setIsConfirmingEverything(true);
337 return;
338 }
339
340 if (!bridge || !state) return;
341 setIsActionPending(true);
342
343 if (action === "download") {
344 void downloadLocalUpdate(bridge, { notifyDownloaded: true }).finally(() =>
345 setIsActionPending(false),
346 );
347 return;
348 }
349
350 if (action === "install") {
351 let confirmed = false;
352 try {
353 confirmed = await ensureLocalApi().dialogs.confirm(
354 getDesktopUpdateInstallConfirmationMessage(state),
355 );
356 } catch (error) {
357 setIsActionPending(false);
358 toastManager.add(
359 stackedThreadToast({
360 type: "error",
361 title: "Could not confirm update",
362 description: error instanceof Error ? error.message : "Update confirmation failed.",
363 }),
364 );
365 return;
366 }
367 if (!confirmed) {
368 setIsActionPending(false);
369 return;
370 }
371 void installLocalUpdate(bridge).finally(() => setIsActionPending(false));
372 return;
373 }
374
375 if (!prefersReducedMotion) {
376 setIsCheckAnimationLatched(true);
377 setCheckAnimationKey((key) => key + 1);
378 }
379 void bridge
380 .checkForUpdate()
381 .then((result) => {
382 if (result.checked) return;
383 toastManager.add(
384 stackedThreadToast({
385 type: "error",
386 title: "Could not check for updates",
387 description:
388 result.state.message ?? "Automatic updates are not available in this build.",
389 }),
390 );
391 })
392 .catch((error) => {
393 toastManager.add(
394 stackedThreadToast({
395 type: "error",
396 title: "Could not check for updates",
397 description: error instanceof Error ? error.message : "Update check failed.",
398 }),
399 );
400 })
401 .finally(() => setIsActionPending(false));
402 }, [action, isInteractionDisabled, prefersReducedMotion, runsEverything, state]);
403
404 const runEverything = useCallback(async () => {
405 const bridge = window.desktopBridge;
406 setIsConfirmingEverything(false);
407 setIsActionPending(true);
408 try {
409 await everything.run({
410 ...(bridge && action === "download"
411 ? {
412 downloadLocal: (reportError) =>
413 downloadLocalUpdate(bridge, { notifyDownloaded: false, reportError }),
414 }
415 : {}),
416 ...(bridge && action !== "none"
417 ? { installLocal: (reportError) => installLocalUpdate(bridge, reportError) }
418 : {}),
419 });
420 } catch (error) {
421 toastManager.add(
422 stackedThreadToast({
423 type: "error",
424 title: "Could not update everything",
425 description: error instanceof Error ? error.message : "An unexpected error occurred.",
426 }),
427 );
428 } finally {
429 setIsActionPending(false);
430 }
431 }, [action, everything]);
432
433 const handleCheckAnimationIteration = useCallback(() => {
434 setIsCheckAnimationLatched(
435 shouldContinueDesktopUpdateCheckAnimation({
436 isChecking: state?.status === "checking",
437 prefersReducedMotion,
438 }),
439 );
440 }, [prefersReducedMotion, state?.status]);
441
442 // Web has no local app to check, so it only shows the button for remote work.
443 if (!isElectron && !runsEverything && !isRunningEverything) return null;
444
445 const updateButton = (
446 <button
447 type="button"
448 aria-label={tooltip}
449 aria-disabled={isInteractionDisabled || undefined}
450 className={cn(
451 "inline-flex size-8 items-center justify-center rounded-full outline-hidden ring-ring transition-colors focus-visible:ring-2 focus-visible:ring-inset",
452 isInteractionDisabled ? "cursor-not-allowed" : "cursor-pointer",
453 showUpdateIconState
454 ? cn(
455 "bg-sidebar-control-surface text-sidebar-foreground",
456 !isInteractionDisabled && "hover:bg-sidebar-row-hover",
457 )
458 : cn(
459 "text-(--sidebar-icon-color)",
460 !isInteractionDisabled && "hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
461 ),
462 disabled && !showUpdateIconState && "opacity-60",
463 )}
464 onClick={handleAction}
465 onBlur={() => {
466 suppressReleaseNotesFocusOpen.current = false;
467 }}
468 onFocus={(event) => {
469 if (!showReleaseNotesPopover || !event.currentTarget.matches(":focus-visible")) return;
470 if (suppressReleaseNotesFocusOpen.current) {
471 suppressReleaseNotesFocusOpen.current = false;
472 return;
473 }
474 flushSync(() => releaseNotesPopoverHandle.open(releaseNotesTriggerId));
475 }}
476 onKeyDown={(event) => {
477 if (!showReleaseNotesPopover) return;
478 openSidebarUpdateReleaseNotesPopoverOnForwardTab(
479 event,
480 releaseNotesPopoverHandle,
481 releaseNotesTriggerId,
482 );
483 }}
484 >
485 <DesktopUpdateStatusIcon
486 key={showCheckIcon ? checkAnimationKey : iconStatus}
487 downloadPercent={state?.downloadPercent ?? null}
488 isCheckAnimating={showCheckIcon && !prefersReducedMotion}
489 onCheckAnimationIteration={handleCheckAnimationIteration}
490 status={iconStatus}
491 />
492 </button>
493 );
494
495 return (
496 <SidebarMenuItem className="ml-auto shrink-0">
497 <Popover
498 handle={releaseNotesPopoverHandle}
499 onOpenChange={(open, details) => {
500 if (open && !showReleaseNotesPopover) {
501 details.cancel();
502 return;
503 }
504 handleSidebarUpdateReleaseNotesPopoverOpenChange(open, details);
505 }}
506 >
507 <Tooltip disabled={showReleaseNotesPopover}>
508 <TooltipTrigger
509 id={releaseNotesTriggerId}
510 render={
511 <PopoverTrigger
512 {...(!showReleaseNotesPopover
513 ? {
514 "aria-controls": undefined,
515 "aria-expanded": undefined,
516 "aria-haspopup": undefined,
517 }
518 : {})}
519 closeDelay={150}
520 handle={releaseNotesPopoverHandle}
521 id={releaseNotesTriggerId}
522 openOnHover={showReleaseNotesPopover}
523 render={updateButton}
524 />
525 }
526 />
527 {!showReleaseNotesPopover ? (
528 <TooltipPopup
529 align="center"
530 side="top"
531 variant={showUpdateDetails ? "glass" : "default"}
532 >
533 <span className="whitespace-pre-line">{tooltip}</span>
534 </TooltipPopup>
535 ) : null}
536 </Tooltip>
537 {showReleaseNotesPopover && state ? (
538 <PopoverPopup
539 align="center"
540 aria-label="Nightly update release notes"
541 initialFocus={false}
542 onKeyDownCapture={(event) => {
543 if (
544 event.key === "Escape" &&
545 releaseNotesPopupRef.current?.contains(document.activeElement)
546 ) {
547 suppressReleaseNotesFocusOpen.current = true;
548 }
549 }}
550 ref={releaseNotesPopupRef}
551 side="top"
552 tooltipStyle
553 >
554 <SidebarUpdateReleaseNotes
555 shell={window.desktopBridge}
556 state={state}
557 tooltip={tooltip}
558 />
559 </PopoverPopup>
560 ) : null}
561 </Popover>
562 <UpdateEverythingDialog
563 open={isConfirmingEverything}
564 onOpenChange={setIsConfirmingEverything}
565 summary={everything.summary}
566 lines={everything.lines}
567 restarts={everything.restarts}
568 skipped={everything.skipped}
569 onConfirm={() => void runEverything()}
570 />
571 </SidebarMenuItem>
572 );
573}