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 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
104/**
105 * The single-prompt provider update notification used when there is only one
106 * local environment (no WSL backend). Non-WSL users see exactly this flow — the
107 * per-environment split is gated behind WSL presence.
108 */
109export function ProviderUpdatePrimaryNotification() {
110 const navigate = useNavigate();
111 const providers = useAtomValue(primaryServerProvidersAtom);
112 const primaryEnvironment = usePrimaryEnvironment();
113 const canManageProviders = useEnvironmentScope(
114 primaryEnvironment?.environmentId ?? null,
115 AuthProvidersManageScope,
116 );
117 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
118 reportFailure: false,
119 });
120 const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
121 const { dismissedNotificationKeys, dismissNotificationKey } =
122 useDismissedProviderUpdateNotificationKeys();
123
124 // If this flow unmounts (e.g. a WSL backend appears and we switch to the
125 // per-environment popover), close any prompt it owns so it does not linger.
126 useEffect(() => {
127 return () => {
128 const activeToast = activeToastRef.current;
129 if (activeToast?.kind === "prompt") {
130 toastManager.close(activeToast.toastId);
131 }
132 activeToastRef.current = null;
133 };
134 }, []);
135
136 const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
137 const notificationKey = useMemo(
138 () => providerUpdateNotificationKey(updateProviders),
139 [updateProviders],
140 );
141 const oneClickProviders = useMemo(
142 () =>
143 updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
144 [providers, updateProviders],
145 );
146
147 const openProviderSettings = useCallback(
148 (toastId?: ProviderUpdateToastId) => {
149 const activeToast = activeToastRef.current;
150 if (toastId !== undefined) {
151 toastManager.close(toastId);
152 } else if (activeToast?.kind === "prompt") {
153 toastManager.close(activeToast.toastId);
154 }
155 if (
156 activeToast &&
157 (toastId === undefined ||
158 (activeToast.kind === "prompt" && activeToast.toastId === toastId))
159 ) {
160 activeToastRef.current = null;
161 }
162 void navigate({ to: "/settings/providers" });
163 },
164 [navigate],
165 );
166
167 useEffect(() => {
168 const activeToast = activeToastRef.current;
169 if (activeToast?.kind !== "update") {
170 return;
171 }
172
173 const activeProviders = providers.filter((provider) =>
174 activeToast.providerInstanceIds.has(provider.instanceId),
175 );
176 const view = getProviderUpdateProgressToastView({
177 providers: activeProviders,
178 providerCount: activeToast.providerCount,
179 });
180 if (!shouldShowPrimaryProviderUpdateToast(view)) {
181 return;
182 }
183
184 addProviderUpdateToast({ view, openSettings: openProviderSettings });
185 activeToastRef.current = null;
186 }, [providers, openProviderSettings]);
187
188 useEffect(() => {
189 const activeToast = activeToastRef.current;
190 if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
191 toastManager.close(activeToast.toastId);
192 activeToastRef.current = null;
193 }
194
195 const updateExistingPrompt =
196 activeToast?.kind === "prompt" &&
197 activeToast.key === notificationKey &&
198 activeToast.canManageProviders !== canManageProviders;
199 if (
200 !notificationKey ||
201 dismissedNotificationKeys.has(notificationKey) ||
202 (seenProviderUpdateNotificationKeys.has(notificationKey) && !updateExistingPrompt) ||
203 (activeToastRef.current && !updateExistingPrompt)
204 ) {
205 return;
206 }
207
208 seenProviderUpdateNotificationKeys.add(notificationKey);
209
210 const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
211
212 let toastId!: ProviderUpdateToastId;
213 let updateStarted = false;
214 const openSettings = () => openProviderSettings(toastId);
215 const dismissPrompt = () => {
216 dismissNotificationKey(notificationKey);
217 };
218
219 const runUpdates = () => {
220 if (
221 updateStarted ||
222 oneClickProviders.length === 0 ||
223 !primaryEnvironment ||
224 !readEnvironmentScope(primaryEnvironment.environmentId, AuthProvidersManageScope)
225 ) {
226 return;
227 }
228 updateStarted = true;
229
230 const providerCount = oneClickProviders.length;
231 const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
232 const activeUpdate: ActiveProviderUpdateToast = {
233 kind: "update",
234 key: notificationKey,
235 providerInstanceIds,
236 providerCount,
237 };
238 activeToastRef.current = activeUpdate;
239
240 toastManager.close(toastId);
241
242 void (async () => {
243 const results = [];
244 for (const provider of oneClickProviders) {
245 if (!readEnvironmentScope(primaryEnvironment.environmentId, AuthProvidersManageScope)) {
246 if (activeToastRef.current === activeUpdate) {
247 addProviderUpdateToast({
248 view: getProviderUpdateRejectedToastView(
249 providerCount,
250 "This connection cannot manage provider accounts.",
251 ),
252 openSettings: openProviderSettings,
253 });
254 activeToastRef.current = null;
255 }
256 return;
257 }
258 results.push(
259 await updateProvider({
260 environmentId: primaryEnvironment.environmentId,
261 input: {
262 provider: provider.driver,
263 instanceId: provider.instanceId,
264 },
265 }),
266 );
267 }
268
269 const activeUpdateToast = activeToastRef.current;
270 if (activeUpdateToast !== activeUpdate) {
271 return;
272 }
273
274 const failedMessage = firstFailedProviderUpdateMessage(results);
275 if (failedMessage) {
276 addProviderUpdateToast({
277 view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
278 openSettings: openProviderSettings,
279 });
280 activeToastRef.current = null;
281 return;
282 }
283
284 const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
285 results,
286 providerInstanceIds,
287 });
288 const view = getProviderUpdateProgressToastView({
289 providers: updatedProviderSnapshots,
290 providerCount,
291 });
292 if (shouldShowPrimaryProviderUpdateToast(view)) {
293 addProviderUpdateToast({ view, openSettings: openProviderSettings });
294 activeToastRef.current = null;
295 }
296 })();
297 };
298
299 const toastOptions = stackedThreadToast({
300 type: initialView.type,
301 title: initialView.title,
302 description: canManageProviders
303 ? initialView.description
304 : "This connection cannot manage provider accounts. View provider settings for update details.",
305 timeout: 0,
306 actionProps:
307 oneClickProviders.length > 0
308 ? {
309 children: "Update",
310 disabled: !canManageProviders,
311 onClick: runUpdates,
312 }
313 : {
314 children: "Settings",
315 onClick: openSettings,
316 },
317 actionVariant: "outline",
318 data: {
319 leadingIcon:
320 updateProviders.length === 1 ? (
321 <ProviderUpdateToastIcon provider={updateProviders[0]!} />
322 ) : undefined,
323 hideCopyButton: true,
324 onClose: dismissPrompt,
325 ...(oneClickProviders.length > 0
326 ? {
327 secondaryActionProps: {
328 children: "Settings",
329 onClick: openSettings,
330 },
331 secondaryActionVariant: "outline" as const,
332 }
333 : {}),
334 },
335 });
336 if (updateExistingPrompt && activeToast?.kind === "prompt") {
337 toastId = activeToast.toastId;
338 toastManager.update(toastId, toastOptions);
339 } else {
340 toastId = toastManager.add(toastOptions);
341 }
342 activeToastRef.current = { kind: "prompt", key: notificationKey, toastId, canManageProviders };
343 }, [
344 canManageProviders,
345 updateProvider,
346 dismissNotificationKey,
347 dismissedNotificationKeys,
348 notificationKey,
349 oneClickProviders,
350 openProviderSettings,
351 primaryEnvironment,
352 updateProviders,
353 ]);
354
355 return null;
356}