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