Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { msg, T, useGT, useMessages } from "gt-react";
3import { type ReactNode, useSyncExternalStore } from "react";
4
5import type { MessageResolver } from "~/i18n/messages";
6import { cn } from "~/lib/utils";
7import { environmentIdsKey } from "~/state/environmentAtomList";
8import { environmentUpdateStatesAtom } from "~/state/server";
9import { useServerUpdate } from "../ServerUpdateAction";
10import { Button } from "../ui/button";
11import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
12import {
13 describeUpdateCapsule,
14 formatUpdateElapsed,
15 RUN_STATUS_LABELS,
16 resolveRestoredRetry,
17 resolveUpdateRunMachineStatus,
18 type UpdateEverythingMachine,
19 type UpdateEverythingRun,
20 type UpdateRunLocalState,
21 type UpdateRunMachineView,
22} from "./updateEverything.logic";
23import {
24 dismissSettledUpdateRunMachines,
25 postponeUpdateRestart,
26 retryFailedUpdateRunServers,
27} from "./updateEverythingRun";
28
29function useNow(intervalMs: number | null): number {
30 const step = intervalMs ?? 60_000;
31 const subscribe = (onChange: () => void) => {
32 if (intervalMs === null) return () => {};
33 const timer = setInterval(onChange, intervalMs);
34 return () => clearInterval(timer);
35 };
36 return useSyncExternalStore(subscribe, () => Math.floor(Date.now() / step) * step);
37}
38
39function useUpdateRunMachineViews(
40 run: UpdateEverythingRun,
41 current: ReadonlyArray<UpdateEverythingMachine>,
42): ReadonlyArray<UpdateRunMachineView> {
43 const updateStates = useAtomValue(
44 environmentUpdateStatesAtom(
45 environmentIdsKey(run.machines.map(({ environmentId }) => environmentId)),
46 ),
47 );
48 return run.machines.map((machine, index) => ({
49 machine,
50 status: resolveUpdateRunMachineStatus(machine, run.phase, updateStates[index]!),
51 restoredRetry: resolveRestoredRetry(machine, current),
52 }));
53}
54
55function restartSecondsLeft(run: UpdateEverythingRun, now: number): number | null {
56 return run.phase === "countdown" && run.restartAt !== null
57 ? Math.max(0, Math.ceil((run.restartAt - now) / 1000))
58 : null;
59}
60
61function localStatusLabel(
62 run: UpdateEverythingRun,
63 local: UpdateRunLocalState,
64 now: number,
65 resolve: MessageResolver,
66) {
67 const seconds = restartSecondsLeft(run, now);
68 if (seconds !== null) return resolve(msg("restarts in {seconds}s", { seconds }));
69 if (run.phase === "installing") return resolve(msg("restarting"));
70 if (local?.status === "downloading") {
71 return local.percent === null
72 ? resolve(msg("downloading"))
73 : resolve(msg("downloading {percent}%", { percent: Math.floor(local.percent) }));
74 }
75 return resolve(msg("restarts after the servers"));
76}
77
78export function SidebarUpdateCapsule({
79 run,
80 current,
81 local,
82 icon,
83 onRestart,
84}: {
85 readonly run: UpdateEverythingRun;
86 /** Every server as it is now, to rebuild the retry of a row restored after a relaunch. */
87 readonly current: ReadonlyArray<UpdateEverythingMachine>;
88 readonly local: UpdateRunLocalState;
89 readonly icon: ReactNode;
90 readonly onRestart?: () => Promise<void>;
91}) {
92 const machines = useUpdateRunMachineViews(run, current);
93 const hasActiveMachine = machines.some(
94 ({ status }) => status !== "done" && status !== "failed" && status !== "waiting",
95 );
96 const now = useNow(run.phase === "countdown" ? 1_000 : hasActiveMachine ? 30_000 : null);
97 const gt = useGT();
98 const m = useMessages();
99 const view = describeUpdateCapsule(run, machines, local, now, m);
100 const updateServer = useServerUpdate();
101 const failed = machines.some(({ status }) => status === "failed");
102 const settled = !hasActiveMachine && run.localVersion === null;
103 const restartSeconds = restartSecondsLeft(run, now);
104 const expandedControlClassName =
105 restartSeconds === null
106 ? "@min-[5rem]/sidebar-update:block"
107 : "@min-[12rem]/sidebar-update:block";
108
109 const actionLabel =
110 view.action === "later" ? gt("Later") : view.action === "retry" ? gt("Retry") : gt("Dismiss");
111 const runAction = () => {
112 if (view.action === "later") postponeUpdateRestart();
113 else if (view.action === "retry") {
114 retryFailedUpdateRunServers(
115 updateServer,
116 new Map(
117 machines.flatMap(({ machine, restoredRetry }) =>
118 restoredRetry === null ? [] : [[machine.environmentId, restoredRetry] as const],
119 ),
120 ),
121 );
122 } else dismissSettledUpdateRunMachines();
123 };
124
125 return (
126 <Popover>
127 <div
128 className={cn(
129 "relative ml-auto flex h-8 w-8 shrink-0 items-center justify-end rounded-full bg-sidebar-control-surface text-sidebar-foreground transition-[width] duration-200 ease-out motion-reduce:transition-none",
130 restartSeconds === null
131 ? "@min-[5rem]/sidebar-update:w-full"
132 : "@min-[12rem]/sidebar-update:w-full",
133 view.tone === "slow" && "ring-1 ring-warning/40 ring-inset",
134 view.tone === "failed" && "ring-1 ring-destructive/40 ring-inset",
135 )}
136 >
137 <PopoverTrigger
138 render={
139 <button
140 type="button"
141 aria-label={
142 view.slow ? `${view.label} ${view.slow.status} ${view.slow.elapsed}` : view.label
143 }
144 className="absolute inset-0 cursor-pointer rounded-full outline-hidden ring-ring hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-inset"
145 />
146 }
147 />
148 <span
149 className={cn(
150 "pointer-events-none relative hidden min-w-0 flex-1 truncate pl-3 text-xs transition-opacity duration-200 ease-out starting:opacity-0 motion-reduce:transition-none",
151 expandedControlClassName,
152 )}
153 >
154 <span className={cn(view.tone === "failed" && "text-destructive")}>{view.label}</span>
155 {view.slow ? (
156 <span className="text-warning tabular-nums"> {view.slow.elapsed}</span>
157 ) : null}
158 </span>
159 {view.action !== null ? (
160 <button
161 type="button"
162 className={cn(
163 "relative hidden shrink-0 cursor-pointer pr-3 pl-1.5 text-xs underline decoration-muted-foreground/60 underline-offset-3 hover:decoration-current transition-opacity duration-200 ease-out starting:opacity-0 motion-reduce:transition-none",
164 expandedControlClassName,
165 )}
166 onClick={runAction}
167 >
168 {actionLabel}
169 </button>
170 ) : null}
171 <span
172 className={cn(
173 "pointer-events-none relative grid size-8 shrink-0 place-items-center",
174 view.action !== null &&
175 (restartSeconds === null
176 ? "@min-[5rem]/sidebar-update:hidden"
177 : "@min-[12rem]/sidebar-update:hidden"),
178 restartSeconds !== null &&
179 "rounded-full text-xs font-medium tabular-nums ring-1 ring-current/22 ring-inset",
180 )}
181 >
182 {restartSeconds !== null ? m(msg("{seconds}s", { seconds: restartSeconds })) : icon}
183 </span>
184 </div>
185 <PopoverPopup side="top" align="end" padding="compact" width="sm">
186 <div className="flex flex-col gap-1 text-xs">
187 {run.localVersion !== null ? (
188 <div className="flex items-center justify-between gap-3">
189 <span>
190 <T>This app</T>
191 </span>
192 <span className="text-muted-foreground tabular-nums">
193 {localStatusLabel(run, local, now, m)}
194 </span>
195 </div>
196 ) : onRestart ? (
197 <div className="flex items-center justify-between gap-3">
198 <span>
199 <T>This app</T>
200 </span>
201 <Button size="xs" variant="outline" onClick={() => void onRestart()}>
202 <T>Restart to update</T>
203 </Button>
204 </div>
205 ) : null}
206 {machines.map(({ machine, status }) => (
207 <div key={machine.environmentId} className="flex min-w-0 flex-col">
208 <div className="flex items-center justify-between gap-3">
209 <span className="truncate">{machine.label}</span>
210 <span
211 className={cn(
212 "shrink-0 tabular-nums",
213 status === "failed" ? "text-destructive" : "text-muted-foreground",
214 )}
215 >
216 {m(RUN_STATUS_LABELS[status])}
217 {status !== "done" && status !== "failed" && status !== "waiting"
218 ? ` ${formatUpdateElapsed(now - machine.startedAt, m)}`
219 : ""}
220 </span>
221 </div>
222 {machine.failure !== null ? (
223 <span className="break-words text-muted-foreground">{machine.failure}</span>
224 ) : null}
225 </div>
226 ))}
227 {view.action !== null ? (
228 <div className="mt-1 flex justify-end gap-1">
229 <Button size="xs" variant="outline" onClick={runAction}>
230 {actionLabel}
231 </Button>
232 {settled && failed && view.action !== "dismiss" ? (
233 <Button size="xs" variant="ghost" onClick={dismissSettledUpdateRunMachines}>
234 <T>Dismiss</T>
235 </Button>
236 ) : null}
237 </div>
238 ) : null}
239 </div>
240 </PopoverPopup>
241 </Popover>
242 );
243}