Open History to see the last commit
1import { CheckIcon } from "lucide-react";
2import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
3import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7 type AtomCommandResult,
8} from "@t3tools/client-runtime/state/runtime";
9
10import { cn } from "~/lib/utils";
11import { serverEnvironment } from "~/state/server";
12import { useAtomCommand } from "~/state/use-atom-command";
13import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";
14import {
15 collectProviderUpdateOutcomeSnapshots,
16 firstRejectedProviderUpdateMessage,
17 getProviderUpdateProgressToastView,
18 getProviderUpdateSidebarPillView,
19 isTerminalProviderUpdatePhase,
20 resolveEnvironmentUpdateRowStatus,
21 type LocalEnvironmentUpdateGroup,
22 type LocalProviderUpdateOutcome,
23 type ProviderUpdateRowStatus,
24 type ProviderUpdateRowStatusKind,
25 type ProviderUpdateToastView,
26} from "./ProviderUpdateLaunchNotification.logic";
27import { Button } from "./ui/button";
28import { Spinner } from "./ui/spinner";
29
30type ProviderUpdateCommandResult = AtomCommandResult<
31 { readonly providers: ReadonlyArray<ServerProvider> },
32 unknown
33>;
34
35/**
36 * Map one targeted instance's update command result into the settled-outcome
37 * shape the multi-backend reducers consume: a non-interrupted failure becomes a
38 * rejection carrying its message; a success carries the post-update snapshot of
39 * the targeted instance (null when the backend did not report it).
40 */
41function toProviderUpdateOutcome(input: {
42 readonly environmentId: EnvironmentId;
43 readonly isPrimary: boolean;
44 readonly target: {
45 readonly driver: ServerProvider["driver"];
46 readonly instanceId: ServerProvider["instanceId"];
47 };
48 readonly result: ProviderUpdateCommandResult;
49}): PromiseSettledResult<LocalProviderUpdateOutcome> {
50 if (input.result._tag === "Failure") {
51 if (isAtomCommandInterrupted(input.result)) {
52 // An interrupted dispatch (e.g. superseded) is neither a success nor a
53 // hard failure — surface it as a non-contributing, non-rejecting outcome.
54 return {
55 status: "fulfilled",
56 value: {
57 environmentId: input.environmentId,
58 isPrimary: input.isPrimary,
59 driver: input.target.driver,
60 instanceId: input.target.instanceId,
61 provider: null,
62 },
63 };
64 }
65 const error = squashAtomCommandFailure(input.result);
66 return {
67 status: "rejected",
68 reason: error instanceof Error ? error : new Error("Provider update failed."),
69 };
70 }
71
72 const provider =
73 input.result.value.providers.find(
74 (candidate) => candidate.instanceId === input.target.instanceId,
75 ) ?? null;
76 return {
77 status: "fulfilled",
78 value: {
79 environmentId: input.environmentId,
80 isPrimary: input.isPrimary,
81 driver: input.target.driver,
82 instanceId: input.target.instanceId,
83 provider,
84 },
85 };
86}
87
88// Transport-hang safety net. The dispatch's `finally` clears the spinner and the
89// in-flight guard on completion, so this only matters if a request never resolves
90// at all (e.g. the socket drops mid-flight without surfacing an error). Keep it
91// well beyond the server's own update timeout (5 min) so a legitimately slow
92// update (npm installs routinely run tens of seconds) is never cut off and left
93// showing a dead, unresponsive Update button.
94const PENDING_EXPIRY_MS = 6 * 60_000;
95
96function rowToneClass(kind: ProviderUpdateRowStatusKind): string {
97 switch (kind) {
98 case "failed":
99 return "text-destructive";
100 case "unchanged":
101 return "text-warning";
102 case "success":
103 return "text-success";
104 default:
105 return "text-muted-foreground";
106 }
107}
108
109function EnvironmentUpdateRow({
110 group,
111 status,
112 onUpdate,
113}: {
114 readonly group: LocalEnvironmentUpdateGroup;
115 readonly status: ProviderUpdateRowStatus;
116 readonly onUpdate: () => void;
117}) {
118 let trailing: ReactNode;
119 switch (status.kind) {
120 case "loading":
121 trailing = <Spinner className="size-4 text-muted-foreground" />;
122 break;
123 case "success":
124 trailing = <CheckIcon aria-hidden="true" className="size-4 text-success" />;
125 break;
126 case "failed":
127 case "unchanged":
128 trailing = (
129 <Button size="xs" variant="outline" onClick={onUpdate}>
130 Retry
131 </Button>
132 );
133 break;
134 default:
135 trailing = (
136 <Button size="xs" onClick={onUpdate}>
137 Update
138 </Button>
139 );
140 break;
141 }
142
143 return (
144 <div className="flex items-center justify-between gap-3 py-0.5">
145 <div className="flex min-w-0 flex-col">
146 <span className="truncate font-medium text-foreground">{group.label}</span>
147 <span className={cn("truncate text-xs", rowToneClass(status.kind))}>{status.text}</span>
148 </div>
149 <div className="shrink-0">{trailing}</div>
150 </div>
151 );
152}
153
154/**
155 * The launch popover's body when WSL is present: one row per local environment
156 * (Windows + WSL), each with its own "update all" trigger that targets only
157 * that environment's backend.
158 */
159export function ProviderUpdateEnvironmentRows({
160 onInteract,
161}: {
162 /** Called the first time the user triggers an update, so the host can stop refreshing the prompt. */
163 readonly onInteract?: () => void;
164}) {
165 const { groups } = useLocalEnvironmentUpdateGroups();
166 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
167 reportFailure: false,
168 });
169 const groupByEnvironment = useMemo(
170 () => new Map(groups.map((group) => [group.environmentId, group] as const)),
171 [groups],
172 );
173
174 // Only surface results that land after this popover opened.
175 const visibleAfterIsoRef = useRef<string>(new Date().toISOString());
176
177 // Synchronous re-entry guard. setPendingEnvironments is an async state update,
178 // and PENDING_EXPIRY_MS can clear the spinner while a request is still in
179 // flight, so a rapid double-click (or a click after the expiry fires mid-
180 // request) would otherwise dispatch a second full round of updates. A ref
181 // updates synchronously, so we can bail before doing any work.
182 const inFlightEnvironmentsRef = useRef<Set<EnvironmentId>>(new Set());
183
184 // Monotonic per-environment request version. Bumped on each dispatch and
185 // captured locally, so an attempt that was superseded -- e.g. one that already
186 // tripped the expiry safety net and was retried -- detects it is no longer
187 // current and skips every state write when it finally resolves, instead of
188 // clobbering the newer attempt's spinner/result/error or its in-flight guard.
189 const requestVersionRef = useRef<Map<EnvironmentId, number>>(new Map());
190
191 const [pendingEnvironments, setPendingEnvironments] = useState<ReadonlySet<EnvironmentId>>(
192 () => new Set(),
193 );
194 const [errorByEnvironment, setErrorByEnvironment] = useState<ReadonlyMap<EnvironmentId, string>>(
195 () => new Map(),
196 );
197 const [resultByEnvironment, setResultByEnvironment] = useState<
198 ReadonlyMap<EnvironmentId, ProviderUpdateToastView>
199 >(() => new Map());
200
201 const clearPending = useCallback((environmentId: EnvironmentId) => {
202 setPendingEnvironments((previous) => {
203 if (!previous.has(environmentId)) {
204 return previous;
205 }
206 const next = new Set(previous);
207 next.delete(environmentId);
208 return next;
209 });
210 }, []);
211
212 const handleUpdate = useCallback(
213 async (environmentId: EnvironmentId) => {
214 const group = groupByEnvironment.get(environmentId);
215 if (!group || group.candidates.length === 0) {
216 return;
217 }
218 if (inFlightEnvironmentsRef.current.has(environmentId)) {
219 return;
220 }
221 inFlightEnvironmentsRef.current.add(environmentId);
222 const requestVersion = (requestVersionRef.current.get(environmentId) ?? 0) + 1;
223 requestVersionRef.current.set(environmentId, requestVersion);
224 const isCurrentRequest = () =>
225 requestVersionRef.current.get(environmentId) === requestVersion;
226 onInteract?.();
227 const providerCount = group.candidates.length;
228 const targets = group.candidates.map((candidate) => ({
229 driver: candidate.driver,
230 instanceId: candidate.instanceId,
231 }));
232
233 setPendingEnvironments((previous) => new Set(previous).add(environmentId));
234 setErrorByEnvironment((previous) => {
235 if (!previous.has(environmentId)) {
236 return previous;
237 }
238 const next = new Map(previous);
239 next.delete(environmentId);
240 return next;
241 });
242 setResultByEnvironment((previous) => {
243 if (!previous.has(environmentId)) {
244 return previous;
245 }
246 const next = new Map(previous);
247 next.delete(environmentId);
248 return next;
249 });
250
251 const expiry = setTimeout(() => {
252 // A newer attempt may have superseded this one; if so, leave its state
253 // untouched.
254 if (!isCurrentRequest()) {
255 return;
256 }
257 // The request is presumed dead (see PENDING_EXPIRY_MS). Clear the
258 // spinner AND the in-flight guard together so the row never strands on a
259 // dead Update button, and surface feedback so the timeout is visible
260 // rather than silently reverting to idle.
261 inFlightEnvironmentsRef.current.delete(environmentId);
262 clearPending(environmentId);
263 setErrorByEnvironment((previous) =>
264 new Map(previous).set(environmentId, "Update timed out — try again."),
265 );
266 }, PENDING_EXPIRY_MS);
267 try {
268 // Dispatch each candidate's update to this environment's own backend and
269 // normalize every settled outcome into the multi-backend reducer shape.
270 const results = await Promise.all(
271 targets.map(async (target): Promise<PromiseSettledResult<LocalProviderUpdateOutcome>> => {
272 try {
273 const result = await updateProvider({
274 environmentId,
275 input: { provider: target.driver, instanceId: target.instanceId },
276 });
277 return toProviderUpdateOutcome({
278 environmentId,
279 isPrimary: group.isPrimary,
280 target,
281 result,
282 });
283 } catch (error) {
284 return {
285 status: "rejected",
286 reason: error instanceof Error ? error : new Error("Provider update failed."),
287 };
288 }
289 }),
290 );
291 if (!isCurrentRequest()) {
292 // A newer attempt superseded this one while it was in flight; leave
293 // the newer attempt's state intact.
294 return;
295 }
296 // The request resolved (not a transport hang), so clear any stale
297 // timeout error the expiry may have set -- otherwise a late success
298 // would be masked, since an error takes priority in the row status.
299 setErrorByEnvironment((previous) => {
300 if (!previous.has(environmentId)) {
301 return previous;
302 }
303 const next = new Map(previous);
304 next.delete(environmentId);
305 return next;
306 });
307 if (results.length === 0) {
308 setErrorByEnvironment((previous) =>
309 new Map(previous).set(
310 environmentId,
311 "This environment isn’t connected — try again once it reconnects.",
312 ),
313 );
314 return;
315 }
316 const rejectedMessage = firstRejectedProviderUpdateMessage(results);
317 if (rejectedMessage) {
318 setErrorByEnvironment((previous) =>
319 new Map(previous).set(environmentId, rejectedMessage),
320 );
321 return;
322 }
323 const view = getProviderUpdateProgressToastView({
324 providers: collectProviderUpdateOutcomeSnapshots(results),
325 providerCount,
326 });
327 // Only persist a terminal outcome. A non-terminal ("running"/"initial")
328 // view means this dispatch could not confirm completion — e.g. a snapshot
329 // came back without its targeted instance (collectProviderUpdateOutcome-
330 // Snapshots drops null providers), which happens when the command is
331 // interrupted as a second backend connects and supersedes the in-flight
332 // update. A stored view never re-polls, so persisting it would pin the
333 // row's spinner forever once the pending flag expires. Drop it and let
334 // the live per-environment provider state (pill) plus the pending expiry
335 // drive the row, so it self-heals to whatever the backend actually did.
336 if (isTerminalProviderUpdatePhase(view.phase)) {
337 setResultByEnvironment((previous) => new Map(previous).set(environmentId, view));
338 }
339 } catch (error) {
340 if (isCurrentRequest()) {
341 setErrorByEnvironment((previous) =>
342 new Map(previous).set(
343 environmentId,
344 error instanceof Error ? error.message : "Provider update failed.",
345 ),
346 );
347 }
348 } finally {
349 clearTimeout(expiry);
350 // Only the current attempt owns the shared spinner and in-flight guard;
351 // a superseded attempt resolving late must not clear a newer one's.
352 if (isCurrentRequest()) {
353 clearPending(environmentId);
354 inFlightEnvironmentsRef.current.delete(environmentId);
355 }
356 }
357 },
358 [clearPending, groupByEnvironment, onInteract, updateProvider],
359 );
360
361 const rows = groups
362 .map((group) => ({
363 group,
364 status: resolveEnvironmentUpdateRowStatus({
365 group,
366 error: errorByEnvironment.get(group.environmentId),
367 result: resultByEnvironment.get(group.environmentId),
368 // Derive the live pill from the candidates this row is actually
369 // tracking, not every provider in the environment. Otherwise an
370 // unrelated provider's recent success (or one candidate succeeding while
371 // another was interrupted) makes the pill report success and hides the
372 // Update action for candidates that are still outdated.
373 pill: getProviderUpdateSidebarPillView(group.candidates, {
374 visibleAfterIso: visibleAfterIsoRef.current,
375 }),
376 isPending: pendingEnvironments.has(group.environmentId),
377 }),
378 }))
379 .filter(({ group, status }) => group.candidates.length > 0 || status.kind !== "idle");
380
381 if (rows.length === 0) {
382 return null;
383 }
384
385 return (
386 <div className="mt-0.5 flex flex-col gap-1">
387 {rows.map(({ group, status }) => (
388 <EnvironmentUpdateRow
389 key={group.environmentId}
390 group={group}
391 status={status}
392 onUpdate={() => handleUpdate(group.environmentId)}
393 />
394 ))}
395 </div>
396 );
397}