Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadDetailsUsage.tsx

259 lines8.8 KB

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