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

UpdateTrackSwitchDialog.tsx

178 lines6.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import type { DesktopUpdateChannel } from "@t3tools/contracts";
4import { acceptsTrackSwitchRelease, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
5import { isMacPlatform } from "@t3tools/shared/keybindings";
6import { useState } from "react";
7import { AsyncResult } from "effect/reactivity";
8​
9import { APP_VERSION } from "~/branding";
10import { useDesktopUpdateState } from "~/state/desktopUpdate";
11import { useEnvironments } from "~/state/environments";
12import { npmReleaseAtom } from "~/state/npmRelease";
13import { downloadLocalUpdate, installLocalUpdate } from "../sidebar/SidebarUpdatePill";
14import { UpdateEverythingDialog } from "../sidebar/UpdateEverythingDialog";
15import {
16 channelSwitchLabel,
17 localSwitchBlockReason,
18 type ChannelSwitchRelease,
19} from "../sidebar/updateEverything.logic";
20import { isHostedByThisApp, useUpdateEverything } from "../sidebar/useUpdateEverything";
21import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
22import {
23 AlertDialog,
24 AlertDialogClose,
25 AlertDialogDescription,
26 AlertDialogFooter,
27 AlertDialogHeader,
28 AlertDialogPopup,
29 AlertDialogTitle,
30} from "../ui/alert-dialog";
31import { Button } from "../ui/button";
32import { stackedThreadToast, toastManager } from "../ui/toast";
33​
34/** Moves this app and every connected machine to `channel`. */
35export function UpdateTrackSwitchDialog({
36 channel,
37 onClose,
38}: {
39 readonly channel: DesktopUpdateChannel;
40 readonly onClose: () => void;
41}) {
42 // npm dist-tags match the desktop channel names.
43 const release = useAtomValue(npmReleaseAtom(channel));
44 if (AsyncResult.isSuccess(release) && release.value !== null) {
45 return <SwitchPlan release={{ channel, ...release.value }} onClose={onClose} />;
46 }
47 const label = channelSwitchLabel(channel);
48 return (
49 <AlertDialog open onOpenChange={(open) => !open && onClose()}>
50 <AlertDialogPopup>
51 <AlertDialogHeader>
52 <AlertDialogTitle>Switch to {label}</AlertDialogTitle>
53 <AlertDialogDescription>
54 {AsyncResult.isFailure(release) || AsyncResult.isSuccess(release)
55 ? `Could not find the latest ${label} release on npm. Try again later.`
56 : "Checking releases…"}
57 </AlertDialogDescription>
58 </AlertDialogHeader>
59 <AlertDialogFooter>
60 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
61 </AlertDialogFooter>
62 </AlertDialogPopup>
63 </AlertDialog>
64 );
66​
67function SwitchPlan({
68 release,
69 onClose,
70}: {
71 readonly release: ChannelSwitchRelease;
72 readonly onClose: () => void;
73}) {
74 const updateState = useDesktopUpdateState();
75 const { environments } = useEnvironments();
76 const crossesLocal = desktopUpdateChannelOf(APP_VERSION) !== release.channel;
77 // With its updater off (a .deb install, or no feed) this app stays put and only remotes move.
78 const updatesOff = updateState?.enabled === false;
79 // After a partial switch this app may already be on the track; then only remotes move.
80 const switchesLocal = crossesLocal && !updatesOff;
81 const [checking, setChecking] = useState(false);
82 const everything = useUpdateEverything(switchesLocal ? release.version : null, release);
83 const label = channelSwitchLabel(release.channel);
84 // This app's reinstall restarts every server it hosts, so each of their databases must allow it.
85 const localBlocked = localSwitchBlockReason(
86 APP_VERSION,
87 release,
88 environments.filter(isHostedByThisApp).map((environment) => ({
89 connected: environment.connection.phase === "connected",
90 databaseMigration: environment.serverConfig?.environment.databaseMigration,
91 })),
92 window.desktopBridge?.getLocalEnvironmentBootstraps().length ?? 0,
93 );
94​
95 const run = async () => {
96 const bridge = window.desktopBridge;
97 if (!bridge) return;
98 // Stay open while the feed is checked; the run's own progress takes over after.
99 setChecking(true);
100 const fail = (description: string) =>
101 toastManager.add(
102 stackedThreadToast({ type: "error", title: `Could not switch to ${label}`, description }),
103 );
104 const prepared = await prepareLocalTrackSwitch(bridge, {
105 channel: release.channel,
106 version: release.version,
107 reinstall: switchesLocal,
108 });
109 onClose();
110 if (!prepared.ok) {
111 fail(prepared.message);
112 return;
113 }
114 const { local } = prepared;
115 const result = await settlePromise(() =>
116 everything.run(
117 local === null
118 ? {}
119 : {
120 ...(local.status === "available"
121 ? {
122 downloadLocal: (reportError) =>
123 downloadLocalUpdate(bridge, { notifyDownloaded: false, reportError }),
124 }
125 : {}),
126 // Install only a build the database check covers, pinned so nothing replaces it.
127 installLocal: async (reportError) => {
128 const { downloadedVersion } = await bridge.getUpdateState();
129 if (
130 downloadedVersion === null ||
131 !acceptsTrackSwitchRelease(downloadedVersion, release.channel, release.version)
132 ) {
133 reportError(
134 "Could not install update",
135 `This app downloaded ${downloadedVersion ?? "nothing"}, not ${release.version} or newer.`,
136 );
137 return false;
138 }
139 return installLocalUpdate(bridge, reportError, downloadedVersion);
140 },
141 },
142 ),
143 );
144 if (result._tag === "Failure") {
145 const error = squashAtomCommandFailure(result);
146 fail(error instanceof Error ? error.message : "An unexpected error occurred.");
147 }
148 };
149​
150 return (
151 <UpdateEverythingDialog
152 open
153 onOpenChange={(open) => !open && !checking && onClose()}
154 title={`Switch to ${label}?`}
155 version={release.version}
156 providerCount={0}
157 rows={everything.rows}
158 notes={[
159 ...(everything.rows.length === 0 && !crossesLocal
160 ? [`Every connected machine is already on ${label}. This only saves the track.`]
161 : []),
162 ...(crossesLocal && updatesOff
163 ? ["This app's updates are off here, so reinstall it yourself to switch."]
164 : []),
165 ...(switchesLocal && isMacPlatform(navigator.platform)
166 ? ["If T3 Code does not reopen after it restarts, open it again."]
167 : []),
168 ]}
169 restarts={everything.restarts}
170 confirmLabel={checking ? "Checking…" : `Switch to ${label}`}
171 busy={checking}
172 disabledReason={
173 !switchesLocal || localBlocked === null ? null : `This app cannot switch: ${localBlocked}.`
174 }
175 onConfirm={() => void run()}
176 />
177 );