Skip to content
TypeScript

feat(web): context meter fills up and shows tokens against the limit (#27892)

Theo Browne961026c6c981
diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx
index 35a954db9d4..b8d96a33ec5 100644
--- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx
+++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx
@@ -23,7 +23,11 @@ import { ThreadDetailsSection } from "./ThreadDetailsSection";
import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel";
import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
import { ThreadServersPanel } from "./ThreadServersPanel";
-import { ThreadDetailsUsage, type ThreadDetailsUsageInput } from "./ThreadDetailsUsage";
+import {
+ ThreadDetailsContext,
+ ThreadDetailsUsage,
+ type ThreadDetailsUsageInput,
+} from "./ThreadDetailsUsage";
import { ThreadDetailsItemsMenuItems } from "./ThreadDetailsItemsMenu";
import { resolveThreadDetailsVisibility, THREAD_DETAILS_ITEMS } from "./threadDetailsItems";
import { useClientSettings } from "../../hooks/useSettings";
@@ -254,6 +258,10 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
{visible.usage ? <ThreadDetailsUsage {...props.usage} /> : null}
+ {visible.context && props.usage.contextWindow ? (
+ <ThreadDetailsContext usage={props.usage.contextWindow} />
+ ) : null}
+
{/* Shown only when no section above has content, so an emptied card can be refilled. */}
<div className="p-2 group-has-[>section>:last-child:not(:empty)]/details-items:hidden">
<ThreadDetailsControl
diff --git a/apps/web/src/components/chat/ThreadDetailsUsage.tsx b/apps/web/src/components/chat/ThreadDetailsUsage.tsx
index e0f5c3afbe8..05211d6ace4 100644
--- a/apps/web/src/components/chat/ThreadDetailsUsage.tsx
+++ b/apps/web/src/components/chat/ThreadDetailsUsage.tsx
@@ -20,6 +20,7 @@ import { type ContextWindowSnapshot, formatContextWindowTokens } from "../../lib
import { cn } from "../../lib/utils";
import { formatUpcomingTimestamp } from "../../timestampFormat";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { formatContextWindowCompactionMessage } from "./ContextWindowMeter.logic";
import { ThreadDetailsSection } from "./ThreadDetailsSection";
const PACE_LABEL: Record<LimitPace, string> = {
@@ -35,16 +36,14 @@ export interface ThreadDetailsUsageInput {
readonly contextWindow: ContextWindowSnapshot | null;
}
-/**
- * The selected provider's limit windows and the thread's context window.
- * Every row reads as room left, so a longer bar always means more headroom.
- */
+type UsageTone = "error" | "warning" | null;
+
+/** The selected provider's limit windows. Each row reads as room left. */
export function ThreadDetailsUsage({
providerInstanceId,
providers,
sources,
- contextWindow,
-}: ThreadDetailsUsageInput) {
+}: Omit<ThreadDetailsUsageInput, "contextWindow">) {
const nowMinute = useNowMinute();
const now = Date.parse(`${nowMinute}:00Z`);
const report =
@@ -56,28 +55,83 @@ export function ThreadDetailsUsage({
const limits =
report?.accounts.find((entry) => entry.instanceId === providerInstanceId)?.limits ??
providers.find((provider) => provider.instanceId === providerInstanceId)?.usageLimits;
- const notice = limits ? limitsNotice(limits) : null;
- if (!limits && !contextWindow) return null;
+ if (!limits) return null;
+ const notice = limitsNotice(limits);
return (
<ThreadDetailsSection
headingId="thread-details-usage-heading"
- title="Usage"
+ title="Usage limits"
showHeading={false}
>
<div className="grid grid-cols-[auto_minmax(3rem,1fr)_auto] gap-x-3 text-xs">
{notice ? (
<UsageRow
label="Limits"
- left={null}
+ fill={null}
+ tone={null}
value="Unavailable"
tooltip={<span className="text-foreground">{notice}</span>}
/>
- ) : null}
- {limits && !notice
- ? limits.windows.map((window) => <LimitRow key={window.id} window={window} now={now} />)
- : null}
- {contextWindow ? <ContextRow usage={contextWindow} spaced={limits !== undefined} /> : null}
+ ) : (
+ limits.windows.map((window) => <LimitRow key={window.id} window={window} now={now} />)
+ )}
+ </div>
+ </ThreadDetailsSection>
+ );
+}
+
+/** The thread's context window. The bar fills as context is used; the tick marks auto-compaction. */
+export function ThreadDetailsContext({ usage }: { readonly usage: ContextWindowSnapshot }) {
+ const maxTokens = usage.maxTokens != null && usage.maxTokens > 0 ? usage.maxTokens : null;
+ const used =
+ maxTokens !== null && usage.usedPercentage !== null
+ ? Math.round(Math.max(0, Math.min(100, usage.usedPercentage)))
+ : null;
+ const threshold = usage.autoCompactThreshold ?? null;
+ const tick =
+ maxTokens !== null && threshold !== null && threshold > 0 && threshold < maxTokens
+ ? (threshold / maxTokens) * 100
+ : null;
+ const usedTokens = formatContextWindowTokens(usage.usedTokens);
+ return (
+ <ThreadDetailsSection
+ headingId="thread-details-context-heading"
+ title="Context window"
+ showHeading={false}
+ >
+ <div className="grid grid-cols-[auto_minmax(3rem,1fr)_auto] gap-x-3 text-xs">
+ <UsageRow
+ label="Context"
+ fill={used}
+ tone={used === null ? null : used >= 90 ? "error" : used >= 80 ? "warning" : null}
+ tick={tick}
+ muted
+ value={
+ maxTokens !== null
+ ? `${usedTokens} / ${formatContextWindowTokens(maxTokens)}`
+ : usedTokens
+ }
+ ariaValue={used !== null ? `${used}% used` : `${usedTokens} tokens used`}
+ tooltip={
+ <>
+ <span className="text-foreground">
+ {used !== null ? `Context: ${used}% used` : `Context: ${usedTokens} tokens used`}
+ </span>
+ {maxTokens !== null ? (
+ <span className="text-muted-foreground">
+ {usage.usedTokens.toLocaleString("en-US")} of {maxTokens.toLocaleString("en-US")}{" "}
+ tokens
+ </span>
+ ) : null}
+ {threshold !== null && threshold > 0 ? (
+ <span className="text-muted-foreground">
+ {formatContextWindowCompactionMessage(null, threshold)}
+ </span>
+ ) : null}
+ </>
+ }
+ />
</div>
</ThreadDetailsSection>
);
@@ -97,7 +151,10 @@ function LimitRow({
return (
<UsageRow
label={window.label}
- left={left}
+ fill={left}
+ tone={left <= 10 ? "error" : left <= 20 ? "warning" : null}
+ value={`${left}%`}
+ ariaValue={`${left}% left`}
tooltip={
<>
<span className="text-foreground">
@@ -116,76 +173,43 @@ function LimitRow({
);
}
-function ContextRow({
- usage,
- spaced,
-}: {
- readonly usage: ContextWindowSnapshot;
- readonly spaced: boolean;
-}) {
- const maxTokens = usage.maxTokens ?? null;
- const left =
- maxTokens !== null && usage.usedPercentage !== null
- ? Math.round(100 - Math.max(0, Math.min(100, usage.usedPercentage)))
- : null;
- const used = formatContextWindowTokens(usage.usedTokens);
- return (
- <UsageRow
- label="Context"
- left={left}
- muted
- className={cn(spaced && "mt-2")}
- tooltip={
- <>
- {left !== null ? <span className="text-foreground">Context: {left}% left</span> : null}
- <span className={left !== null ? "text-muted-foreground" : "text-foreground"}>
- {maxTokens !== null
- ? `${used} of ${formatContextWindowTokens(maxTokens)} tokens used`
- : `${used} tokens used`}
- </span>
- </>
- }
- value={left === null ? used : undefined}
- />
- );
-}
-
/** One label, hairline, and value row; the whole row opens the details tooltip. */
function UsageRow({
label,
- left,
- tooltip,
+ fill,
+ tone,
+ tick = null,
value,
+ ariaValue = value,
+ tooltip,
muted = false,
- className,
}: {
readonly label: string;
- readonly left: number | null;
+ /** Bar fill from 0 to 100. Null hides the bar. */
+ readonly fill: number | null;
+ readonly tone: UsageTone;
+ /** A marker on the bar, from 0 to 100. */
+ readonly tick?: number | null;
+ readonly value: string;
+ readonly ariaValue?: string;
readonly tooltip: ReactNode;
- /** Replaces the percentage when there is none. */
- readonly value?: string | undefined;
readonly muted?: boolean;
- readonly className?: string | undefined;
}) {
- const tone = left === null ? null : left <= 10 ? "error" : left <= 20 ? "warning" : null;
return (
<Tooltip>
<TooltipTrigger
render={
<div
tabIndex={0}
- aria-label={`${label}: ${value ?? `${left}% left`}`}
- className={cn(
- "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]",
- className,
- )}
+ aria-label={`${label}: ${ariaValue}`}
+ 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]"
/>
}
>
<span className="max-w-28 truncate text-muted-foreground">{label}</span>
- {left !== null ? (
+ {fill !== null ? (
<span className="relative h-[3px] rounded-full bg-muted-foreground/30 dark:bg-muted-foreground/20">
- {left > 0 ? (
+ {fill > 0 ? (
<span
className={cn(
"absolute inset-y-0 left-0 rounded-full",
@@ -197,7 +221,14 @@ function UsageRow({
? "bg-muted-foreground"
: "bg-foreground/80",
)}
- style={{ width: `max(${left}%, 6px)` }}
+ style={{ width: `max(${fill}%, 6px)` }}
+ />
+ ) : null}
+ {tick !== null ? (
+ <span
+ aria-hidden
+ className="absolute -top-[3px] h-[9px] w-px -translate-x-1/2 bg-foreground/60"
+ style={{ left: `${tick}%` }}
/>
) : null}
</span>
@@ -206,17 +237,17 @@ function UsageRow({
className={cn(
// Text-only rows span the bar column so they never widen the shared value column.
"text-end font-medium tabular-nums",
- left === null && "col-span-2",
+ fill === null && "col-span-2",
tone === "error"
? "text-error-foreground"
: tone === "warning"
? "text-warning-foreground"
- : left === null
+ : fill === null
? "text-muted-foreground"
: "text-foreground/80",
)}
>
- {value ?? `${left}%`}
+ {value}
</span>
</TooltipTrigger>
{/* Rows sit 8px inside the card; clear its edge instead of overlapping it. */}
diff --git a/apps/web/src/components/chat/threadDetailsItems.test.ts b/apps/web/src/components/chat/threadDetailsItems.test.ts
index 0a0787061d2..6e3e746fd76 100644
--- a/apps/web/src/components/chat/threadDetailsItems.test.ts
+++ b/apps/web/src/components/chat/threadDetailsItems.test.ts
@@ -11,16 +11,17 @@ const servers = THREAD_DETAILS_ITEMS.find((item) => item.id === "servers")!;
describe("thread details items", () => {
it.each([
- { legacy: false, items: {}, usage: false },
- { legacy: true, items: {}, usage: true },
- { legacy: true, items: { usage: false }, usage: false },
- { legacy: false, items: { usage: true, retired: false }, usage: true },
- ])("resolves Usage from overrides and the retired Labs flag: %o", (row) => {
+ { legacy: false, items: {}, usage: false, context: false },
+ { legacy: true, items: {}, usage: true, context: true },
+ { legacy: true, items: { usage: false }, usage: false, context: true },
+ { legacy: false, items: { usage: true, retired: false }, usage: true, context: false },
+ ])("resolves Usage and Context from overrides and the retired Labs flag: %o", (row) => {
const visibility = resolveThreadDetailsVisibility({
threadDetailsItems: row.items,
threadDetailsUsageEnabled: row.legacy,
});
expect(visibility.usage).toBe(row.usage);
+ expect(visibility.context).toBe(row.context);
expect(visibility.servers).toBe(true);
});
diff --git a/apps/web/src/components/chat/threadDetailsItems.ts b/apps/web/src/components/chat/threadDetailsItems.ts
index 7502a4c0b1d..9922b1b8a0b 100644
--- a/apps/web/src/components/chat/threadDetailsItems.ts
+++ b/apps/web/src/components/chat/threadDetailsItems.ts
@@ -11,7 +11,8 @@ export const THREAD_DETAILS_ITEMS = [
{ id: "servers", label: "Servers", defaultVisible: true },
{ id: "automations", label: "Automations", defaultVisible: true },
{ id: "lineage", label: "Lineage", defaultVisible: true },
- { id: "usage", label: "Usage", defaultVisible: false },
+ { id: "usage", label: "Usage limits", defaultVisible: false },
+ { id: "context", label: "Context window", defaultVisible: false },
] as const;
export type ThreadDetailsItemId = (typeof THREAD_DETAILS_ITEMS)[number]["id"];
@@ -23,9 +24,11 @@ type ThreadDetailsItemSettings = Pick<
"threadDetailsItems" | "threadDetailsUsageEnabled"
>;
-// People who turned on the retired Labs toggle keep Usage until they change it here.
+// People who turned on the retired Labs toggle keep Usage and Context until they change them here.
function defaultVisible(item: ThreadDetailsItem, settings: ThreadDetailsItemSettings) {
- return item.id === "usage" ? settings.threadDetailsUsageEnabled : item.defaultVisible;
+ return item.id === "usage" || item.id === "context"
+ ? settings.threadDetailsUsageEnabled
+ : item.defaultVisible;
}
export function resolveThreadDetailsVisibility(
@@ -53,7 +56,7 @@ export function isDefaultThreadDetailsVisibility(visibility: ThreadDetailsVisibi
return THREAD_DETAILS_ITEMS.every((item) => visibility[item.id] === item.defaultVisible);
}
-/** Also clears the retired Labs flag, so Usage returns to off. */
+/** Also clears the retired Labs flag, so Usage and Context return to off. */
export const RESET_THREAD_DETAILS_ITEMS = {
threadDetailsItems: {},
threadDetailsUsageEnabled: false,
diff --git a/docs/user/usage.md b/docs/user/usage.md
index af1fc02352f..447924a072e 100644
--- a/docs/user/usage.md
+++ b/docs/user/usage.md
@@ -120,11 +120,12 @@ current model's limits without leaving the conversation. The result opens above
closes when you dismiss it or send your next message. It uses the same snapshot as **Usage → Limits**, so it does not run the agent or refresh
anything. The command is offered only for providers that appear under **Usage → Limits**.
-To keep them in view on web and desktop, turn on **Usage** in **Settings → Appearance → Thread details**, or right-click the thread details card.
+To keep them in view on web and desktop, turn on **Usage limits** in **Settings → Appearance → Thread details**, or right-click the thread details card.
The bottom of the thread details card then shows how much is left in each limit window of the
-current provider account and in the thread's context window. Some windows, such as a weekly Opus
-limit, count only one model. Hover a row to see when it resets, your pace, or
-the token count.
+current provider account. Some windows, such as a weekly Opus limit, count only one model. Hover a
+row to see when it resets and your pace. Turn on **Context window** to also show the thread's
+context use against the model's limit. A tick on the bar marks where the provider compacts
+automatically, when it reports that point.
OpenCode Go reports its session, weekly, and monthly allowance when OpenCode runs locally in
the environment. T3 cannot report limits for external OpenCode servers because their credentials