Open History to see the last commit
1import type {
2 ProviderInstanceId,
3 ServerProvider,
4 ServerProviderUsageWindow,
5 UsageLimitSourceSnapshots,
6} from "@t3tools/contracts";
7import {
8 collectProviderUsageLimits,
9 type LimitPace,
10 paceOf,
11 paceRemainingPercent,
12 remainingPercent,
13} from "@t3tools/shared/usageLimits";
14import { formatDuration, limitsNotice } from "@t3tools/shared/usageLimitsCopy";
15import { Link } from "@tanstack/react-router";
16import { msg, useGT, useLocale, useMessages } from "gt-react";
17import type { ReactNode } from "react";
18
19import { usePrimarySettings } from "../../hooks/useSettings";
20import { useNowMinute } from "../../hooks/useNowMinute";
21import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
22import { formatContextWindowTokens } from "../../lib/contextWindow";
23import { cn } from "../../lib/utils";
24import { formatUpcomingTimestamp } from "../../timestampFormat";
25import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
26import { formatContextWindowCompactionMessage } from "./compaction.logic";
27import { ThreadDetailsSection } from "./ThreadDetailsSection";
28
29const PACE_LABEL: Record<LimitPace, string> = {
30 ahead: msg("Ahead of pace"),
31 on: msg("On pace"),
32 under: msg("Under pace"),
33};
34
35export interface ThreadDetailsUsageInput {
36 readonly providerInstanceId: ProviderInstanceId | null;
37 readonly providers: readonly ServerProvider[];
38 readonly sources: UsageLimitSourceSnapshots;
39 readonly contextWindow: ContextWindowSnapshot | null;
40}
41
42type UsageTone = "error" | "warning" | null;
43
44/** The selected provider's limit windows. Each row reads as room left and opens the usage page. */
45export function ThreadDetailsUsage({
46 providerInstanceId,
47 providers,
48 sources,
49}: Omit<ThreadDetailsUsageInput, "contextWindow">) {
50 const gt = useGT();
51 const m = useMessages();
52 const nowMinute = useNowMinute();
53 const now = Date.parse(`${nowMinute}:00Z`);
54 const report =
55 providerInstanceId !== null
56 ? collectProviderUsageLimits(providerInstanceId, providers, sources, now)
57 : null;
58 // Only this instance's data: the report keeps one instance per login, and any other entry may be
59 // a different login or workspace, so fall back to the instance's own snapshot.
60 const limits =
61 report?.accounts.find((entry) => entry.instanceId === providerInstanceId)?.limits ??
62 providers.find((provider) => provider.instanceId === providerInstanceId)?.usageLimits;
63 if (!limits) return null;
64 const notice = limitsNotice(limits, m);
65
66 return (
67 <ThreadDetailsSection
68 headingId="thread-details-usage-heading"
69 title={gt("Usage limits")}
70 showHeading={false}
71 >
72 <div className="grid grid-cols-[auto_minmax(3rem,1fr)_auto] gap-x-3 text-xs">
73 {notice ? (
74 <UsageRow
75 label={gt("Limits", { $context: "usage limits row label" })}
76 fill={null}
77 tone={null}
78 value={gt("Unavailable")}
79 tooltip={<span className="text-foreground">{notice}</span>}
80 opensUsage
81 />
82 ) : (
83 limits.windows.map((window) => <LimitRow key={window.id} window={window} now={now} />)
84 )}
85 </div>
86 </ThreadDetailsSection>
87 );
88}
89
90/** The thread's context window. The bar fills as context is used; the tick marks auto-compaction. */
91export function ThreadDetailsContext({ usage }: { readonly usage: ContextWindowSnapshot }) {
92 const maxTokens = usage.maxTokens != null && usage.maxTokens > 0 ? usage.maxTokens : null;
93 const used =
94 maxTokens !== null && usage.usedPercentage !== null
95 ? Math.round(Math.max(0, Math.min(100, usage.usedPercentage)))
96 : null;
97 const threshold = usage.autoCompactThreshold ?? null;
98 const tick =
99 maxTokens !== null && threshold !== null && threshold > 0 && threshold < maxTokens
100 ? (threshold / maxTokens) * 100
101 : null;
102 const gt = useGT();
103 const m = useMessages();
104 const locale = useLocale();
105 const usedTokens = formatContextWindowTokens(usage.usedTokens);
106 return (
107 <ThreadDetailsSection
108 headingId="thread-details-context-heading"
109 title={gt("Context window")}
110 showHeading={false}
111 >
112 <div className="grid grid-cols-[auto_minmax(3rem,1fr)_auto] gap-x-3 text-xs">
113 <UsageRow
114 label={gt("Context", { $context: "context window row label" })}
115 fill={used}
116 tone={used === null ? null : used >= 90 ? "error" : used >= 80 ? "warning" : null}
117 tick={tick}
118 muted
119 value={
120 maxTokens !== null
121 ? `${usedTokens} / ${formatContextWindowTokens(maxTokens)}`
122 : usedTokens
123 }
124 ariaValue={
125 used !== null
126 ? gt("{used}% used", { used })
127 : gt("{usedTokens} tokens used", { usedTokens })
128 }
129 tooltip={
130 <>
131 <span className="text-foreground">
132 {used !== null
133 ? gt("Context: {used}% used", { used })
134 : gt("Context: {usedTokens} tokens used", { usedTokens })}
135 </span>
136 {maxTokens !== null ? (
137 <span className="text-muted-foreground">
138 {gt("{used} of {max} tokens", {
139 used: usage.usedTokens.toLocaleString(locale),
140 max: maxTokens.toLocaleString(locale),
141 })}
142 </span>
143 ) : null}
144 {threshold !== null && threshold > 0 ? (
145 <span className="text-muted-foreground">
146 {formatContextWindowCompactionMessage(threshold, m)}
147 </span>
148 ) : null}
149 </>
150 }
151 />
152 </div>
153 </ThreadDetailsSection>
154 );
155}
156
157function LimitRow({
158 window,
159 now,
160}: {
161 readonly window: ServerProviderUsageWindow;
162 readonly now: number;
163}) {
164 const gt = useGT();
165 const m = useMessages();
166 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
167 const left = remainingPercent(window);
168 const pace = paceOf(window, now);
169 const timeLeft = paceRemainingPercent(window, now);
170 const resetsAt = window.resetsAt ? Date.parse(window.resetsAt) : Number.NaN;
171 return (
172 <UsageRow
173 label={window.label}
174 fill={left}
175 tone={left <= 10 ? "error" : left <= 20 ? "warning" : null}
176 tick={timeLeft}
177 value={`${left}%`}
178 ariaValue={gt("{left}% left", { left })}
179 opensUsage
180 tooltip={
181 <>
182 <span className="text-foreground">
183 {gt("{label}: {left}% left", { label: window.label, left })}
184 </span>
185 {pace && timeLeft !== null ? (
186 <span className="text-muted-foreground">
187 {m(PACE_LABEL[pace])} · {gt("{timeLeft}% of the window left", { timeLeft })}
188 </span>
189 ) : null}
190 {window.resetsAt && resetsAt > now ? (
191 <span className="text-muted-foreground">
192 {gt("Resets in {duration} · {time}", {
193 duration: formatDuration(resetsAt - now, m),
194 time: formatUpcomingTimestamp(window.resetsAt, timestampFormat, now, undefined, m),
195 })}
196 </span>
197 ) : null}
198 </>
199 }
200 />
201 );
202}
203
204/** One label, hairline, and value row; the whole row opens the details tooltip. With `opensUsage` it links to the usage page. */
205function UsageRow({
206 label,
207 fill,
208 tone,
209 tick = null,
210 value,
211 ariaValue = value,
212 tooltip,
213 muted = false,
214 opensUsage = false,
215}: {
216 readonly label: string;
217 /** Bar fill from 0 to 100. Null hides the bar. */
218 readonly fill: number | null;
219 readonly tone: UsageTone;
220 /** A marker on the bar, from 0 to 100. */
221 readonly tick?: number | null;
222 readonly value: string;
223 readonly ariaValue?: string;
224 readonly tooltip: ReactNode;
225 readonly muted?: boolean;
226 readonly opensUsage?: boolean;
227}) {
228 const gt = useGT();
229 const rowProps = {
230 "aria-label": gt("{label}: {value}", { label, value: ariaValue }),
231 className: cn(
232 "col-span-3 grid h-6 grid-cols-subgrid items-center rounded-lg px-2.5 outline-none hover:bg-black/[0.035] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring data-popup-open:bg-black/[0.035] dark:hover:bg-white/[0.08] dark:data-popup-open:bg-white/[0.08]",
233 opensUsage
234 ? "group cursor-pointer active:bg-black/[0.06] dark:active:bg-white/[0.12]"
235 : "cursor-default",
236 ),
237 };
238 return (
239 <Tooltip>
240 <TooltipTrigger
241 render={
242 opensUsage ? <Link to="/usage" {...rowProps} /> : <div tabIndex={0} {...rowProps} />
243 }
244 >
245 <span className="max-w-28 truncate text-muted-foreground group-hover:text-foreground">
246 {label}
247 </span>
248 {fill !== null ? (
249 <span className="relative h-[3px] rounded-full bg-muted-foreground/30 dark:bg-muted-foreground/20">
250 {fill > 0 ? (
251 <span
252 className={cn(
253 "absolute inset-y-0 left-0 rounded-full",
254 tone === "error"
255 ? "bg-error"
256 : tone === "warning"
257 ? "bg-warning"
258 : muted
259 ? "bg-muted-foreground"
260 : "bg-foreground/80",
261 )}
262 style={{ width: `max(${fill}%, 6px)` }}
263 />
264 ) : null}
265 {tick !== null ? (
266 <span
267 aria-hidden
268 className="absolute -top-[3px] h-[9px] w-px -translate-x-1/2 bg-foreground/75"
269 style={{ left: `clamp(0.5px, ${tick}%, calc(100% - 0.5px))` }}
270 />
271 ) : null}
272 </span>
273 ) : null}
274 <span
275 className={cn(
276 // Text-only rows span the bar column so they never widen the shared value column.
277 "text-end font-medium tabular-nums",
278 fill === null && "col-span-2",
279 tone === "error"
280 ? "text-error-foreground"
281 : tone === "warning"
282 ? "text-warning-foreground"
283 : fill === null
284 ? "text-muted-foreground"
285 : "text-foreground/80",
286 )}
287 >
288 {value}
289 </span>
290 </TooltipTrigger>
291 {/* Rows sit 8px inside the card; clear its edge instead of overlapping it. */}
292 <TooltipPopup side="left" sideOffset={16}>
293 <div className="flex flex-col gap-0.5">
294 {tooltip}
295 {opensUsage ? <span className="text-muted-foreground">{gt("Open usage")}</span> : null}
296 </div>
297 </TooltipPopup>
298 </Tooltip>
299 );
300}