Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderUpdatePrimaryNotification.tsx

335 lines10.7 KB

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 { 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 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 );
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 // Base UI merges toast updates and omits `undefined` keys, so `undefined`
72 // would leave the prompt's Update button in place. Replace it with a
73 // defined empty action so the CTA cannot linger while the update runs.
74 actionProps: hiddenToastActionProps,
75 data: {
76 hideCopyButton: true,
77 ...(input.view.dismissAfterVisibleMs !== undefined
78 ? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
79 : {}),
80 },
81 });
82 return;
83 }
84​
85 toastManager.update(
86 input.toastId,
87 stackedThreadToast({
88 type: input.view.type,
89 title: input.view.title,
90 description: input.view.description,
91 timeout: 0,
92 actionProps: {
93 children: "Settings",
94 onClick: input.openSettings,
95 },
96 actionVariant: "outline",
97 data: {
98 hideCopyButton: true,
99 },
100 }),
101 );
103​
104function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
105 return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
107​
108/**
109 * The single-prompt provider update notification used when there is only one
110 * local environment (no WSL backend). Non-WSL users see exactly this flow — the
111 * per-environment split is gated behind WSL presence.
112 */
113export function ProviderUpdatePrimaryNotification() {
114 const navigate = useNavigate();
115 const providers = useAtomValue(primaryServerProvidersAtom);
116 const primaryEnvironment = usePrimaryEnvironment();
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) {
130 toastManager.close(activeToast.toastId);
131 activeToastRef.current = null;
132 }
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) {
153 toastManager.close(activeToast.toastId);
154 }
155 if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
156 activeToastRef.current = null;
157 }
158 void navigate({ to: "/settings/providers" });
159 },
160 [navigate],
161 );
162​
163 useEffect(() => {
164 const activeToast = activeToastRef.current;
165 if (activeToast?.kind !== "update") {
166 return;
167 }
168​
169 const activeProviders = providers.filter((provider) =>
170 activeToast.providerInstanceIds.has(provider.instanceId),
171 );
172 const view = getProviderUpdateProgressToastView({
173 providers: activeProviders,
174 providerCount: activeToast.providerCount,
175 });
176 updateProviderUpdateToast({
177 toastId: activeToast.toastId,
178 view,
179 openSettings: () => openProviderSettings(activeToast.toastId),
180 });
181​
182 if (isTerminalProviderUpdateToastView(view)) {
183 activeToastRef.current = null;
184 }
185 }, [providers, openProviderSettings]);
186​
187 useEffect(() => {
188 const activeToast = activeToastRef.current;
189 if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
190 toastManager.close(activeToast.toastId);
191 activeToastRef.current = null;
192 }
193​
194 if (
195 !notificationKey ||
196 dismissedNotificationKeys.has(notificationKey) ||
197 seenProviderUpdateNotificationKeys.has(notificationKey) ||
198 activeToastRef.current
199 ) {
200 return;
201 }
202​
203 seenProviderUpdateNotificationKeys.add(notificationKey);
204​
205 const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
206​
207 let toastId!: ProviderUpdateToastId;
208 let updateStarted = false;
209 const openSettings = () => openProviderSettings(toastId);
210 const dismissPrompt = () => {
211 dismissNotificationKey(notificationKey);
212 };
213​
214 const runUpdates = () => {
215 if (updateStarted || oneClickProviders.length === 0 || !primaryEnvironment) {
216 return;
217 }
218 updateStarted = true;
219​
220 const providerCount = oneClickProviders.length;
221 const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
222 activeToastRef.current = {
223 kind: "update",
224 key: notificationKey,
225 toastId,
226 providerInstanceIds,
227 providerCount,
228 };
229​
230 updateProviderUpdateToast({
231 toastId,
232 view: getProviderUpdateRunningToastView(providerCount),
233 openSettings,
234 });
235​
236 void (async () => {
237 const results = [];
238 for (const provider of oneClickProviders) {
239 results.push(
240 await updateProvider({
241 environmentId: primaryEnvironment.environmentId,
242 input: {
243 provider: provider.driver,
244 instanceId: provider.instanceId,
245 },
246 }),
247 );
248 }
249​
250 const activeUpdateToast = activeToastRef.current;
251 if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
252 return;
253 }
254​
255 const failedMessage = firstFailedProviderUpdateMessage(results);
256 if (failedMessage) {
257 updateProviderUpdateToast({
258 toastId,
259 view: getProviderUpdateRejectedToastView(providerCount, failedMessage),
260 openSettings,
261 });
262 activeToastRef.current = null;
263 return;
264 }
265​
266 const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
267 results,
268 providerInstanceIds,
269 });
270 const view = getProviderUpdateProgressToastView({
271 providers: updatedProviderSnapshots,
272 providerCount,
273 });
274 updateProviderUpdateToast({
275 toastId,
276 view,
277 openSettings,
278 });
279​
280 if (isTerminalProviderUpdateToastView(view)) {
281 activeToastRef.current = null;
282 }
283 })();
284 };
285​
286 toastId = toastManager.add(
287 stackedThreadToast({
288 type: initialView.type,
289 title: initialView.title,
290 description: initialView.description,
291 timeout: 0,
292 actionProps:
293 oneClickProviders.length > 0
294 ? {
295 children: "Update",
296 onClick: runUpdates,
297 }
298 : {
299 children: "Settings",
300 onClick: openSettings,
301 },
302 actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
303 data: {
304 leadingIcon:
305 updateProviders.length === 1 ? (
306 <ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
307 ) : undefined,
308 hideCopyButton: true,
309 onClose: dismissPrompt,
310 ...(oneClickProviders.length > 0
311 ? {
312 secondaryActionProps: {
313 children: "Settings",
314 onClick: openSettings,
315 },
316 secondaryActionVariant: "outline" as const,
317 }
318 : {}),
319 },
320 }),
321 );
322 activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
323 }, [
324 updateProvider,
325 dismissNotificationKey,
326 dismissedNotificationKeys,
327 notificationKey,
328 oneClickProviders,
329 openProviderSettings,
330 primaryEnvironment,
331 updateProviders,
332 ]);
333​
334 return null;