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