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 { useEffect, 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 = collectProviderUpdateCandidates(providers);
130 const notificationKey = providerUpdateNotificationKey(updateProviders);
131 const oneClickProviders = updateProviders.filter((provider) =>
132 canOneClickUpdateProviderCandidate(provider, providers),
133 );
134
135 const openProviderSettings = (toastId?: ProviderUpdateToastId) => {
136 const activeToast = activeToastRef.current;
137 if (toastId !== undefined) {
138 toastManager.close(toastId);
139 } else if (activeToast?.kind === "prompt") {
140 toastManager.close(activeToast.toastId);
141 }
142 if (
143 activeToast &&
144 (toastId === undefined || (activeToast.kind === "prompt" && activeToast.toastId === toastId))
145 ) {
146 activeToastRef.current = null;
147 }
148 void navigate({ to: "/settings/providers" });
149 };
150
151 useEffect(() => {
152 const activeToast = activeToastRef.current;
153 if (activeToast?.kind !== "update") {
154 return;
155 }
156
157 const activeProviders = providers.filter((provider) =>
158 activeToast.providerInstanceIds.has(provider.instanceId),
159 );
160 const view = getProviderUpdateProgressToastView({
161 providers: activeProviders,
162 providerCount: activeToast.providerCount,
163 });
164 if (!shouldShowPrimaryProviderUpdateToast(view)) {
165 return;
166 }
167
168 addProviderUpdateToast({ view, openSettings: openProviderSettings });
169 activeToastRef.current = null;
170 }, [providers, openProviderSettings]);
171
172 useEffect(() => {
173 const activeToast = activeToastRef.current;
174 if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
175 toastManager.close(activeToast.toastId);
176 activeToastRef.current = null;
177 }
178
179 const updateExistingPrompt =
180 activeToast?.kind === "prompt" &&
181 activeToast.key === notificationKey &&
182 activeToast.canManageProviders !== canManageProviders;
183 if (
184 !notificationKey ||
185 dismissedNotificationKeys.has(notificationKey) ||
186 (seenProviderUpdateNotificationKeys.has(notificationKey) && !updateExistingPrompt) ||
187 (activeToastRef.current && !updateExistingPrompt)
188 ) {
189 return;
190 }
191
192 seenProviderUpdateNotificationKeys.add(notificationKey);
193
194 const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
195
196 let toastId!: ProviderUpdateToastId;
197 let updateStarted = false;
198 const openSettings = () => openProviderSettings(toastId);
199 const dismissPrompt = () => {
200 dismissNotificationKey(notificationKey);
201 };
202
203 const runUpdates = () => {
204 if (
205 updateStarted ||
206 oneClickProviders.length === 0 ||
207 !primaryEnvironment ||
208 !readEnvironmentScope(primaryEnvironment.environmentId, AuthProvidersManageScope)
209 ) {
210 return;
211 }
212 updateStarted = true;
213
214 const providerCount = oneClickProviders.length;
215 const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
216 const activeUpdate: ActiveProviderUpdateToast = {
217 kind: "update",
218 key: notificationKey,
219 providerInstanceIds,
220 providerCount,
221 };
222 activeToastRef.current = activeUpdate;
223
224 toastManager.close(toastId);
225
226 void (async () => {
227 const results = [];
228 for (const provider of oneClickProviders) {
229 if (!readEnvironmentScope(primaryEnvironment.environmentId, AuthProvidersManageScope)) {
230 if (activeToastRef.current === activeUpdate) {
231 addProviderUpdateToast({
232 view: getProviderUpdateRejectedToastView(
233 providerCount,
234 "This connection cannot manage provider accounts.",
235 ),
236 openSettings: openProviderSettings,
237 });
238 activeToastRef.current = null;
239 }
240 return;
241 }
242 results.push(
243 await updateProvider({
244 environmentId: primaryEnvironment.environmentId,
245 input: {
246 provider: provider.driver,
247 instanceId: provider.instanceId,
248 },
249 }),
250 );
251 }
252
253 const activeUpdateToast = activeToastRef.current;
254 if (activeUpdateToast !== activeUpdate) {
255 return;
256 }
257
258 const failedMessage = firstFailedProviderUpdateMessage(results);
259 if (failedMessage) {
260 addProviderUpdateToast({
261 view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
262 openSettings: openProviderSettings,
263 });
264 activeToastRef.current = null;
265 return;
266 }
267
268 const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
269 results,
270 providerInstanceIds,
271 });
272 const view = getProviderUpdateProgressToastView({
273 providers: updatedProviderSnapshots,
274 providerCount,
275 });
276 if (shouldShowPrimaryProviderUpdateToast(view)) {
277 addProviderUpdateToast({ view, openSettings: openProviderSettings });
278 activeToastRef.current = null;
279 }
280 })();
281 };
282
283 const toastOptions = stackedThreadToast({
284 type: initialView.type,
285 title: initialView.title,
286 description: canManageProviders
287 ? initialView.description
288 : "This connection cannot manage provider accounts. View provider settings for update details.",
289 timeout: 0,
290 actionProps:
291 oneClickProviders.length > 0
292 ? {
293 children: "Update",
294 disabled: !canManageProviders,
295 onClick: runUpdates,
296 }
297 : {
298 children: "Settings",
299 onClick: openSettings,
300 },
301 actionVariant: "outline",
302 data: {
303 leadingIcon:
304 updateProviders.length === 1 ? (
305 <ProviderUpdateToastIcon provider={updateProviders[0]!} />
306 ) : undefined,
307 hideCopyButton: true,
308 onClose: dismissPrompt,
309 ...(oneClickProviders.length > 0
310 ? {
311 secondaryActionProps: {
312 children: "Settings",
313 onClick: openSettings,
314 },
315 secondaryActionVariant: "outline" as const,
316 }
317 : {}),
318 },
319 });
320 if (updateExistingPrompt && activeToast?.kind === "prompt") {
321 toastId = activeToast.toastId;
322 toastManager.update(toastId, toastOptions);
323 } else {
324 toastId = toastManager.add(toastOptions);
325 }
326 activeToastRef.current = { kind: "prompt", key: notificationKey, toastId, canManageProviders };
327 }, [
328 canManageProviders,
329 updateProvider,
330 dismissNotificationKey,
331 dismissedNotificationKeys,
332 notificationKey,
333 oneClickProviders,
334 openProviderSettings,
335 primaryEnvironment,
336 updateProviders,
337 ]);
338
339 return null;
340}