Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(settings): keep neighbouring model token limits distinguishable

vastsafe53b2771b28
diff --git a/apps/desktop/src/components/ContextUsageInspector.tsx b/apps/desktop/src/components/ContextUsageInspector.tsx
index fe41e7fe1..d1e36bb23 100644
--- a/apps/desktop/src/components/ContextUsageInspector.tsx
+++ b/apps/desktop/src/components/ContextUsageInspector.tsx
@@ -8,7 +8,11 @@ import {
} from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
-import type { MessageUsage, UiMessage } from "@pi-desktop/shared";
+import {
+ formatCompactTokenCount,
+ type MessageUsage,
+ type UiMessage,
+} from "@pi-desktop/shared";
import { useAppStore } from "../stores/app-store";
import { TooltipButton } from "./ui";
import {
@@ -25,13 +29,6 @@ import {
type ContextInspectorPlacement,
} from "../lib/context-inspector-position";
-function formatTokenCount(value: number): string {
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M`;
- if (value >= 10_000) return `${Math.round(value / 1000)}k`;
- if (value >= 1000) return `${(value / 1000).toFixed(1)}k`;
- return String(value);
-}
-
const CONTEXT_RING_RADIUS = 9;
const CONTEXT_RING_CIRCUMFERENCE = 2 * Math.PI * CONTEXT_RING_RADIUS;
@@ -101,7 +98,7 @@ export function ContextUsageInspector({
// tooltip contract while `percent`/`count` stay numeric.
const ariaArguments = {
percent: display.percent,
- count: formatTokenCount(display.tokens),
+ count: formatCompactTokenCount(display.tokens),
state:
display.display === "used"
? t("chat.usageContextAriaUsed")
@@ -264,10 +261,10 @@ export function ContextUsageInspector({
<strong className="context-inspector-heading-value">
{display.display === "used"
? t("chat.usageContextSpent", {
- count: formatTokenCount(display.tokens),
+ count: formatCompactTokenCount(display.tokens),
})
: t("chat.usageContextLeft", {
- count: formatTokenCount(display.tokens),
+ count: formatCompactTokenCount(display.tokens),
})}
</strong>
<strong className="context-inspector-heading-percent">
@@ -278,8 +275,8 @@ export function ContextUsageInspector({
<span>{t("chat.usageContextWindow")}</span>
<strong>
{t("chat.usageContextTokens", {
- used: formatTokenCount(context.usedTokens),
- window: formatTokenCount(contextWindow),
+ used: formatCompactTokenCount(context.usedTokens),
+ window: formatCompactTokenCount(contextWindow),
})}
</strong>
<span className="context-inspector-window-percent">
@@ -289,7 +286,7 @@ export function ContextUsageInspector({
<div className="context-inspector-kpis">
<div>
<span>{t("chat.usageTurnTotal")}</span>
- <strong>{formatTokenCount(turnTotal)}</strong>
+ <strong>{formatCompactTokenCount(turnTotal)}</strong>
</div>
<div>
<span>{t("chat.usageThroughputLabel")}</span>
@@ -301,7 +298,7 @@ export function ContextUsageInspector({
? "chat.usageThroughputEstimated"
: "chat.usageThroughput",
{
- count: formatTokenCount(throughput),
+ count: formatCompactTokenCount(throughput),
},
)}
</strong>
@@ -312,14 +309,14 @@ export function ContextUsageInspector({
<strong>{t("chat.usageProviderUsage")}</strong>
<span className="context-inspector-summary-values">
<span>
- {t("chat.usageInput")} {formatTokenCount(usage.inputTokens)}
+ {t("chat.usageInput")} {formatCompactTokenCount(usage.inputTokens)}
</span>
<span>
- {t("chat.usageOutput")} {formatTokenCount(usage.outputTokens)}
+ {t("chat.usageOutput")} {formatCompactTokenCount(usage.outputTokens)}
</span>
{usage.cacheReadTokens !== undefined ? (
<span>
- {t("chat.usageCacheRead")} {formatTokenCount(usage.cacheReadTokens)}
+ {t("chat.usageCacheRead")} {formatCompactTokenCount(usage.cacheReadTokens)}
</span>
) : null}
{cacheRate !== undefined ? (
@@ -329,12 +326,12 @@ export function ContextUsageInspector({
) : null}
{usage.cacheWriteTokens !== undefined ? (
<span>
- {t("chat.usageCacheWrite")} {formatTokenCount(usage.cacheWriteTokens)}
+ {t("chat.usageCacheWrite")} {formatCompactTokenCount(usage.cacheWriteTokens)}
</span>
) : null}
{usage.reasoningTokens !== undefined ? (
<span>
- {t("chat.usageReasoning")} {formatTokenCount(usage.reasoningTokens)}
+ {t("chat.usageReasoning")} {formatCompactTokenCount(usage.reasoningTokens)}
</span>
) : null}
</span>
@@ -346,7 +343,7 @@ export function ContextUsageInspector({
? t("chat.usageToolsSummary", {
count: toolRows.length,
calls: tools.length,
- tokens: formatTokenCount(toolTotal),
+ tokens: formatCompactTokenCount(toolTotal),
})
: t("chat.usageNoTools")}
</span>
@@ -357,7 +354,7 @@ export function ContextUsageInspector({
<span>
{t("chat.usageCompaction", { times: compaction.generation })}
</span>
- <strong>~{formatTokenCount(compaction.summaryTokens)}</strong>
+ <strong>~{formatCompactTokenCount(compaction.summaryTokens)}</strong>
</div>
) : null}
</div>
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
index ea9d56df0..b88fa133d 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
@@ -8,6 +8,7 @@ import type {
AgentActivity,
ContextCompactionMark,
} from "@pi-desktop/shared";
+import { formatCompactTokenCount } from "@pi-desktop/shared";
import {
assistantTurnContent,
assistantTurnMessages,
@@ -31,7 +32,6 @@ import {
AssistantErrorMessage,
CopyButton,
MessageMeta,
- formatTokenCount,
} from "./shared";
import { activityItemsEqual, ActivityGroup } from "./ActivityGroup";
import { MessageRow } from "./MessageRow";
@@ -372,7 +372,7 @@ export function CompactionRow({ mark }: { mark: ContextCompactionMark }) {
<span className="transcript-compaction-detail">
{mark.summarized
? t("chat.compactionRowSummary", {
- tokens: formatTokenCount(mark.summaryTokens),
+ tokens: formatCompactTokenCount(mark.summaryTokens),
})
: t("chat.compactionRowNoSummary")}
</span>
diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsx
index 7d338f448..f04976f39 100644
--- a/apps/desktop/src/features/chat/transcript/shared.tsx
+++ b/apps/desktop/src/features/chat/transcript/shared.tsx
@@ -14,6 +14,7 @@ import type {
UiMessage,
} from "@pi-desktop/shared";
import {
+ formatCompactTokenCount,
THINKING_LEVELS,
type ThinkingLevel,
} from "@pi-desktop/shared";
@@ -88,16 +89,6 @@ export function CopyButton({
</TooltipButton>
);
}
-
-
-export function formatTokenCount(value: number): string {
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M`;
- if (value >= 10_000) return `${Math.round(value / 1000)}k`;
- if (value >= 1000) return `${(value / 1000).toFixed(1)}k`;
- return String(value);
-}
-
-
export function MessageMeta({
modelId,
usage,
@@ -128,7 +119,7 @@ export function MessageMeta({
{showThroughput ? (
<span className="message-meta-chip throughput">
{t("chat.usageThroughputEstimated", {
- count: formatTokenCount(throughput),
+ count: formatCompactTokenCount(throughput),
})}
</span>
) : null}
diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.md
index 496276fc4..4997ac232 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -56,6 +56,15 @@ entitled to it.
and the runtime uses the binding's explicit set. A model that publishes no
level list and no level map but does claim reasoning still seeds
`low`/`medium`/`high`.
+- Limit values render through one shared compact formatter
+ (`formatCompactTokenCount`): up to two decimals at the `M` scale and one at
+ the `K` scale, trailing zeros dropped, and a `K` mantissa that would round up
+ to 1000 promoted to the `M` scale. Published windows on the 1M line therefore
+ stay distinguishable — 1000000 reads `1M`, 1048576 and 1050000 read `1.05M`,
+ 1100000 reads `1.1M` — instead of collapsing into one rounded `1M`/`1.1M`, and
+ a limit the service never published reads as an em dash. The settings rows,
+ the Composer picker, the context inspector and the transcript all call this
+ one implementation, while usage counters keep a real `0` instead of the dash.
- When an explicit binding enables `xhigh` or `max` without a catalog wire
mapping, the runtime sends that canonical value through to the adapter rather
than letting the adapter clamp it to `high`. Existing non-null catalog
@@ -458,3 +467,6 @@ same model to the check mark, the toggle and the duplicate guard.
- [ ] unknown free-form models remain runnable without invented capabilities
- [ ] a models.dev record and an unknown generic record resolve through the same
selected transport without sending provider credentials to the remote catalog
+- [ ] compact limit text never reads above the published value, keeps the
+ neighbouring 1M-line windows apart (`1M` / `1.05M` / `1.1M`), and never
+ renders a `K` mantissa at or above 1000
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 4a6056ea3..93b9196b7 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -237,8 +237,9 @@ a usage tab.
action that re-probes the service immediately. Each selected model has an independent, compact
configuration row for context window, max output, supported thinking
levels, and the default thinking level. The row keeps the model ID,
- source, capabilities, and token limits visible at a glance, and expands
- in place for edits. The expanded body is a compact sheet, not a stacked
+ source, capabilities, and token limits visible at a glance in one shared
+ compact form that keeps neighbouring windows apart (`1.05M · 128K`), and
+ expands in place for edits. The expanded body is a compact sheet, not a stacked
form dump: 2xs labels, dense numeric fields without native spinners, the
alias hint as a title tooltip rather than a paragraph, the default
thinking selector on the thinking label row, and attachments plus
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 5176f3762..8ba56d93c 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -441,8 +441,8 @@ identify the platform validation still needed.
#### E2E-005: Add a provider and save API key
- **Preconditions**: App running; no provider configured; the models.dev snapshot ships with the build.
-- **Steps**: 1) Open Settings → Model configuration and choose Add provider. 2) Confirm the dialog is ONE form with no stepper or Next/Back buttons. The first control is Service — a searchable menu (Choose a service, Custom endpoint, then a flat vendor list from models.dev including Xiaomi), not a native select, region grouping, or vendor-card grid. Open it, type to filter client-side, then choose **Custom endpoint**. Confirm Name and Base URL appear on one row with no helper paragraph under the URL (placeholder only), API Key and API format appear side by side on the next row (not behind Advanced), and that a focused field plus its 2px accent ring stays fully inside the dialog, including on a window narrower than 1040px. 3) Enter a name and a base URL for a service that publishes a `/models` route, then paste an API key. 4) Confirm the models section fills with the models THAT SERVICE returned, not with every model its vendor publishes; confirm a model the deployment does not host is absent. 5) Type in the filter box and confirm the list narrows client-side with no network request per keystroke. 6) Confirm each row shows the models.dev-derived context/output for models the catalog knows, and that a model with no catalog match still lists with generic defaults. 7) Select two models with the checkboxes. 8) Expand Advanced on one chosen row, override its limits and toggle thinking chips; confirm each numeric field has a five-chip preset ladder for common values, clicking a chip writes the value, hand editing remains possible, and a non-preset value leaves the ladder unselected. Confirm the label and optional hint sit above one compact grouped control and do not force the options onto a second row at normal dialog width; confirm all seven canonical levels are available, that published levels start selected for a known reasoning model, and that a non-reasoning or unknown row shows the same chips unselected with the manual-override hint; enable one level on that row and confirm the other row is unaffected. 9) Open the form-level Advanced and confirm the API format is present but pre-derived. 10) Add a free-form model ID the service did not return; confirm it is added with 128,000 / 8,192 / no-thinking defaults, then enable a thinking level if the endpoint supports it; confirm re-adding the same ID in different letter case is rejected as already added. 11) Save.
-- **Expected**: The service is asked first and models.dev only enriches the answer and seeds known-model defaults. The settings picker always offers the seven canonical thinking levels, and the Composer later renders the explicit levels saved in the same model binding; an empty or `off`-only binding resolves to `off`. Discovery is debounced ~600 ms, does not mark loading until that window elapses, and a slow reply from an earlier keystroke never replaces a newer list; named add-path discovery waits for an API key, while an unsaved custom provider is probed with the typed base URL (and key, if any) before it exists. Preset ladders cover common context/output limits while preserving hand-edited values. Custom endpoint keeps API format beside the key and omits Base URL helper copy; named endpoints do not show format. Point the same custom form at an unreachable or unauthorized URL and confirm the left pane shows a classified error (not a raw JSON/HTML dump and not a second “no models” empty state); with cached rows from a later edit, the same error is a one-line banner above the list. Point a second provider at a base URL with no `/models` route and confirm the list falls back to the catalog, is labelled as coming from models.dev rather than the service, and still saves. The provider appears as a row with its host, model count and secret badge; the key is stored securely (not in plaintext config); `models` contains both bindings and `models[0]` remains the provider default.
+- **Steps**: 1) Open Settings → Model configuration and choose Add provider. 2) Confirm the dialog is ONE form with no stepper or Next/Back buttons. The first control is Service — a searchable menu (Choose a service, Custom endpoint, then a flat vendor list from models.dev including Xiaomi), not a native select, region grouping, or vendor-card grid. Open it, type to filter client-side, then choose **Custom endpoint**. Confirm Name and Base URL appear on one row with no helper paragraph under the URL (placeholder only), API Key and API format appear side by side on the next row (not behind Advanced), and that a focused field plus its 2px accent ring stays fully inside the dialog, including on a window narrower than 1040px. 3) Enter a name and a base URL for a service that publishes a `/models` route, then paste an API key. 4) Confirm the models section fills with the models THAT SERVICE returned, not with every model its vendor publishes; confirm a model the deployment does not host is absent. 5) Type in the filter box and confirm the list narrows client-side with no network request per keystroke. 6) Confirm each row shows the models.dev-derived context/output for models the catalog knows, that its compact text tracks the published value instead of a coarser rounded one (a 1,050,000 window reads `1.05M`, never `1.1M`), and that a model with no catalog match still lists with generic defaults. 7) Select two models with the checkboxes. 8) Expand Advanced on one chosen row, override its limits and toggle thinking chips; confirm each numeric field has a five-chip preset ladder for common values, clicking a chip writes the value, hand editing remains possible, and a non-preset value leaves the ladder unselected. Confirm the label and optional hint sit above one compact grouped control and do not force the options onto a second row at normal dialog width; confirm all seven canonical levels are available, that published levels start selected for a known reasoning model, and that a non-reasoning or unknown row shows the same chips unselected with the manual-override hint; enable one level on that row and confirm the other row is unaffected. 9) Open the form-level Advanced and confirm the API format is present but pre-derived. 10) Add a free-form model ID the service did not return; confirm it is added with 128,000 / 8,192 / no-thinking defaults, then enable a thinking level if the endpoint supports it; confirm re-adding the same ID in different letter case is rejected as already added. 11) Save.
+- **Expected**: The service is asked first and models.dev only enriches the answer and seeds known-model defaults. The settings picker always offers the seven canonical thinking levels, and the Composer later renders the explicit levels saved in the same model binding; an empty or `off`-only binding resolves to `off`. Discovery is debounced ~600 ms, does not mark loading until that window elapses, and a slow reply from an earlier keystroke never replaces a newer list; named add-path discovery waits for an API key, while an unsaved custom provider is probed with the typed base URL (and key, if any) before it exists. Preset ladders cover common context/output limits while preserving hand-edited values. Limit text renders through one shared compact formatter, so neighbouring published windows stay distinguishable (`1M` / `1.05M` / `1.1M`) and a compact limit never reads above its published value. Custom endpoint keeps API format beside the key and omits Base URL helper copy; named endpoints do not show format. Point the same custom form at an unreachable or unauthorized URL and confirm the left pane shows a classified error (not a raw JSON/HTML dump and not a second “no models” empty state); with cached rows from a later edit, the same error is a one-line banner above the list. Point a second provider at a base URL with no `/models` route and confirm the list falls back to the catalog, is labelled as coming from models.dev rather than the service, and still saves. The provider appears as a row with its host, model count and secret badge; the key is stored securely (not in plaintext config); `models` contains both bindings and `models[0]` remains the provider default.
- **Specs linked**: `03-runtime/11-provider-model-system.md`, `03-runtime/12-provider-config-schema.md`, `03-runtime/13-model-catalog-and-selection.md`, `03-runtime/14-secrets-storage.md`, `04-ux/06-settings-ia.md`
- **Acceptance**: B (multi-model provider configuration, save key)
- **Milestone**: M2
diff --git a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
index 465fd7f53..d2a9636a4 100644
--- a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
@@ -35,6 +35,12 @@
- 提供商名称
- 能力徽章
- 可选的上下文窗口
+- 上限值与用量计数经同一个紧凑格式化函数(`formatCompactTokenCount`)渲染:
+ `M` 量级最多两位小数、`K` 量级一位小数,去掉末尾零;`K` 尾数若进位到 1000
+ 则提升到 `M` 量级。1M 附近的已发布窗口因此保持可区分(1000000 显示 `1M`,
+ 1048576 与 1050000 显示 `1.05M`,1100000 显示 `1.1M`),不会塌缩成同一个
+ `1M`/`1.1M`;服务未发布的上限显示为破折号,用量计数则保留真实的 `0`。
+ 设置行、Composer 选择器、上下文检查器和聊天记录共用这一份实现。
### 子智能体编辑器
@@ -281,3 +287,5 @@ Electron 使用本地 `models.dev` 记录装饰缓存和新发现的模型行。
- [ ] 提供程序设置和缓存发现无法覆盖已知的 pi 模型
- [ ] 未知的自由形式模型在没有发明功能的情况下仍然可以运行
- [ ] 固定 pi-ai ^0.82.1+ 将 `claude-opus-5`(和网关兼容的别名)解析为已发布的 1M 上下文自适应思维记录,无需桌面覆盖
+- [ ] 紧凑上限文本不会高于已发布值,1M 附近的相邻窗口保持可区分
+ (`1M` / `1.05M` / `1.1M`),且永远不会渲染出大于等于 1000 的 `K` 尾数
diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index adbc1efc1..688b7ddbb 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -141,6 +141,8 @@ Token 用量**不是设置目的地**(D335 / ADR 0173)。已完成回合历
- “编辑账户”打开的对话框带有账户标签,以及与 AI 服务对话框完全相同的双栏
模型选择器(D270):左侧是该账户已发现/有权使用的模型(列表标题旁可全选当前可见行,并可立刻获取列表),右侧是已选绑定,
每个模型在“高级”折叠区里可编辑别名、上下文窗口、输出上限、思考等级与附件能力;
+ 行内以统一的紧凑格式显示模型 ID、来源、能力与上限(如 `1.05M · 128K`),
+ 相邻窗口不会被舍入成同一个字符串;
展开区是紧凑表单:别名说明放在输入框 title 上,数字框去掉原生步进按钮,思考档铺满一行且默认档与标签同行,附件与委派勾选同一行。
因此两种凭据的模型选择完全一致。账户没有 API 密钥输入框,模型发现改由已保存
的 OAuth 登录解析。保存会更新该 OAuth 提供商行,并在该账户被选为默认时同步
diff --git a/packages/shared/src/model-catalog.test.ts b/packages/shared/src/model-catalog.test.ts
index 9e4ee30ce..dd9044a50 100644
--- a/packages/shared/src/model-catalog.test.ts
+++ b/packages/shared/src/model-catalog.test.ts
@@ -5,6 +5,8 @@ import {
bindingSupportsDocuments,
effectiveContextWindow,
bindingSupportsImages,
+ formatCompactTokenCount,
+ formatTokenCount,
modelMatchesFilter,
normalizeApiStyle,
} from "./model-catalog.js";
@@ -92,3 +94,50 @@ describe("effective binding attachment capabilities", () => {
expect(bindingSupportsImages({ supportsImages: true }, null)).toBe(true);
});
});
+
+describe("compact token counts", () => {
+ it("keeps neighbouring published windows distinguishable", () => {
+ // models.dev publishes all three of these along the 1M line. One rounded
+ // decimal collapsed them into `1M` / `1.1M` / `1.1M`.
+ const rendered = [
+ formatTokenCount(1_000_000),
+ formatTokenCount(1_050_000),
+ formatTokenCount(1_100_000),
+ ];
+ expect(rendered).toEqual(["1M", "1.05M", "1.1M"]);
+ expect(new Set(rendered).size).toBe(3);
+ });
+
+ it("never reports a window above the published value's own precision", () => {
+ // `1.1M` overstated 1,050,000 by 50k tokens, which is what made unrelated
+ // models look like they shared one limit.
+ expect(formatTokenCount(1_050_000)).not.toBe("1.1M");
+ expect(formatTokenCount(1_048_576)).toBe("1.05M");
+ expect(formatTokenCount(1_064_000)).toBe("1.06M");
+ expect(formatTokenCount(1_131_072)).toBe("1.13M");
+ });
+
+ it("keeps the K and M scales exact at their boundaries", () => {
+ expect(formatTokenCount(999)).toBe("999");
+ expect(formatTokenCount(1_000)).toBe("1K");
+ expect(formatTokenCount(1_500)).toBe("1.5K");
+ expect(formatTokenCount(200_000)).toBe("200K");
+ expect(formatTokenCount(262_144)).toBe("262.1K");
+ expect(formatTokenCount(10_000_000)).toBe("10M");
+ });
+
+ it("promotes a K mantissa instead of rendering `1000K`", () => {
+ expect(formatTokenCount(999_949)).toBe("999.9K");
+ expect(formatTokenCount(999_999)).toBe("1M");
+ expect(formatTokenCount(1_000_000)).toBe("1M");
+ });
+
+ it("reads an unpublished limit as absent, but a real count as a number", () => {
+ expect(formatTokenCount(undefined)).toBe("—");
+ expect(formatTokenCount(0)).toBe("—");
+ // Usage counters report a real zero, so they must not borrow the dash.
+ expect(formatCompactTokenCount(0)).toBe("0");
+ expect(formatCompactTokenCount(12)).toBe("12");
+ expect(formatCompactTokenCount(1_500)).toBe("1.5K");
+ });
+});
diff --git a/packages/shared/src/model-catalog.ts b/packages/shared/src/model-catalog.ts
index 60273d080..4d5fc8946 100644
--- a/packages/shared/src/model-catalog.ts
+++ b/packages/shared/src/model-catalog.ts
@@ -204,18 +204,46 @@ export function bindingForCustomModel(id: string): ModelBinding {
};
}
-/** Compact token count for dense UI, e.g. `200K`, `1M`. */
+/**
+ * Drop a fraction's trailing zeros: `200.0` reads `200` and `1.10` reads `1.1`.
+ */
+function trimFraction(value: string): string {
+ if (!value.includes(".")) return value;
+ return value.replace(/0+$/, "").replace(/\.$/, "");
+}
+
+/**
+ * Compact token count for dense UI.
+ *
+ * Published context windows sit on values a single rounded decimal cannot tell
+ * apart — 1,000,000, 1,048,576 and 1,050,000 all rendered as `1M`/`1.1M`, and
+ * reading 1,050,000 as `1.1M` overstated the window by 50k tokens. Two decimals
+ * at the `M` scale and one at the `K` scale keep neighbouring rows distinct
+ * while staying short: `1M`, `1.05M`, `1.1M`, `262.1K`.
+ *
+ * A count of `0` is a real value here, so callers that render an unpublished
+ * limit go through `formatTokenCount` instead.
+ */
+export function formatCompactTokenCount(tokens: number): string {
+ if (tokens < 1_000) return String(tokens);
+ const thousands = tokens / 1_000;
+ // Rounding can push a `K` mantissa up to 1000 (999,999 -> `1000K`), which
+ // reads as a scale error. Promote those to the `M` scale instead.
+ if (Number(thousands.toFixed(1)) < 1_000) {
+ return `${trimFraction(thousands.toFixed(1))}K`;
+ }
+ return `${trimFraction((tokens / 1_000_000).toFixed(2))}M`;
+}
+
+/**
+ * Compact token count for a model limit, e.g. `200K`, `1.05M`.
+ *
+ * An absent or non-positive limit means the service never published one, so it
+ * renders as an em dash rather than a number the user might trust.
+ */
export function formatTokenCount(tokens?: number): string {
if (!tokens || tokens <= 0) return "—";
- if (tokens >= 1_000_000) {
- const millions = tokens / 1_000_000;
- return `${Number.isInteger(millions) ? millions : millions.toFixed(1)}M`;
- }
- if (tokens >= 1_000) {
- const thousands = tokens / 1_000;
- return `${Number.isInteger(thousands) ? thousands : Math.round(thousands)}K`;
- }
- return String(tokens);
+ return formatCompactTokenCount(tokens);
}
/**