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