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

UpdateTrackSwitchDialog.tsx

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