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

UpdateTrackSwitchDialog.tsx

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