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

UpdateTrackSwitchDialog.tsx

179 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, npmReleaseFailureMessage } 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 { localUpdaterStaysPut, 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)
55 ? npmReleaseFailureMessage(release.cause)
56 : AsyncResult.isSuccess(release)
57 ? `Could not find the latest ${label} release in this environment's npm registry.`
58 : "Checking releases…"}
59 </AlertDialogDescription>
60 </AlertDialogHeader>
61 <AlertDialogFooter>
62 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
63 </AlertDialogFooter>
64 </AlertDialogPopup>
65 </AlertDialog>
66 );
68​
69function SwitchPlan({
70 release,
71 onClose,
72}: {
73 readonly release: ChannelSwitchRelease;
74 readonly onClose: () => void;
75}) {
76 const updateState = useDesktopUpdateState();
77 const { environments } = useEnvironments();
78 const crossesLocal = desktopUpdateChannelOf(APP_VERSION) !== release.channel;
79 const updatesOff = localUpdaterStaysPut(updateState, release.channel);
80 // After a partial switch this app may already be on the track; then only remotes move.
81 const switchesLocal = crossesLocal && !updatesOff;
82 const [checking, setChecking] = useState(false);
83 const everything = useUpdateEverything(switchesLocal ? release.version : null, release);
84 const label = channelSwitchLabel(release.channel);
85 // This app's reinstall restarts every server it hosts, so each of their databases must allow it.
86 const localBlocked = localSwitchBlockReason(
87 APP_VERSION,
88 release,
89 environments.filter(isHostedByThisApp).map((environment) => ({
90 connected: environment.connection.phase === "connected",
91 databaseMigration: environment.serverConfig?.environment.databaseMigration,
92 })),
93 window.desktopBridge?.getLocalEnvironmentBootstraps().length ?? 0,
94 );
95​
96 const run = async () => {
97 const bridge = window.desktopBridge;
98 if (!bridge) return;
99 // Stay open while the feed is checked; the run's own progress takes over after.
100 setChecking(true);
101 const fail = (description: string) =>
102 toastManager.add(
103 stackedThreadToast({ type: "error", title: `Could not switch to ${label}`, description }),
104 );
105 const prepared = await prepareLocalTrackSwitch(bridge, {
106 channel: release.channel,
107 version: release.version,
108 reinstall: switchesLocal,
109 });
110 onClose();
111 if (!prepared.ok) {
112 fail(prepared.message);
113 return;
114 }
115 const { local } = prepared;
116 const result = await settlePromise(() =>
117 everything.run(
118 local === null
119 ? {}
120 : {
121 ...(local.status === "available"
122 ? {
123 downloadLocal: (reportError) =>
124 downloadLocalUpdate(bridge, { notifyDownloaded: false, reportError }),
125 }
126 : {}),
127 // Install only a build the database check covers, pinned so nothing replaces it.
128 installLocal: async (reportError) => {
129 const { downloadedVersion } = await bridge.getUpdateState();
130 if (
131 downloadedVersion === null ||
132 !acceptsTrackSwitchRelease(downloadedVersion, release.channel, release.version)
133 ) {
134 reportError(
135 "Could not install update",
136 `This app downloaded ${downloadedVersion ?? "nothing"}, not ${release.version} or newer.`,
137 );
138 return false;
139 }
140 return installLocalUpdate(bridge, reportError, downloadedVersion);
141 },
142 },
143 ),
144 );
145 if (result._tag === "Failure") {
146 const error = squashAtomCommandFailure(result);
147 fail(error instanceof Error ? error.message : "An unexpected error occurred.");
148 }
149 };
150​
151 return (
152 <UpdateEverythingDialog
153 open
154 onOpenChange={(open) => !open && !checking && onClose()}
155 title={`Switch to ${label}?`}
156 version={release.version}
157 providerCount={0}
158 rows={everything.rows}
159 notes={[
160 ...(everything.rows.length === 0 && !crossesLocal
161 ? [`Every connected machine is already on ${label}. This only saves the track.`]
162 : []),
163 ...(crossesLocal && updatesOff
164 ? ["This app's updates are off here, so reinstall it yourself to switch."]
165 : []),
166 ...(switchesLocal && isMacPlatform(navigator.platform)
167 ? ["If T3 Code does not reopen after it restarts, open it again."]
168 : []),
169 ]}
170 restarts={everything.restarts}
171 confirmLabel={checking ? "Checking…" : `Switch to ${label}`}
172 busy={checking}
173 disabledReason={
174 !switchesLocal || localBlocked === null ? null : `This app cannot switch: ${localBlocked}.`
175 }
176 onConfirm={() => void run()}
177 />
178 );