Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(llm): replace the context pie with a hairline on the composer edge
Elian Doran36c4f3a44b5f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 448c56e799..0dd22753b5 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2357,7 +2357,9 @@"tokens_used_with_model": "{{model}}: {{prompt}} prompt + {{completion}} completion = {{total}} tokens","tokens_used_with_model_and_cost": "{{model}}: {{prompt}} prompt + {{completion}} completion = {{total}} tokens (~${{cost}})","tokens": "tokens",- "context_used": "{{percentage}}% used",+ "context_usage_label": "Context window usage",+ "context_tooltip": "{{used}} of {{total}} tokens used ({{percentage}}%)",+ "context_nearly_full": "Context nearly full. Sending may fail, so start a new chat to continue.","note_context_enabled": "Click to disable note context: {{title}}","note_context_disabled": "Click to include current note in context","no_provider_message": "No AI provider configured. Add one to start chatting.",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.cssindex 6c0b188f2d..5403f86fc5 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css@@ -7,6 +7,19 @@* island's own inner padding.*/.llm-chat-input-form {+ /*+ * Trilium has no general-purpose warning/danger token — the only semantic error colours+ * in the themes are domain-specific (`--log-*`, `--sync-status-*`) — so these are local,+ * picked to read against both the light and dark card fills. Declared here rather than on+ * the indicator itself so the bar and the alert beside it both inherit them; a theme-level+ * token would override them here if one ever lands.+ */+ --llm-chat-context-neutral: var(--muted-text-color);+ --llm-chat-context-warning: #d98c1f;+ --llm-chat-context-critical: #d9534f;++ /* Positioning context for the context hairline, which rides the bottom edge. */+ position: relative;display: flex;flex-direction: column;gap: 0.375rem;@@ -308,25 +321,89 @@ body[dir=rtl] .llm-chat-input-form .llm-chat-model-select.select-button.dropdownopacity: 0.5;}-/* Context window indicator */-.llm-chat-context-indicator {+/*+ * Context window indicator.+ *+ * A hairline riding the island's bottom edge rather than an element in the control row:+ * it costs no width, and length is read far more accurately than the angle of the 14px+ * pie it replaces. It only exists once the window is at least half gone (see+ * chat_context_usage), so it is absent for most of most conversations.+ */+/*+ * Full-bleed, so the outer element is a clipper rather than the line itself: `inset: -1px`+ * resolves against the containing block's padding box, which expands it to exactly the+ * island's border box, and `border-radius: inherit` then matches the island's curve exactly.+ * Without that clip a 2px line running edge to edge would poke ~5px past each bottom corner,+ * since the curve is still 5px inboard at that height.+ */+.llm-chat-context-bar {+ position: absolute;+ inset: -1px;+ border-radius: inherit;+ overflow: hidden;+ /* The clipper covers the whole island, so it must not intercept presses meant for the+ editor. Only the strip at the bottom takes pointer events, for the tooltip. */+ pointer-events: none;display: flex;- align-items: center;- gap: 0.375rem;- margin-left: 0.25rem;+ align-items: flex-end;+}++.llm-chat-context-bar-track {+ position: relative;+ width: 100%;+ height: 2px;+ background: var(--main-border-color);+ pointer-events: auto;cursor: help;}-.llm-chat-context-pie {- width: 14px;- height: 14px;- border-radius: 50%;- flex-shrink: 0;+/* A hairline is far too small to hover, and the tooltip is where the token counts live, so+ the hit area is extended upward without drawing anything. Kept inside the island's 8px+ bottom padding so it can't sit over the controls. */+.llm-chat-context-bar-track::before {+ content: "";+ position: absolute;+ inset-inline: 0;+ bottom: 0;+ height: 8px;}-.llm-chat-context-text {- font-size: 0.75rem;- color: var(--muted-text-color);+.llm-chat-context-bar-fill {+ height: 100%;+ border-radius: 1px;+ background: var(--llm-chat-context-neutral);+ transition: width 150ms linear, background-color 150ms linear;+}++.llm-chat-context-bar-warning .llm-chat-context-bar-fill {+ background: var(--llm-chat-context-warning);+}++.llm-chat-context-bar-critical .llm-chat-context-bar-fill {+ background: var(--llm-chat-context-critical);+}++@media (prefers-reduced-motion: reduce) {+ .llm-chat-context-bar-fill {+ transition: none;+ }+}++/* At the critical threshold the bar is no longer enough — the consequence gets said. */+.llm-chat-context-alert {+ display: flex;+ align-items: center;+ gap: 0.35rem;+ margin: 0;+ padding: 0 0.375rem;+ color: var(--main-text-color);+ font-size: 0.8rem;+}++.llm-chat-context-alert .bx {+ color: var(--llm-chat-context-critical);+ font-size: 1rem;+ flex-shrink: 0;}/*diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 8bac8cb5ee..c0ed7c50b0 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -15,6 +15,7 @@ import Dropdown from "../../react/Dropdown.js";import { FormDropdownDivider, FormListHeader, FormListItem, FormListToggleableItem } from "../../react/FormList.js";import { useLegacyImperativeHandlers } from "../../react/hooks.js";import AddProviderModal, { type LlmProviderConfig, type ProviderStep } from "../options/llm/AddProviderModal.js";+import { computeContextUsage } from "./chat_context_usage.js";import { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdentListItemAtStart } from "./chat_input_editing.js";import { editorHtmlToMarkdown } from "./chat_input_markdown.js";import { SafeImage } from "./retry_image.js";@@ -210,14 +211,23 @@ export default function ChatInputBar({// web search server-side; reflect that here by disabling the toggle so the// user understands the trade-off instead of seeing it mysteriously ignored.const webSearchUnavailable = currentModel?.provider === "google" && chat.enableNoteTools;- const contextWindow = currentModel?.contextWindow || 200000;- const percentage = Math.min((chat.lastPromptTokens / contextWindow) * 100, 100);- const isWarning = percentage > 75;- const isCritical = percentage > 90;- // `--main-selection-color` is not defined by any Trilium theme, so the nominal- // colour here was always the hardcoded fallback; `--link-color` is the real- // theme-aware accent.- const pieColor = isCritical ? "var(--danger-color, #d9534f)" : isWarning ? "var(--warning-color, #f0ad4e)" : "var(--link-color, #007bff)";+ // Null until the window is close enough to matter, and null (rather than a guess) when+ // the model advertises no window at all. See chat_context_usage.+ const contextUsage = computeContextUsage({+ promptTokens: chat.lastPromptTokens,+ completionTokens: chat.lastCompletionTokens,+ draftTokens: chat.draftTokens,+ contextWindow: currentModel?.contextWindow+ });+ // The bar itself carries no text, so the numbers live in its tooltip (and, for assistive+ // tech, in `aria-valuetext`).+ const contextTooltip = contextUsage+ ? t("llm_chat.context_tooltip", {+ used: formatTokenCount(contextUsage.usedTokens),+ total: formatTokenCount(contextUsage.contextWindow),+ percentage: Math.round(contextUsage.percentage)+ })+ : undefined;// Show setup prompt if no provider is configuredif (!chat.isCheckingProvider && !chat.hasProvider) {@@ -363,6 +373,17 @@ export default function ChatInputBar({onChange={attachments.handleFilePickerChange}style={{ display: "none" }}/>+ {/* At the point the window is nearly gone, say so in words — a 2px bar is not+ enough warning for a hard failure. Nothing in the send path trims the+ conversation (BaseProvider.chat sends every message; `contextWindow` is+ metadata the server never reads), so overflow is not graceful degradation:+ the provider rejects the request and the error lands in the transcript. */}+ {contextUsage?.level === "critical" && (+ <p className="llm-chat-context-alert">+ <span className="bx bx-error-circle" />+ {t("llm_chat.context_nearly_full")}+ </p>+ )}<div className="llm-chat-options"><div className="llm-chat-model-selector"><Dropdown@@ -446,20 +467,6 @@ export default function ChatInputBar({: t("llm_chat.note_context_disabled")}/>)}- {chat.lastPromptTokens > 0 && (- <div- className="llm-chat-context-indicator"- title={`${formatTokenCount(chat.lastPromptTokens)} / ${formatTokenCount(contextWindow)} ${t("llm_chat.tokens")}`}- >- <div- className="llm-chat-context-pie"- style={{- background: `conic-gradient(${pieColor} ${percentage}%, var(--accented-background-color) ${percentage}%)`- }}- />- <span className="llm-chat-context-text">{t("llm_chat.context_used", { percentage: percentage.toFixed(0) })}</span>- </div>- )}</div><ActionButtonicon="bx bx-paperclip"@@ -478,6 +485,29 @@ export default function ChatInputBar({className={`llm-chat-send-btn ${chat.isStreaming ? "llm-chat-stop-btn" : ""}`}/></div>+ {/* The hairline rides the island's bottom edge, edge to edge, rather than taking+ a slot in the control row. The outer element only clips to the island's corners+ and takes no pointer events; the track carries the tooltip and the ARIA, so+ assistive tech gets the same reading the length gives visually. */}+ {contextUsage && (+ <div className={`llm-chat-context-bar llm-chat-context-bar-${contextUsage.level}`}>+ <div+ className="llm-chat-context-bar-track"+ role="progressbar"+ aria-label={t("llm_chat.context_usage_label")}+ aria-valuenow={Math.round(contextUsage.percentage)}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuetext={contextTooltip}+ title={contextTooltip}+ >+ <div+ className="llm-chat-context-bar-fill"+ style={{ width: `${contextUsage.percentage}%` }}+ />+ </div>+ </div>+ )}</form><AddProviderModalkey={openToken}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_context_usage.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_usage.spec.tsnew file mode 100644index 0000000000..9ddd77c4c3--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_usage.spec.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from "vitest";++import { computeContextUsage, estimateTokens, quantizeDraftTokens } from "./chat_context_usage.js";++describe("chat context usage", () => {+ describe("computeContextUsage", () => {+ it("stays hidden below the visible threshold, and appears once crossed", () => {+ const below = computeContextUsage({ promptTokens: 4_000, completionTokens: 0, draftTokens: 0, contextWindow: 10_000 });+ expect(below).toBeNull();++ const above = computeContextUsage({ promptTokens: 5_500, completionTokens: 0, draftTokens: 0, contextWindow: 10_000 });+ expect(above).toMatchObject({ level: "neutral", percentage: 55, usedTokens: 5_500, contextWindow: 10_000 });+ });++ it("reports nothing when the model advertises no context window, rather than guessing one", () => {+ const shared = { promptTokens: 190_000, completionTokens: 0, draftTokens: 0 };+ expect(computeContextUsage({ ...shared, contextWindow: undefined })).toBeNull();+ expect(computeContextUsage({ ...shared, contextWindow: 0 })).toBeNull();+ expect(computeContextUsage({ ...shared, contextWindow: -1 })).toBeNull();+ });++ it("counts the last reply and the unsent draft, not just the last prompt", () => {+ // 4k prompt alone is 40% and would stay hidden; the reply and draft are what+ // actually push the *next* request over the line.+ expect(computeContextUsage({ promptTokens: 4_000, completionTokens: 0, draftTokens: 0, contextWindow: 10_000 })).toBeNull();++ const usage = computeContextUsage({ promptTokens: 4_000, completionTokens: 1_500, draftTokens: 500, contextWindow: 10_000 });+ expect(usage).toMatchObject({ level: "neutral", percentage: 60, usedTokens: 6_000 });+ });++ it("escalates through neutral, warning and critical at the thresholds", () => {+ const at = (tokens: number) => computeContextUsage({ promptTokens: tokens, completionTokens: 0, draftTokens: 0, contextWindow: 1_000 })?.level;+ expect(at(740)).toBe("neutral");+ expect(at(750)).toBe("warning");+ expect(at(899)).toBe("warning");+ expect(at(900)).toBe("critical");+ });++ it("clamps an overflowing conversation to 100% instead of reporting past full", () => {+ const usage = computeContextUsage({ promptTokens: 5_000, completionTokens: 0, draftTokens: 0, contextWindow: 2_000 });+ expect(usage).toMatchObject({ level: "critical", percentage: 100, usedTokens: 5_000 });+ });++ it("ignores negative token counts rather than letting them subtract", () => {+ const usage = computeContextUsage({ promptTokens: 900, completionTokens: -500, draftTokens: -100, contextWindow: 1_000 });+ expect(usage).toMatchObject({ level: "critical", usedTokens: 900 });+ });+ });++ describe("estimateTokens", () => {+ it("approximates four characters per token and rounds up, so any text costs at least one", () => {+ expect(estimateTokens("")).toBe(0);+ expect(estimateTokens("a")).toBe(1);+ expect(estimateTokens("abcd")).toBe(1);+ expect(estimateTokens("abcde")).toBe(2);+ expect(estimateTokens("x".repeat(400))).toBe(100);+ });+ });++ describe("quantizeDraftTokens", () => {+ it("snaps to a coarse step, so nearby values collapse to the same state", () => {+ expect(quantizeDraftTokens(0)).toBe(0);+ expect(quantizeDraftTokens(12)).toBe(0);+ expect(quantizeDraftTokens(13)).toBe(25);+ expect(quantizeDraftTokens(30)).toBe(25);+ expect(quantizeDraftTokens(38)).toBe(50);+ // A keystroke inside a step must not produce a new value (which would re-render).+ expect(quantizeDraftTokens(101)).toBe(quantizeDraftTokens(105));+ });+ });+});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_context_usage.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_usage.tsnew file mode 100644index 0000000000..d52353bb34--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_usage.ts@@ -0,0 +1,107 @@+/**+ * How full the model's context window is, and whether that is worth showing yet.+ *+ * The figure providers report (`promptTokens`) is the size of the *whole* request —+ * system prompt, every prior turn, note context, tool definitions, and only then the+ * newest message — so it climbs monotonically through a conversation and is flat and+ * uninteresting for most of one. The composer therefore shows nothing at all until it+ * approaches the point where it can affect the next reply, rather than displaying a+ * single-digit percentage for the entire life of a chat.+ */++/** Below this, the window is not close enough to matter and nothing is rendered. */+export const CONTEXT_VISIBLE_THRESHOLD = 50;+/** Above this, the indicator changes colour. */+export const CONTEXT_WARNING_THRESHOLD = 75;+/**+ * Above this, the composer says so in words instead of leaving it to a 2px bar. Overflow is a+ * hard failure rather than graceful degradation: nothing in the send path trims the+ * conversation, so the provider simply rejects the request.+ */+export const CONTEXT_CRITICAL_THRESHOLD = 90;++export type ContextUsageLevel = "neutral" | "warning" | "critical";++export interface ContextUsage {+ level: ContextUsageLevel;+ /** Share of the context window in use, 0-100, clamped at 100. */+ percentage: number;+ /** Estimated tokens the next request will carry. */+ usedTokens: number;+ contextWindow: number;+}++export interface ContextUsageInput {+ /** Prompt tokens the provider reported for the last completed request. */+ promptTokens: number;+ /** Completion tokens for that request — part of the next prompt, so they count too. */+ completionTokens: number;+ /** Estimated tokens for the unsent draft (see {@link estimateTokens}). */+ draftTokens: number;+ /** The model's advertised window. Optional: plenty of providers don't report one. */+ contextWindow?: number;+}++/**+ * Decide what, if anything, the context indicator should show.+ *+ * Returns `null` both when there is nothing worth saying and when there is no honest way+ * to say it: without a `contextWindow` there is no denominator, and inventing one (the+ * previous behaviour assumed 200k) produces a confident percentage derived from a guess.+ * Local and OpenAI-compatible providers frequently omit it, so this is a common case,+ * not an edge one.+ */+export function computeContextUsage({ promptTokens, completionTokens, draftTokens, contextWindow }: ContextUsageInput): ContextUsage | null {+ if (!contextWindow || contextWindow <= 0) {+ return null;+ }++ // What the *next* request will carry: the last prompt already covers the conversation+ // up to and including the last user message, so only the reply that followed it and+ // the current draft are still unaccounted for. Reporting `promptTokens` alone — as the+ // old indicator did — is retrospective, and understates by a whole reply.+ const usedTokens = Math.max(0, promptTokens) + Math.max(0, completionTokens) + Math.max(0, draftTokens);+ // Thresholds read the raw ratio; only the reported figure is rounded. Rounding first+ // would let a value sitting just under a threshold be nudged across it.+ const rawPercentage = Math.min((usedTokens / contextWindow) * 100, 100);++ if (rawPercentage < CONTEXT_VISIBLE_THRESHOLD) {+ return null;+ }++ const level: ContextUsageLevel = rawPercentage >= CONTEXT_CRITICAL_THRESHOLD+ ? "critical"+ : rawPercentage >= CONTEXT_WARNING_THRESHOLD+ ? "warning"+ : "neutral";++ // One decimal: enough to move a bar smoothly, and free of the float noise that makes+ // an exact 55% arrive as 55.00000000000001.+ const percentage = Math.round(rawPercentage * 10) / 10;++ return { level, percentage, usedTokens, contextWindow };+}++/**+ * Rough token count for text that hasn't been sent yet, at the usual ~4-characters-per-token+ * approximation. Deliberately crude: the real count depends on the model's tokenizer, and the+ * result drives a 2px bar and a threshold, not a billing figure.+ */+export function estimateTokens(text: string): number {+ return Math.ceil(text.length / 4);+}++/**+ * Round a draft estimate to a coarse step.+ *+ * The draft lives in a ref precisely so typing doesn't re-render the chat tree, but the+ * indicator has to move as you type or the bar can go from hidden to critical inside a single+ * send. Quantizing means the state only actually changes about once per {@link DRAFT_TOKEN_STEP}+ * tokens typed — same-value `setState` calls bail out — which is far finer than a 2px bar can+ * show while costing a re-render roughly every hundred characters instead of every keystroke.+ */+export function quantizeDraftTokens(tokens: number): number {+ return Math.round(tokens / DRAFT_TOKEN_STEP) * DRAFT_TOKEN_STEP;+}++const DRAFT_TOKEN_STEP = 25;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex 7670fd78bc..fddaf8e6fe 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -7,6 +7,7 @@ import { formatModelCost } from "../../../services/llm_model_cost.js";import options from "../../../services/options.js";import { randomString } from "../../../services/utils.js";import { useTriliumEvent } from "../../react/hooks.js";+import { estimateTokens, quantizeDraftTokens } from "./chat_context_usage.js";import { stripQuoteSources } from "./chat_quote.js";import { conversationForRegenerate } from "./chat_regenerate.js";import { type ContentBlock, type FileBlock, type ImageBlock, type LlmChatContent, type StoredMessage, type TextFileBlock, trimToFirstUserMessage } from "./llm_chat_types.js";@@ -150,6 +151,10 @@ export interface UseLlmChatReturn {/** The chat note's ID — used as the upload target for attachments. */chatNoteId: string | undefined;lastPromptTokens: number;+ /** Completion tokens of the last reply — part of the next prompt, so the context indicator counts them. */+ lastCompletionTokens: number;+ /** Coarse estimate of the unsent draft, quantized so typing rarely re-renders. */+ draftTokens: number;messagesEndRef: RefObject<HTMLDivElement>;scrollContainerRef: RefObject<HTMLDivElement>;/** Trailing spacer below the last message; sized so the active turn can park near the top. */@@ -216,7 +221,13 @@ export function useLlmChat(const setInput = useCallback((value: string) => {inputRef.current = value;setHasInputText(value.trim().length > 0);+ // The context indicator has to account for the draft, or it can go from hidden+ // straight to critical inside one send. Quantized so this only actually changes+ // state about once per hundred characters typed, keeping the ref's whole point —+ // that typing doesn't re-render the chat tree — very nearly intact.+ setDraftTokens(quantizeDraftTokens(estimateTokens(value)));}, []);+ const [draftTokens, setDraftTokens] = useState(0);const getInput = useCallback(() => inputRef.current, []);const [isStreaming, setIsStreaming] = useState(false);// The canonical "target" content received from the stream so far. The@@ -238,6 +249,9 @@ export function useLlmChat(const [contextNoteId, setContextNoteId] = useState<string | undefined>(initialContextNoteId);const [chatNoteId, setChatNoteIdState] = useState<string | undefined>(initialChatNoteId);const [lastPromptTokens, setLastPromptTokens] = useState<number>(0);+ // The reply to the last prompt is part of the *next* prompt, so the context indicator+ // has to count it too — `lastPromptTokens` alone understates by a whole reply.+ const [lastCompletionTokens, setLastCompletionTokens] = useState<number>(0);const [hasProvider, setHasProvider] = useState<boolean>(true); // Assume true initiallyconst [isCheckingProvider, setIsCheckingProvider] = useState<boolean>(true);const [showScrollToBottom, setShowScrollToBottom] = useState(false);@@ -533,6 +547,7 @@ export function useLlmChat(// Restore last prompt tokens from the most recent message with usageconst lastUsage = [...(content.messages || [])].reverse().find(m => m.usage)?.usage;setLastPromptTokens(lastUsage?.promptTokens ?? 0);+ setLastCompletionTokens(lastUsage?.completionTokens ?? 0);}, [supportsExtendedThinking, selectModel]);// Get current state as content object (uses refs to avoid stale closures)@@ -555,6 +570,7 @@ export function useLlmChat(const clearMessages = useCallback(() => {setMessages([]);setLastPromptTokens(0);+ setLastCompletionTokens(0);}, [setMessages]);/**@@ -780,6 +796,7 @@ export function useLlmChat(onUsage: (u) => {usage = u;setLastPromptTokens(u.promptTokens);+ setLastCompletionTokens(u.completionTokens);},onError: (errorMsg) => {console.error("Chat error:", errorMsg);@@ -941,6 +958,8 @@ export function useLlmChat(contextNoteId,chatNoteId,lastPromptTokens,+ lastCompletionTokens,+ draftTokens,messagesEndRef,scrollContainerRef,bottomSpacerRef,