Open History to see the last commit
1import { useNavigate } from "@tanstack/react-router";
2import { useAtomValue } from "@effect/atom-react";
3import { DownloadIcon } from "lucide-react";
4import { useCallback, useEffect, useMemo, useRef } from "react";
5import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
6
7import { primaryServerProvidersAtom, serverEnvironment } from "../state/server";
8import { usePrimaryEnvironment } from "../state/environments";
9import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
10import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";
11import {
12 canOneClickUpdateProviderCandidate,
13 collectProviderUpdateCandidates,
14 collectUpdatedProviderSnapshots,
15 firstFailedProviderUpdateMessage,
16 getProviderUpdateInitialToastView,
17 getProviderUpdateProgressToastView,
18 getProviderUpdateRejectedToastView,
19 getProviderUpdateRunningToastView,
20 providerUpdateNotificationKey,
21 type ProviderUpdateToastView,
22} from "./ProviderUpdateLaunchNotification.logic";
23import { stackedThreadToast, toastManager } from "./ui/toast";
24import { useAtomCommand } from "../state/use-atom-command";
25
26const seenProviderUpdateNotificationKeys = new Set<string>();
27type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
28
29type ActiveProviderUpdateToast =
30 | { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
31 | {
32 readonly kind: "update";
33 readonly key: string;
34 readonly toastId: ProviderUpdateToastId;
35 readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
36 readonly providerCount: number;
37 };
38
39function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
40 const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
41
42 if (!ProviderIcon) {
43 return (
44 <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
45 <DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
46 </span>
47 );
48 }
49
50 return (
51 <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
52 <ProviderIcon aria-hidden="true" className="size-4" />
53 <span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
54 <DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
55 </span>
56 </span>
57 );
58}
59
60function updateProviderUpdateToast(input: {
61 readonly toastId: ProviderUpdateToastId;
62 readonly view: ProviderUpdateToastView;
63 readonly openSettings: () => void;
64}) {
65 if (input.view.type === "loading" || input.view.type === "success") {
66 toastManager.update(input.toastId, {
67 type: input.view.type,
68 title: input.view.title,
69 description: input.view.description,
70 timeout: 0,
71 data: {
72 hideCopyButton: true,
73 ...(input.view.dismissAfterVisibleMs !== undefined
74 ? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
75 : {}),
76 },
77 });
78 return;
79 }
80
81 toastManager.update(
82 input.toastId,
83 stackedThreadToast({
84 type: input.view.type,
85 title: input.view.title,
86 description: input.view.description,
87 timeout: 0,
88 actionProps: {
89 children: "Settings",
90 onClick: input.openSettings,
91 },
92 actionVariant: "outline",
93 data: {
94 hideCopyButton: true,
95 },
96 }),
97 );
98}
99
100function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
101 return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
102}
103
104export function ProviderUpdateLaunchNotification() {
105 const navigate = useNavigate();
106 const providers = useAtomValue(primaryServerProvidersAtom);
107 const primaryEnvironment = usePrimaryEnvironment();
108 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
109 reportFailure: false,
110 });
111 const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
112 const { dismissedNotificationKeys, dismissNotificationKey } =
113 useDismissedProviderUpdateNotificationKeys();
114
115 const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
116 const notificationKey = useMemo(
117 () => providerUpdateNotificationKey(updateProviders),
118 [updateProviders],
119 );
120 const oneClickProviders = useMemo(
121 () =>
122 updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
123 [providers, updateProviders],
124 );
125
126 const openProviderSettings = useCallback(
127 (toastId?: ProviderUpdateToastId) => {
128 const activeToast = activeToastRef.current;
129 if (toastId !== undefined) {
130 toastManager.close(toastId);
131 } else if (activeToast) {
132 toastManager.close(activeToast.toastId);
133 }
134 if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
135 activeToastRef.current = null;
136 }
137 void navigate({ to: "/settings/providers" });
138 },
139 [navigate],
140 );
141
142 useEffect(() => {
143 const activeToast = activeToastRef.current;
144 if (activeToast?.kind !== "update") {
145 return;
146 }
147
148 const activeProviders = providers.filter((provider) =>
149 activeToast.providerInstanceIds.has(provider.instanceId),
150 );
151 const view = getProviderUpdateProgressToastView({
152 providers: activeProviders,
153 providerCount: activeToast.providerCount,
154 });
155 updateProviderUpdateToast({
156 toastId: activeToast.toastId,
157 view,
158 openSettings: () => openProviderSettings(activeToast.toastId),
159 });
160
161 if (isTerminalProviderUpdateToastView(view)) {
162 activeToastRef.current = null;
163 }
164 }, [providers, openProviderSettings]);
165
166 useEffect(() => {
167 const activeToast = activeToastRef.current;
168 if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
169 toastManager.close(activeToast.toastId);
170 activeToastRef.current = null;
171 }
172
173 if (
174 !notificationKey ||
175 dismissedNotificationKeys.has(notificationKey) ||
176 seenProviderUpdateNotificationKeys.has(notificationKey) ||
177 activeToastRef.current
178 ) {
179 return;
180 }
181
182 seenProviderUpdateNotificationKeys.add(notificationKey);
183
184 const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
185
186 let toastId!: ProviderUpdateToastId;
187 let updateStarted = false;
188 const openSettings = () => openProviderSettings(toastId);
189 const dismissPrompt = () => {
190 dismissNotificationKey(notificationKey);
191 };
192
193 const runUpdates = () => {
194 if (updateStarted || oneClickProviders.length === 0 || !primaryEnvironment) {
195 return;
196 }
197 updateStarted = true;
198
199 const providerCount = oneClickProviders.length;
200 const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
201 activeToastRef.current = {
202 kind: "update",
203 key: notificationKey,
204 toastId,
205 providerInstanceIds,
206 providerCount,
207 };
208
209 updateProviderUpdateToast({
210 toastId,
211 view: getProviderUpdateRunningToastView(providerCount),
212 openSettings,
213 });
214
215 void (async () => {
216 const results = [];
217 for (const provider of oneClickProviders) {
218 results.push(
219 await updateProvider({
220 environmentId: primaryEnvironment.environmentId,
221 input: {
222 provider: provider.driver,
223 instanceId: provider.instanceId,
224 },
225 }),
226 );
227 }
228
229 const activeUpdateToast = activeToastRef.current;
230 if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
231 return;
232 }
233
234 const failedMessage = firstFailedProviderUpdateMessage(results);
235 if (failedMessage) {
236 updateProviderUpdateToast({
237 toastId,
238 view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
239 openSettings,
240 });
241 activeToastRef.current = null;
242 return;
243 }
244
245 const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
246 results,
247 providerInstanceIds,
248 });
249 const view = getProviderUpdateProgressToastView({
250 providers: updatedProviderSnapshots,
251 providerCount,
252 });
253 updateProviderUpdateToast({
254 toastId,
255 view,
256 openSettings,
257 });
258
259 if (isTerminalProviderUpdateToastView(view)) {
260 activeToastRef.current = null;
261 }
262 })();
263 };
264
265 toastId = toastManager.add(
266 stackedThreadToast({
267 type: initialView.type,
268 title: initialView.title,
269 description: initialView.description,
270 timeout: 0,
271 actionProps:
272 oneClickProviders.length > 0
273 ? {
274 children: "Update",
275 onClick: runUpdates,
276 }
277 : {
278 children: "Settings",
279 onClick: openSettings,
280 },
281 actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
282 data: {
283 leadingIcon:
284 updateProviders.length === 1 ? (
285 <ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
286 ) : undefined,
287 hideCopyButton: true,
288 onClose: dismissPrompt,
289 ...(oneClickProviders.length > 0
290 ? {
291 secondaryActionProps: {
292 children: "Settings",
293 onClick: openSettings,
294 },
295 secondaryActionVariant: "outline" as const,
296 }
297 : {}),
298 },
299 }),
300 );
301 activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
302 }, [
303 updateProvider,
304 dismissNotificationKey,
305 dismissedNotificationKeys,
306 notificationKey,
307 oneClickProviders,
308 openProviderSettings,
309 primaryEnvironment,
310 updateProviders,
311 ]);
312
313 return null;
314}