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 providerUpdateNotificationKey,
20 shouldShowPrimaryProviderUpdateToast,
21 type ProviderUpdateToastView,
22} from "./ProviderUpdateLaunchNotification.logic";
23import { hiddenToastActionProps, 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 providerInstanceIds: ReadonlySet<ProviderInstanceId>;
35 readonly providerCount: number;
36 };
37
38function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
39 const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
40
41 if (!ProviderIcon) {
42 return (
43 <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
44 <DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
45 </span>
46 );
47 }
48
49 return (
50 <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
51 <ProviderIcon aria-hidden="true" className="size-4" />
52 <span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
53 <DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
54 </span>
55 </span>
56 );
57}
58
59function addProviderUpdateToast(input: {
60 readonly view: ProviderUpdateToastView;
61 readonly openSettings: (toastId: ProviderUpdateToastId) => void;
62}) {
63 if (input.view.type === "loading" || input.view.type === "success") {
64 return toastManager.add({
65 type: input.view.type,
66 title: input.view.title,
67 description: input.view.description,
68 timeout: 0,
69 actionProps: hiddenToastActionProps,
70 data: {
71 hideCopyButton: true,
72 ...(input.view.dismissAfterVisibleMs !== undefined
73 ? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
74 : {}),
75 },
76 });
77 }
78
79 let toastId!: ProviderUpdateToastId;
80 toastId = toastManager.add(
81 stackedThreadToast({
82 type: input.view.type,
83 title: input.view.title,
84 description: input.view.description,
85 timeout: 0,
86 actionProps: {
87 children: "Settings",
88 onClick: () => input.openSettings(toastId),
89 },
90 actionVariant: "outline",
91 data: {
92 hideCopyButton: true,
93 },
94 }),
95 );
96 return toastId;
97}
98
99/**
100 * The single-prompt provider update notification used when there is only one
101 * local environment (no WSL backend). Non-WSL users see exactly this flow — the
102 * per-environment split is gated behind WSL presence.
103 */
104export function ProviderUpdatePrimaryNotification() {
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 // If this flow unmounts (e.g. a WSL backend appears and we switch to the
116 // per-environment popover), close any prompt it owns so it does not linger.
117 useEffect(() => {
118 return () => {
119 const activeToast = activeToastRef.current;
120 if (activeToast?.kind === "prompt") {
121 toastManager.close(activeToast.toastId);
122 }
123 activeToastRef.current = null;
124 };
125 }, []);
126
127 const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
128 const notificationKey = useMemo(
129 () => providerUpdateNotificationKey(updateProviders),
130 [updateProviders],
131 );
132 const oneClickProviders = useMemo(
133 () =>
134 updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
135 [providers, updateProviders],
136 );
137
138 const openProviderSettings = useCallback(
139 (toastId?: ProviderUpdateToastId) => {
140 const activeToast = activeToastRef.current;
141 if (toastId !== undefined) {
142 toastManager.close(toastId);
143 } else if (activeToast?.kind === "prompt") {
144 toastManager.close(activeToast.toastId);
145 }
146 if (
147 activeToast &&
148 (toastId === undefined ||
149 (activeToast.kind === "prompt" && activeToast.toastId === toastId))
150 ) {
151 activeToastRef.current = null;
152 }
153 void navigate({ to: "/settings/providers" });
154 },
155 [navigate],
156 );
157
158 useEffect(() => {
159 const activeToast = activeToastRef.current;
160 if (activeToast?.kind !== "update") {
161 return;
162 }
163
164 const activeProviders = providers.filter((provider) =>
165 activeToast.providerInstanceIds.has(provider.instanceId),
166 );
167 const view = getProviderUpdateProgressToastView({
168 providers: activeProviders,
169 providerCount: activeToast.providerCount,
170 });
171 if (!shouldShowPrimaryProviderUpdateToast(view)) {
172 return;
173 }
174
175 addProviderUpdateToast({ view, openSettings: openProviderSettings });
176 activeToastRef.current = null;
177 }, [providers, openProviderSettings]);
178
179 useEffect(() => {
180 const activeToast = activeToastRef.current;
181 if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
182 toastManager.close(activeToast.toastId);
183 activeToastRef.current = null;
184 }
185
186 if (
187 !notificationKey ||
188 dismissedNotificationKeys.has(notificationKey) ||
189 seenProviderUpdateNotificationKeys.has(notificationKey) ||
190 activeToastRef.current
191 ) {
192 return;
193 }
194
195 seenProviderUpdateNotificationKeys.add(notificationKey);
196
197 const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
198
199 let toastId!: ProviderUpdateToastId;
200 let updateStarted = false;
201 const openSettings = () => openProviderSettings(toastId);
202 const dismissPrompt = () => {
203 dismissNotificationKey(notificationKey);
204 };
205
206 const runUpdates = () => {
207 if (updateStarted || oneClickProviders.length === 0 || !primaryEnvironment) {
208 return;
209 }
210 updateStarted = true;
211
212 const providerCount = oneClickProviders.length;
213 const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
214 const activeUpdate: ActiveProviderUpdateToast = {
215 kind: "update",
216 key: notificationKey,
217 providerInstanceIds,
218 providerCount,
219 };
220 activeToastRef.current = activeUpdate;
221
222 toastManager.close(toastId);
223
224 void (async () => {
225 const results = [];
226 for (const provider of oneClickProviders) {
227 results.push(
228 await updateProvider({
229 environmentId: primaryEnvironment.environmentId,
230 input: {
231 provider: provider.driver,
232 instanceId: provider.instanceId,
233 },
234 }),
235 );
236 }
237
238 const activeUpdateToast = activeToastRef.current;
239 if (activeUpdateToast !== activeUpdate) {
240 return;
241 }
242
243 const failedMessage = firstFailedProviderUpdateMessage(results);
244 if (failedMessage) {
245 addProviderUpdateToast({
246 view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
247 openSettings: openProviderSettings,
248 });
249 activeToastRef.current = null;
250 return;
251 }
252
253 const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
254 results,
255 providerInstanceIds,
256 });
257 const view = getProviderUpdateProgressToastView({
258 providers: updatedProviderSnapshots,
259 providerCount,
260 });
261 if (shouldShowPrimaryProviderUpdateToast(view)) {
262 addProviderUpdateToast({ view, openSettings: openProviderSettings });
263 activeToastRef.current = null;
264 }
265 })();
266 };
267
268 toastId = toastManager.add(
269 stackedThreadToast({
270 type: initialView.type,
271 title: initialView.title,
272 description: initialView.description,
273 timeout: 0,
274 actionProps:
275 oneClickProviders.length > 0
276 ? {
277 children: "Update",
278 onClick: runUpdates,
279 }
280 : {
281 children: "Settings",
282 onClick: openSettings,
283 },
284 actionVariant: "outline",
285 data: {
286 leadingIcon:
287 updateProviders.length === 1 ? (
288 <ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
289 ) : undefined,
290 hideCopyButton: true,
291 onClose: dismissPrompt,
292 ...(oneClickProviders.length > 0
293 ? {
294 secondaryActionProps: {
295 children: "Settings",
296 onClick: openSettings,
297 },
298 secondaryActionVariant: "outline" as const,
299 }
300 : {}),
301 },
302 }),
303 );
304 activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
305 }, [
306 updateProvider,
307 dismissNotificationKey,
308 dismissedNotificationKeys,
309 notificationKey,
310 oneClickProviders,
311 openProviderSettings,
312 primaryEnvironment,
313 updateProviders,
314 ]);
315
316 return null;
317}