Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import {
4 canHideHostPressureUntilClear,
5 type HostPressureHide,
6 HostPressureDismissals,
7 hideHostPressure,
8 shownHostPressureKinds,
9} from "@t3tools/client-runtime/host-pressure-dismissals";
10import {
11 type EnvironmentId,
12 HOST_PRESSURE_KINDS,
13 type HostPressure,
14 type HostPressureAgent,
15 type HostPressureKind,
16 hostPressureRanking,
17} from "@t3tools/contracts";
18import { useNavigate } from "@tanstack/react-router";
19import { T, useGT, plural, part } from "gt-react";
20import { TriangleAlertIcon, XIcon } from "lucide-react";
21import { memo } from "react";
22
23import { useLocalStorage } from "../../hooks/useLocalStorage";
24import { useNowMinute } from "../../hooks/useNowMinute";
25import { formatBytes } from "../../lib/formatBytes";
26import { useServerConfigs, useThreadShell } from "../../state/entities";
27import { environmentPresentations } from "../../state/presentation";
28import { buildThreadRouteParams } from "../../threadRoutes";
29import { useForceStopThread } from "../chat/useForceStopThread";
30import { Button, InlineButton } from "../ui/button";
31import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover";
32import { SharedTooltipTrigger } from "../ui/shared-tooltip";
33
34type GT = ReturnType<typeof useGT>;
35type Strained = {
36 readonly environmentId: EnvironmentId;
37 readonly label: string;
38 readonly pressure: HostPressure;
39 /** Severe kinds this device has not hidden, most actionable first. */
40 readonly kinds: ReadonlyArray<HostPressureKind>;
41};
42
43const DISMISSALS_KEY = "t3code:host-pressure-dismissals";
44
45/** Only severe pressure earns a warning: a machine that is merely busy is working as intended. */
46export const SidebarHostPressureWarning = memo(function SidebarHostPressureWarning() {
47 const gt = useGT();
48 const configs = useServerConfigs();
49 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
50 const [dismissals, setDismissals] = useLocalStorage(DISMISSALS_KEY, [], HostPressureDismissals);
51 // A timed hide ends on the minute it is due.
52 const now = Date.parse(`${useNowMinute()}:00Z`);
53 const strained = [...configs].flatMap(([environmentId, config]): ReadonlyArray<Strained> => {
54 const pressure = config.hostPressure;
55 // A disconnected machine's last sample is stale, not a current warning.
56 const connected = presentations.get(environmentId)?.connection.phase === "connected";
57 if (!connected || pressure === undefined) return [];
58 const kinds = shownHostPressureKinds(dismissals, { environmentId, pressure }, now);
59 return kinds.length > 0
60 ? [{ environmentId, label: config.environment.label, pressure, kinds }]
61 : [];
62 });
63 const only = strained.length === 1 ? strained[0]! : null;
64 if (strained.length === 0) return null;
65 // One notice however many machines are strained, so the sidebar never fills with warnings.
66 const pillTitle =
67 only === null ? machinesTitle(gt, strained) : kindTitle(gt, only.kinds[0]!, only.label);
68 // The click time, not the minute tick, so an hour is a full hour.
69 const hide = (choice: HostPressureHide) =>
70 setDismissals((current) => hideHostPressure(current, strained, choice, Date.now()));
71 const canHideUntilClear = canHideHostPressureUntilClear(strained);
72 return (
73 <Popover>
74 <div className="group/host-pressure relative mx-(--sidebar-row-content-inset) shrink-0">
75 <SharedTooltipTrigger
76 render={
77 <PopoverTrigger
78 render={
79 <Button
80 variant="warning-outline"
81 size="compact"
82 data-host-pressure={strained.map((entry) => entry.environmentId).join(" ")}
83 className="w-full justify-start"
84 />
85 }
86 />
87 }
88 label={pillTitle}
89 align="start"
90 >
91 <TriangleAlertIcon />
92 <span className="mr-5 min-w-0 truncate">{pillTitle}</span>
93 </SharedTooltipTrigger>
94 {/* Same default as mobile's swipe; the popover still offers every duration. */}
95 <span className="absolute inset-y-0 right-1 flex items-center opacity-0 transition-opacity focus-within:opacity-100 group-hover/host-pressure:opacity-100 pointer-coarse:opacity-100">
96 <Button
97 variant="ghost-warning"
98 size="icon-tiny"
99 aria-label={gt`Dismiss notice`}
100 onClick={() => hide(canHideUntilClear ? "untilClear" : "hour")}
101 >
102 <XIcon className="size-3" />
103 </Button>
104 </span>
105 </div>
106 <PopoverPopup side="top" align="start" padding="compact">
107 {only === null ? (
108 <MachinesDetails strained={strained} />
109 ) : (
110 <>
111 <KindExplanations
112 kinds={only.kinds}
113 pressure={only.pressure}
114 machineName={only.label}
115 />
116 <AgentList environmentId={only.environmentId} pressure={only.pressure} />
117 </>
118 )}
119 <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border/60 pt-2 text-xs">
120 <span className="text-muted-foreground">
121 <T>Dismiss notice</T>
122 </span>
123 {canHideUntilClear ? (
124 <InlineButton onClick={() => hide("untilClear")}>
125 <T>Until it clears</T>
126 </InlineButton>
127 ) : null}
128 <InlineButton onClick={() => hide("hour")}>
129 <T>For 1 hour</T>
130 </InlineButton>
131 <InlineButton onClick={() => hide("tomorrow")}>
132 <T>Until tomorrow</T>
133 </InlineButton>
134 </div>
135 </PopoverPopup>
136 </Popover>
137 );
138});
139
140/** Overload covers both CPU and storage stalls, which share one title. */
141const titleGroup = (kind: HostPressureKind) => (kind === "io" ? "cpu" : kind);
142const startsTitleGroup = (kinds: ReadonlyArray<HostPressureKind>, index: number) =>
143 index === 0 || titleGroup(kinds[index]!) !== titleGroup(kinds[index - 1]!);
144
145function machinesTitle(gt: GT, strained: ReadonlyArray<Strained>): string {
146 const count = strained.length;
147 const groups = new Set(strained.map((entry) => titleGroup(entry.kinds[0]!)));
148 if (groups.size > 1) return gt`${{ count }} machines need attention`;
149 switch ([...groups][0]!) {
150 case "memory":
151 return gt`Memory is slowing agents on ${{ count }} machines`;
152 case "disk":
153 return gt`${{ count }} machines are almost out of disk space`;
154 default:
155 return gt`${{ count }} machines are overloaded`;
156 }
157}
158
159function kindTitle(gt: GT, kind: HostPressureKind, name: string | null): string {
160 switch (kind) {
161 case "memory":
162 return name === null
163 ? gt`Memory is slowing agents down`
164 : gt`Memory is slowing agents on ${{ name }}`;
165 case "disk":
166 return name === null
167 ? gt`Almost out of disk space`
168 : gt`${{ name }} is almost out of disk space`;
169 case "cpu":
170 case "io":
171 return name === null ? gt`Machine overloaded` : gt`${{ name }} is overloaded`;
172 }
173}
174
175/** Without a single machine's reading, the disk explanation leaves out the free space. */
176function kindExplanation(gt: GT, kind: HostPressureKind, pressure: HostPressure | null): string {
177 switch (kind) {
178 case "memory":
179 return gt`Agents keep waiting while the system frees up memory, so they may stop responding. Stopping the largest agent helps the rest.`;
180 case "disk":
181 return pressure === null || pressure.diskFreeBytes === null
182 ? gt`Agents fail once the disk is full. Remove worktrees you no longer need.`
183 : gt`${{ free: formatBytes(pressure.diskFreeBytes) }} left where T3 Code keeps its data and worktrees. Agents fail once it is full. Remove worktrees you no longer need.`;
184 case "cpu":
185 return gt`Work waits for a free CPU most of the time, so agents and builds run slowly.`;
186 case "io":
187 return gt`Work waits on disk reads and writes most of the time, so agents run slowly.`;
188 }
189}
190
191function KindExplanations(props: {
192 readonly kinds: ReadonlyArray<HostPressureKind>;
193 readonly pressure: HostPressure | null;
194 readonly machineName: string | null;
195}) {
196 const gt = useGT();
197 return props.kinds.map((kind, index) => (
198 <div key={kind} className={index === 0 ? undefined : "mt-3"}>
199 {startsTitleGroup(props.kinds, index) ? (
200 <PopoverTitle>{kindTitle(gt, kind, props.machineName)}</PopoverTitle>
201 ) : null}
202 <p className="mt-1 max-w-64 text-2xs text-muted-foreground">
203 {kindExplanation(gt, kind, props.pressure)}
204 </p>
205 </div>
206 ));
207}
208
209/** Each problem is explained once; each machine then lists its own problems and agents. */
210function MachinesDetails(props: { readonly strained: ReadonlyArray<Strained> }) {
211 const gt = useGT();
212 const kinds = HOST_PRESSURE_KINDS.filter((kind) =>
213 props.strained.some((entry) => entry.kinds.includes(kind)),
214 );
215 return (
216 <>
217 <KindExplanations kinds={kinds} pressure={null} machineName={null} />
218 {props.strained.map((entry) => (
219 <section key={entry.environmentId} className="mt-3 border-t border-border/60 pt-2">
220 <p className="truncate text-xs font-medium">{entry.label}</p>
221 {kinds.length > 1 ? (
222 <p className="mt-0.5 text-2xs text-muted-foreground">
223 {[...new Set(entry.kinds.map((kind) => kindTitle(gt, kind, null)))].join(" · ")}
224 </p>
225 ) : null}
226 <AgentList environmentId={entry.environmentId} pressure={entry.pressure} />
227 </section>
228 ))}
229 </>
230 );
231}
232
233function AgentList(props: {
234 readonly environmentId: EnvironmentId;
235 readonly pressure: HostPressure;
236}) {
237 const rankedBy = hostPressureRanking(props.pressure);
238 if (props.pressure.heaviestAgents.length === 0) return null;
239 return (
240 <ul className="mt-2 flex flex-col gap-1">
241 {props.pressure.heaviestAgents.map((agent, index) => (
242 <HostPressureAgentRow
243 key={agent.threadId ?? `${agent.agent}:${index}`}
244 environmentId={props.environmentId}
245 agent={agent}
246 rankedBy={rankedBy}
247 />
248 ))}
249 </ul>
250 );
251}
252
253/** Memory or cores, whichever the server ranked agents by. */
254export function hostPressureAgentUsage(
255 gt: GT,
256 agent: HostPressureAgent,
257 rankedBy: "memory" | "cpu",
258): string {
259 return rankedBy === "memory" || agent.cpuCores === null
260 ? formatBytes(agent.memoryBytes)
261 : gt`${plural(
262 { count: agent.cpuCores },
263 {
264 one: part`${{ count: agent.cpuCores }} core`,
265 other: part`${{ count: agent.cpuCores }} cores`,
266 },
267 )}`;
268}
269
270function HostPressureAgentRow(props: {
271 readonly environmentId: EnvironmentId;
272 readonly agent: HostPressureAgent;
273 readonly rankedBy: "memory" | "cpu";
274}) {
275 const gt = useGT();
276 const navigate = useNavigate();
277 const threadId = props.agent.threadId;
278 const threadRef = threadId === null ? null : scopeThreadRef(props.environmentId, threadId);
279 const thread = useThreadShell(threadRef);
280 const forceStop = useForceStopThread(props.environmentId);
281 const name =
282 thread?.title ??
283 (threadId === null ? gt`${{ agent: props.agent.agent }} (shared)` : props.agent.agent);
284 return (
285 <li className="flex min-w-0 items-center gap-2 text-xs">
286 {threadRef === null ? (
287 <span className="min-w-0 flex-1 truncate">{name}</span>
288 ) : (
289 <span className="min-w-0 flex-1 truncate">
290 <InlineButton
291 onClick={() =>
292 void navigate({
293 to: "/$environmentId/$threadId",
294 params: buildThreadRouteParams(threadRef),
295 })
296 }
297 >
298 {name}
299 </InlineButton>
300 </span>
301 )}
302 <span className="shrink-0 text-muted-foreground tabular-nums">
303 {hostPressureAgentUsage(gt, props.agent, props.rankedBy)}
304 </span>
305 {threadId !== null && forceStop.canForceStop ? (
306 <InlineButton
307 tone="muted"
308 disabled={forceStop.stoppingThreadId === threadId}
309 onClick={() => void forceStop.forceStopThread(threadId)}
310 >
311 {forceStop.stoppingThreadId === threadId ? <T>Force stopping...</T> : <T>Force stop</T>}
312 </InlineButton>
313 ) : null}
314 </li>
315 );
316}