Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added .github/pr-assets/context-token-count-before.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions apps/desktop/src/settings/DesktopClientSettings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const clientSettings: ClientSettings = {
glassOpacity: 80,
planModeEnabled: false,
providerModelPreferences: {},
showContextWindowTokenCount: false,
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
sidebarProjectGroupingMode: "repository_path",
Expand Down
13 changes: 8 additions & 5 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ import {
renderProviderTraitsMenuContent,
renderProviderTraitsPicker,
} from "./composerProviderState";
import { ContextWindowMeter } from "./ContextWindowMeter";
import { ContextWindowMeter, ContextWindowTokenCount } from "./ContextWindowMeter";
import { resolveContextWindowModelDisplayName } from "./ContextWindowMeter.logic";
import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
import { basenameOfPath } from "../../pierre-icons";
Expand Down Expand Up @@ -421,10 +421,13 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
return (
<>
{props.activeContextWindow ? (
<ContextWindowMeter
usage={props.activeContextWindow}
modelDisplayName={props.activeThreadModelDisplayName}
/>
<>
<ContextWindowTokenCount usage={props.activeContextWindow} />
<ContextWindowMeter
usage={props.activeContextWindow}
modelDisplayName={props.activeThreadModelDisplayName}
/>
</>
) : null}
{props.isPreparingWorktree ? (
<span className="text-secondary-label text-xs">Preparing worktree...</span>
Expand Down
33 changes: 33 additions & 0 deletions apps/web/src/components/chat/ContextWindowMeter.logic.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ProviderInstanceId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
contextWindowSeverityColor,
formatContextWindowCompactionMessage,
resolveContextWindowModelDisplayName,
} from "./ContextWindowMeter.logic";
Expand Down Expand Up @@ -56,3 +57,35 @@ describe("formatContextWindowCompactionMessage", () => {
);
});
});

describe("contextWindowSeverityColor", () => {
const green = "var(--color-success)";
const orange = "color-mix(in oklab, var(--color-warning) 50%, var(--color-error))";
const red = "var(--color-error)";

it("is green below the 160k threshold", () => {
expect(contextWindowSeverityColor(0)).toBe(green);
expect(contextWindowSeverityColor(80_000)).toBe(green);
expect(contextWindowSeverityColor(159_999)).toBe(green);
});

it("is orange from 160k up to the 250k threshold", () => {
expect(contextWindowSeverityColor(160_000)).toBe(orange);
expect(contextWindowSeverityColor(205_000)).toBe(orange);
expect(contextWindowSeverityColor(249_999)).toBe(orange);
});

it("is red at and above 250k", () => {
expect(contextWindowSeverityColor(250_000)).toBe(red);
expect(contextWindowSeverityColor(900_000)).toBe(red);
});

it("ignores how full the model's window is, banding on absolute tokens only", () => {
// A tiny window can sit at 99% used and still be a small, healthy context.
expect(contextWindowSeverityColor(8_000)).toBe(green);
});

it("treats missing usage as empty rather than severe", () => {
expect(contextWindowSeverityColor(null)).toBe(green);
});
});
29 changes: 29 additions & 0 deletions apps/web/src/components/chat/ContextWindowMeter.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,32 @@ export function formatContextWindowCompactionMessage(
? `Context for ${modelDisplayName} compacts automatically when needed.`
: "Context compacts automatically when needed.";
}

/**
* Absolute used-token thresholds for context severity. They track where agents
* start losing the plot, which happens at roughly the same absolute sizes no
* matter how large a window the model advertises - so the model's own context
* limit deliberately plays no part in the banding.
*/
const SEVERITY_ORANGE_TOKENS = 160_000;

/** At and above this, context is bad enough to also earn a warning glyph. */
export const CONTEXT_WINDOW_CRITICAL_TOKENS = 250_000;

/**
* Theme color for the meter's count and progress stroke, in three discrete
* bands: green below 160k used tokens, orange up to 250k, red from there up.
* The theme's warning token is amber rather than a true orange, so the middle
* band is a fixed half-blend toward error.
*/
export function contextWindowSeverityColor(usedTokens: number | null): string {
const tokens = typeof usedTokens === "number" && Number.isFinite(usedTokens) ? usedTokens : 0;

if (tokens >= CONTEXT_WINDOW_CRITICAL_TOKENS) {
return "var(--color-error)";
}
if (tokens >= SEVERITY_ORANGE_TOKENS) {
return "color-mix(in oklab, var(--color-warning) 50%, var(--color-error))";
}
return "var(--color-success)";
}
41 changes: 39 additions & 2 deletions apps/web/src/components/chat/ContextWindowMeter.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { TriangleAlertIcon } from "lucide-react";
import { Button } from "../ui/button";
import { type ContextWindowSnapshot, formatContextWindowTokens } from "~/lib/contextWindow";
import { useClientSettings } from "~/hooks/useSettings";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { formatContextWindowCompactionMessage } from "./ContextWindowMeter.logic";
import {
CONTEXT_WINDOW_CRITICAL_TOKENS,
contextWindowSeverityColor,
formatContextWindowCompactionMessage,
} from "./ContextWindowMeter.logic";

function formatPercentage(value: number | null): string | null {
if (value === null || !Number.isFinite(value)) {
Expand All @@ -13,6 +19,31 @@ function formatPercentage(value: number | null): string | null {
return `${Math.round(value)}%`;
}

/**
* Used-token count for the composer footer, sitting immediately left of the
* meter ring when the user opts in. Presentational only: the ring next to it
* owns the hover popover.
*/
export function ContextWindowTokenCount(props: { usage: ContextWindowSnapshot }) {
const showTokenCount = useClientSettings((settings) => settings.showContextWindowTokenCount);
if (!showTokenCount) {
return null;
}

const { usedTokens } = props.usage;
return (
<span
className="flex items-center gap-1 text-xs tabular-nums transition-colors duration-500 ease-out motion-reduce:transition-none"
style={{ color: contextWindowSeverityColor(usedTokens) }}
>
{(usedTokens ?? 0) >= CONTEXT_WINDOW_CRITICAL_TOKENS ? (
<TriangleAlertIcon className="size-3" aria-hidden="true" />
) : null}
{formatContextWindowTokens(usedTokens)}
</span>
);
}

export function ContextWindowMeter(props: {
usage: ContextWindowSnapshot;
modelDisplayName?: string | null;
Expand All @@ -29,6 +60,12 @@ export function ContextWindowMeter(props: {
const usageColor = isOverloaded
? "var(--color-error)"
: "color-mix(in oklab, var(--color-muted-foreground) 72%, transparent)";
const showTokenCount = useClientSettings((settings) => settings.showContextWindowTokenCount);
// Opting into the count also opts the ring into severity coloring, so the
// number and the arc never disagree. A nearly full window still wins, so a
// small model's saturation keeps the overload red it had before.
const ringColor =
showTokenCount && !isOverloaded ? contextWindowSeverityColor(usage.usedTokens) : usageColor;

return (
<Popover>
Expand Down Expand Up @@ -66,7 +103,7 @@ export function ContextWindowMeter(props: {
cy="12"
r={radius}
fill="none"
stroke={usageColor}
stroke={ringColor}
strokeWidth="3"
strokeLinecap="round"
strokeDasharray={circumference}
Expand Down
40 changes: 40 additions & 0 deletions apps/web/src/components/settings/SettingsPanels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,10 @@ export function useSettingsRestore(onRestored?: () => void) {
? ["Auto-settle merged threads"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
...(settings.showContextWindowTokenCount !==
DEFAULT_UNIFIED_SETTINGS.showContextWindowTokenCount
? ["Context window token count"]
: []),
...getChangedTypographySettingLabels(settings),
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
? ["Diff whitespace changes"]
Expand Down Expand Up @@ -568,6 +572,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
settings.wordWrap,
settings.showContextWindowTokenCount,
followSystem,
theme,
themeHalves,
Expand Down Expand Up @@ -639,6 +644,7 @@ export function useSettingsRestore(onRestored?: () => void) {
updateSettings({
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
showContextWindowTokenCount: DEFAULT_UNIFIED_SETTINGS.showContextWindowTokenCount,
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode,
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
Expand Down Expand Up @@ -1318,6 +1324,39 @@ function WordWrapRow() {
);
}

function ContextWindowTokenCountRow() {
const settings = usePrimarySettings();
const updateSettings = useUpdatePrimarySettings();
return (
<SettingsRow
{...searchableSetting("context-window-token-count")}
description="Print the used token count next to the composer's context window ring, colored green, orange, then red as tokens accumulate."
resetAction={
settings.showContextWindowTokenCount !==
DEFAULT_UNIFIED_SETTINGS.showContextWindowTokenCount ? (
<SettingResetButton
label="context window token count"
onClick={() =>
updateSettings({
showContextWindowTokenCount: DEFAULT_UNIFIED_SETTINGS.showContextWindowTokenCount,
})
}
/>
) : null
}
control={
<Switch
checked={settings.showContextWindowTokenCount}
onCheckedChange={(checked) =>
updateSettings({ showContextWindowTokenCount: Boolean(checked) })
}
aria-label="Show context window token count"
/>
}
/>
);
}

function FontSettingsGroup() {
return (
<>
Expand Down Expand Up @@ -1415,6 +1454,7 @@ function TypographySection() {
>
{advanced ? <FontSettingsGroup /> : <SimpleFontRows />}
<WordWrapRow />
<ContextWindowTokenCountRow />
</SettingsSection>
);
}
Expand Down
5 changes: 5 additions & 0 deletions apps/web/src/components/settings/settingsSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Word wrap",
to: "/settings/appearance",
},
{
id: "context-window-token-count",
title: "Show context window token count",
to: "/settings/appearance",
},
{
id: "project-grouping",
title: "Project grouping",
Expand Down
6 changes: 6 additions & 0 deletions packages/contracts/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,11 @@ export const ClientSettingsSchema = Schema.Struct({
// old keys, so everyone, including prior beta opt-outs, resets to the new
// default sidebar.
legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
// Print the composer's used context tokens next to the meter ring instead of
// only inside its popover. Off by default so the ring stays as shipped.
showContextWindowTokenCount: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
),
sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
),
Expand Down Expand Up @@ -903,6 +908,7 @@ export const ClientSettingsPatch = Schema.Struct({
),
planModeEnabled: Schema.optionalKey(Schema.Boolean),
legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
showContextWindowTokenCount: Schema.optionalKey(Schema.Boolean),
sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
Expand Down
Loading