Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
3import { Atom } from "effect/unstable/reactivity";
4import { useMemo, useState } from "react";
5
6import type { EnvironmentPresentation } from "~/state/environments";
7import { serverEnvironment } from "~/state/server";
8import {
9 buildVersionMismatchDismissalKey,
10 dismissServerUpdateFailure,
11 dismissVersionMismatch,
12 isServerUpdateFailureDismissed,
13 isVersionMismatchDismissed,
14 resolveServerConfigVersionMismatch,
15 resolveServerSelfUpdateCapability,
16 supportsDesktopAppUpdate,
17 supportsServerUpdateThreadContinuation,
18} from "~/versionSkew";
19import {
20 ServerUpdateAction,
21 ServerUpdateProgress,
22 ServerUpdatesAction,
23} from "../ServerUpdateAction";
24import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
25import type { ComposerBannerStackItem } from "./ComposerBannerStack";
26import { ComposerServerUpdateIcon } from "./ComposerServerUpdateStatus";
27
28/** Keep every machine's update visible while auto balance has no single update target. */
29export function useAutoBalanceUpdateBanner(
30 environments: readonly EnvironmentPresentation[],
31): ComposerBannerStackItem | null {
32 const statesAtom = useMemo(
33 () =>
34 Atom.make((get) =>
35 environments.map((environment) => ({
36 environment,
37 state: get(serverEnvironment.updateStateAtom(environment.environmentId)),
38 })),
39 ),
40 [environments],
41 );
42 const states = useAtomValue(statesAtom);
43 const [dismissedNotices, setDismissedNotices] = useState<ReadonlySet<string | ServerUpdateState>>(
44 () => new Set(),
45 );
46 const machines = states.flatMap(({ environment, state }) => {
47 const mismatch = resolveServerConfigVersionMismatch(environment.serverConfig);
48 const dismissKey = mismatch
49 ? buildVersionMismatchDismissalKey(environment.environmentId, mismatch)
50 : null;
51 if (
52 state.status === "idle"
53 ? !mismatch ||
54 (dismissKey !== null && dismissedNotices.has(dismissKey)) ||
55 isVersionMismatchDismissed(dismissKey)
56 : dismissedNotices.has(state) || isServerUpdateFailureDismissed(state)
57 )
58 return [];
59 const selfUpdate = resolveServerSelfUpdateCapability(environment.serverConfig);
60 const desktopAppUpdate = supportsDesktopAppUpdate(environment.serverConfig);
61 return [
62 {
63 environmentId: environment.environmentId,
64 serverLabel: environment.label,
65 selfUpdate,
66 desktopAppUpdate,
67 threadContinuation: supportsServerUpdateThreadContinuation(environment.serverConfig),
68 continueThreadsAfterServerUpdate:
69 environment.serverConfig?.settings.continueThreadsAfterServerUpdate ?? false,
70 targetVersion: state.status === "idle" ? mismatch!.clientVersion : state.targetVersion,
71 connected: environment.connection.phase === "connected",
72 remoteUpdate: selfUpdate !== null && (selfUpdate !== "desktop-managed" || desktopAppUpdate),
73 state,
74 dismissKey,
75 },
76 ];
77 });
78 if (machines.length === 0) return null;
79
80 const running = machines.filter((machine) => machine.state.status === "running").length;
81 const failed = machines.filter((machine) => machine.state.status === "failed").length;
82 const manual = machines.filter((machine) => !machine.remoteUpdate).length;
83 const targets = machines.filter(
84 (machine) => machine.connected && machine.remoteUpdate && machine.state.status !== "running",
85 );
86 const count = running || failed || machines.length;
87 const status = running ? "running" : failed ? "failed" : "idle";
88 const prefix = running ? "Updating" : failed ? "Could not update" : "Update available for";
89 const title = `${prefix} ${count} ${count === 1 ? "machine" : "machines"}`;
90 return {
91 id: `auto-balance-server-updates-${dismissedNotices.size}`,
92 variant: failed ? "error" : "default",
93 priority: running ? "urgent" : "notice",
94 icon: <ComposerServerUpdateIcon status={status} />,
95 title: (
96 <Popover>
97 <PopoverTrigger
98 className="block max-w-full truncate rounded-sm text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
99 aria-label={`${title}. View machines`}
100 >
101 {title}
102 </PopoverTrigger>
103 <PopoverPopup side="top" align="start" className="w-80 max-w-[calc(100vw-2rem)]">
104 <div className="space-y-3 text-xs">
105 {machines.map((machine) => (
106 <div key={machine.environmentId} className="space-y-1">
107 <div className="font-medium">{machine.serverLabel}</div>
108 {machine.state.status !== "idle" ? (
109 <ServerUpdateProgress state={machine.state} />
110 ) : !machine.remoteUpdate ? (
111 <>
112 <div className="text-muted-foreground">Manual update required</div>
113 <ServerUpdateAction {...machine} />
114 </>
115 ) : (
116 <div className="text-muted-foreground">
117 {machine.connected
118 ? `Ready to update to ${machine.targetVersion}`
119 : "Reconnect this machine to update"}
120 </div>
121 )}
122 </div>
123 ))}
124 </div>
125 </PopoverPopup>
126 </Popover>
127 ),
128 description:
129 manual > 0 ? `${manual} ${manual === 1 ? "needs" : "need"} a manual update` : undefined,
130 actions:
131 running === 0 && targets.length > 0 ? (
132 <ServerUpdatesAction
133 targets={targets}
134 variant="ghost"
135 label={
136 failed > 0
137 ? "Retry"
138 : targets.length === machines.length
139 ? "Update all"
140 : `Update ${targets.length} ${targets.length === 1 ? "machine" : "machines"}`
141 }
142 />
143 ) : undefined,
144 dismissLabel: "Dismiss update notice",
145 ...(running
146 ? {}
147 : {
148 onDismiss: () => {
149 const next = new Set(dismissedNotices);
150 for (const { state, dismissKey } of machines) {
151 dismissServerUpdateFailure(state);
152 dismissVersionMismatch(dismissKey);
153 if (dismissKey) next.add(dismissKey);
154 if (state.status === "failed") next.add(state);
155 }
156 setDismissedNotices(next);
157 },
158 }),
159 };
160}