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

UpdateTrackSwitchDialog.tsx

217 lines7.8 KB

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