Public: anyone can read this; the crew can change it.
Talk's context meter uses the model's real window, not 200k #17841
Merged 4h 18m ago, live in production
scout/forge:scout/17826-talk-s-context-meter-uses-the-model-s-re → main 0 commits fork 3 threads · 3 unresolved
7 files
changed +192
−15
docs/features/talk.md +4
| @@ -354,3 +354,7 @@ The request is built fresh each time. It sends `User-Agent: forge-fetch/1` and n | ||
| 354 | 354 | Text a reader cannot see is left out: an element that is hidden, invisible, of no size, fully transparent, moved off the page, clipped to nothing, or the colour of its own background. Brackets the page writes are escaped, so a link reads only as its number and the address listed below. The forge's own host is matched by name whatever its case, trailing dot or escaped dot. `/a` and `/a/` are two pages. |
| 355 | 355 | |
| 356 | 356 | What the page says is someone else's text. It reaches the agent fenced, like an issue body, and once the agent has read it, a write you did not ask for waits for your confirm. |
| 357 | ||
| 358 | ## The context meter | |
| 359 | ||
| 360 | The meter says how full the model that answered really is: its window comes from the run, else from the table in `src/crew/model_windows.ts`. A model that table does not know shows its token count and no percentage. The page and the terminal use the same words (`contextText`). |
src/core/conversation_cost.ts +31 −11
| @@ -4,9 +4,8 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import type { Database } from "bun:sqlite"; |
| 7 | import { windowOf } from "../crew/model_windows.ts"; | |
| 7 | 8 | |
| 8 | /** The window assumed when a run did not report its model's. */ | |
| 9 | export const CONTEXT_TOKENS = 200_000; | |
| 10 | 9 | /** From this share of the context a new conversation is suggested. */ |
| 11 | 10 | export const FULL_AT = 0.8; |
| 12 | 11 | |
| @@ -73,28 +72,49 @@ export const totalText = (usd: number): string => `Spent ${dollars(usd)} in this | ||
| 73 | 72 | |
| 74 | 73 | export interface Context { |
| 75 | 74 | readonly tokens: number; |
| 76 | /** The model's window as its run reported it, else `CONTEXT_TOKENS`. */ | |
| 77 | readonly window: number; | |
| 78 | readonly share: number; | |
| 75 | /** | |
| 76 | * The model's window as its run reported it, else `crew/model_windows.ts`; absent when neither | |
| 77 | * knows it. | |
| 78 | */ | |
| 79 | readonly window?: number | undefined; | |
| 80 | /** Of the window, 0 to 1; absent with the window: an unknown model shows no percentage. */ | |
| 81 | readonly share?: number | undefined; | |
| 79 | 82 | } |
| 80 | 83 | |
| 84 | /** | |
| 85 | * The window the "full" rules assume when a model's is unknown: they never go blind, only the meter | |
| 86 | * does. | |
| 87 | */ | |
| 88 | const SAFE_WINDOW = 200_000; | |
| 89 | ||
| 90 | /** | |
| 91 | * How full the context is for the rules that start fresh or carry on: the real share, else tokens | |
| 92 | * against `SAFE_WINDOW`. | |
| 93 | */ | |
| 94 | export const fullness = (c: Context | undefined): number => (c === undefined ? 0 : c.share ?? Math.min(1, c.tokens / SAFE_WINDOW)); | |
| 95 | ||
| 81 | 96 | /** How full the context was at the end of the latest turn, or undefined before any usage. */ |
| 82 | 97 | export function contextOf(db: Database, conversationId: string): Context | undefined { |
| 83 | 98 | const row = db |
| 84 | .query<{ n: number; w: number }, [string]>( | |
| 85 | "SELECT context_tokens AS n, context_window AS w FROM conversation_run WHERE conversation_id = ?1 AND context_tokens > 0 ORDER BY started_at DESC, rowid DESC LIMIT 1", | |
| 99 | .query<{ n: number; w: number; m: string }, [string]>( | |
| 100 | "SELECT context_tokens AS n, context_window AS w, model AS m FROM conversation_run WHERE conversation_id = ?1 AND context_tokens > 0 ORDER BY started_at DESC, rowid DESC LIMIT 1", | |
| 86 | 101 | ) |
| 87 | 102 | .get(conversationId); |
| 88 | 103 | if (row === null) return undefined; |
| 89 | const window = row.w > 0 ? row.w : CONTEXT_TOKENS; | |
| 90 | return { tokens: row.n, window, share: Math.min(1, row.n / window) }; | |
| 104 | const window = row.w > 0 ? row.w : windowOf(row.m); | |
| 105 | return window === undefined ? { tokens: row.n } : { tokens: row.n, window, share: Math.min(1, row.n / window) }; | |
| 91 | 106 | } |
| 92 | 107 | |
| 93 | 108 | const thousands = (n: number): string => (n >= 1_000_000 ? `${+(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1000)}k`); |
| 94 | 109 | |
| 95 | /** "Context 85% full (170k of 200k tokens)", with the nudge from `FULL_AT`. */ | |
| 110 | /** | |
| 111 | * "Context 85% full (170k of 200k tokens)", with the nudge from `FULL_AT`; "Context 170k tokens" | |
| 112 | * when the window is unknown. | |
| 113 | */ | |
| 96 | 114 | export const contextText = (c: Context): string => |
| 97 | `Context ${Math.round(c.share * 100)}% full (${thousands(c.tokens)} of ${thousands(c.window)} tokens)${c.share >= FULL_AT ? ". A new conversation answers faster and costs less" : ""}`; | |
| 115 | c.share === undefined || c.window === undefined | |
| 116 | ? `Context ${thousands(c.tokens)} tokens` | |
| 117 | : `Context ${Math.round(c.share * 100)}% full (${thousands(c.tokens)} of ${thousands(c.window)} tokens)${c.share >= FULL_AT ? ". A new conversation answers faster and costs less" : ""}`; | |
| 98 | 118 | |
| 99 | 119 | /** Dollars as a quiet figure: cents below a dollar, a tenth of a cent below that. */ |
| 100 | 120 | export const dollars = (usd: number): string => (usd < 0.01 ? `$${usd.toFixed(3)}` : `$${usd.toFixed(2)}`); |
src/crew/conversation.ts +3 −3
| @@ -37,7 +37,7 @@ import { cancelHeld, readFenced, WORDS_MAX } from "../core/fence.ts"; | ||
| 37 | 37 | import { answeredNote, answerFor, FOLLOW_UP, type Outcome } from "./conversation_answered.ts"; |
| 38 | 38 | import { thinkingOf } from "../core/talk_work.ts"; |
| 39 | 39 | import { FRESH_LINE, freshDue, RECORD_HEAD, recordHistory, recordLines, type RecordTurn, TURN_CHARS } from "./fresh_start.ts"; |
| 40 | import { contextOf } from "../core/conversation_cost.ts"; | |
| 40 | import { contextOf, fullness } from "../core/conversation_cost.ts"; | |
| 41 | 41 | import { conversationPlan, noteAutoTurn, openSteps, planText, resetAutoTurns } from "../core/conversation_plan.ts"; |
| 42 | 42 | import { memoryBrief } from "../core/talk_memory.ts"; |
| 43 | 43 | import { getSubscription, PLATFORM, pickSubscription, type Pick } from "../core/subscriptions.ts"; |
| @@ -592,7 +592,7 @@ export const CONTEXT_FULL = 0.85; | ||
| 592 | 592 | /** Whether this conversation's next turn starts in a fresh session: full, or due (`freshDue`). */ |
| 593 | 593 | const startsFresh = (app: App, conversation: Conversation): boolean => { |
| 594 | 594 | if (conversation.claudeSessionId === "") return false; |
| 595 | const share = contextOf(app.db, conversation.id)?.share ?? 0; | |
| 595 | const share = fullness(contextOf(app.db, conversation.id)); | |
| 596 | 596 | return share >= CONTEXT_FULL || freshDue(app.db, conversation.id, conversation.claudeSessionId, share); |
| 597 | 597 | }; |
| 598 | 598 | |
| @@ -787,7 +787,7 @@ function carryOn(app: App, options: ConversationOptions, conversation: Conversat | ||
| 787 | 787 | if (current === undefined || current.archivedAt !== null || queues.has(conversation.id)) return; |
| 788 | 788 | // A turn that ended well carries on only when its context is full; a long thread alone starts |
| 789 | 789 | // nothing, it only makes the carried-on turn start fresh. |
| 790 | const full = (contextOf(app.db, conversation.id)?.share ?? 0) >= CONTEXT_FULL; | |
| 790 | const full = fullness(contextOf(app.db, conversation.id)) >= CONTEXT_FULL; | |
| 791 | 791 | if (ended.how !== "timeout" && ended.how !== "max_budget_reached" && !(ended.how === "ok" && full)) return; |
| 792 | 792 | const plan = conversationPlan(app.db, conversation.id); |
| 793 | 793 | if (plan === undefined || openSteps(plan).length === 0) return; |
src/crew/model_windows.ts added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | /** | |
| 2 | * How many tokens each model can hold (#17826): the one table Talk's context meter reads for the | |
| 3 | * model that answered. A model not listed has no window here, and the meter then shows no | |
| 4 | * percentage rather than a wrong one. A new model is one line. | |
| 5 | */ | |
| 6 | ||
| 7 | const WINDOWS: Readonly<Record<string, number>> = { | |
| 8 | // The ids and aliases `crew/models.ts` offers, and the 5.x ids the forge records. A run that | |
| 9 | // reports its own window outranks these (`contextOf`); these are Claude Code's standard 200k. | |
| 10 | "claude-fable-5-1": 200_000, | |
| 11 | "claude-fable-5-2": 200_000, | |
| 12 | "claude-opus-5-5": 200_000, | |
| 13 | "claude-sonnet-5-5": 200_000, | |
| 14 | "claude-haiku-5-5": 200_000, | |
| 15 | opus: 200_000, | |
| 16 | sonnet: 200_000, | |
| 17 | haiku: 200_000, | |
| 18 | "claude-opus-4-5": 200_000, | |
| 19 | "claude-sonnet-4-5": 200_000, | |
| 20 | "claude-haiku-4-5": 200_000, | |
| 21 | "claude-sonnet-4-5[1m]": 1_000_000, | |
| 22 | "gpt-4o": 128_000, | |
| 23 | "gpt-4o-mini": 128_000, | |
| 24 | "gpt-4.1": 1_000_000, | |
| 25 | "gpt-4.1-mini": 1_000_000, | |
| 26 | "gemini-2.5-pro": 1_000_000, | |
| 27 | "gemini-2.5-flash": 1_000_000, | |
| 28 | }; | |
| 29 | ||
| 30 | /** | |
| 31 | * The model's window in tokens, or undefined when the table does not know it. A `vendor/` prefix is | |
| 32 | * ignored. | |
| 33 | */ | |
| 34 | export function windowOf(model: string): number | undefined { | |
| 35 | const id = model.trim().toLowerCase(); | |
| 36 | const bare = id.slice(id.lastIndexOf("/") + 1); | |
| 37 | return Object.hasOwn(WINDOWS, bare) ? WINDOWS[bare] : undefined; | |
| 38 | } |
src/web/pages/talk.ts +1 −1
| @@ -530,7 +530,7 @@ function hereBar(ctx: Ctx, conversation: Conversation, context: Context | undefi | ||
| 530 | 530 | return html`<header class="talk-head"> |
| 531 | 531 | <a class="btn talk-back" data-variant="ghost" href="${urlOf(conversation)}?chats=1" title="All your chats, newest first">${icon("comment")}Chats</a> |
| 532 | 532 | <h2 class="talk-title">${nameOf(conversation)}${archived ? " (archived)" : ""}</h2> |
| 533 | ${tabs}${context !== undefined && context.share >= CONTEXT_SHOWN ? html`<span class="talk-fill small muted" title="${contextText(context)}">${meter(context.share * 100, contextText(context))} context used</span>` : null} | |
| 533 | ${tabs}${context?.share !== undefined && context.share >= CONTEXT_SHOWN ? html`<span class="talk-fill small muted" title="${contextText(context)}">${meter(context.share * 100, contextText(context))} context used</span>` : null} | |
| 534 | 534 | ${conversationMenu(ctx, conversation, context, display)} |
| 535 | 535 | <form method="post" action="${HERE}/new">${iconBtn("plus", "New conversation", { variant: "ghost" })}</form> |
| 536 | 536 | </header>`; |
test/model-windows.test.ts added +85
| @@ -0,0 +1,85 @@ | ||
| 1 | /** | |
| 2 | * The context meter reads the window of the model that answered (#17826): a 1M model at 200k tokens | |
| 3 | * is 20% full, and an unknown model shows no percentage. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { newConversation } from "../src/core/conversations.ts"; | |
| 11 | import { contextOf, contextText, fullness } from "../src/core/conversation_cost.ts"; | |
| 12 | import { createSession } from "../src/core/sessions.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { windowOf } from "../src/crew/model_windows.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | let dir: string; | |
| 21 | let app: App; | |
| 22 | let alice: User; | |
| 23 | let servers: Servers; | |
| 24 | ||
| 25 | beforeAll(async () => { | |
| 26 | dir = await mkdtemp(join(tmpdir(), "forge-windows-")); | |
| 27 | app = createApp({ dataDir: dir, port: 0 }); | |
| 28 | const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 29 | if (!u.ok) throw new Error("seed"); | |
| 30 | alice = u.value; | |
| 31 | servers = await serve(app); | |
| 32 | }); | |
| 33 | afterAll(async () => { | |
| 34 | await servers.stop(); | |
| 35 | await rm(dir, { recursive: true, force: true }); | |
| 36 | }); | |
| 37 | ||
| 38 | const answered = (model: string, tokens: number, reported = 0): string => { | |
| 39 | const c = newConversation(app.db, alice.id); | |
| 40 | app.db | |
| 41 | .query("INSERT INTO conversation_run (id, conversation_id, user_id, prompt, state, model, context_tokens, context_window, started_at, finished_at) VALUES (?1,?2,?3,'x','ok',?4,?5,?6,?7,?7)") | |
| 42 | .run(`r-${c.id}`, c.id, alice.id, model, tokens, reported, new Date().toISOString()); | |
| 43 | return c.id; | |
| 44 | }; | |
| 45 | ||
| 46 | describe("model windows", () => { | |
| 47 | test("the table knows a window, ignores a vendor prefix, and not an unknown id", () => { | |
| 48 | expect(windowOf("gpt-4.1")).toBe(1_000_000); | |
| 49 | expect(windowOf("openai/GPT-4.1")).toBe(1_000_000); | |
| 50 | expect(windowOf("some-new-model")).toBeUndefined(); | |
| 51 | expect(windowOf("toString")).toBeUndefined(); | |
| 52 | }); | |
| 53 | ||
| 54 | test("a 1M-window model at 200k tokens reads 20%", () => { | |
| 55 | const c = contextOf(app.db, answered("gpt-4.1", 200_000)); | |
| 56 | expect(c?.window).toBe(1_000_000); | |
| 57 | expect(c?.share).toBeCloseTo(0.2); | |
| 58 | expect(contextText(c!)).toContain("20% full (200k of 1M tokens)"); | |
| 59 | }); | |
| 60 | ||
| 61 | test("an unknown model reads no percentage", () => { | |
| 62 | const c = contextOf(app.db, answered("mystery-1", 200_000)); | |
| 63 | expect(c?.share).toBeUndefined(); | |
| 64 | expect(contextText(c!)).toBe("Context 200k tokens"); | |
| 65 | expect(contextText(c!)).not.toContain("%"); | |
| 66 | }); | |
| 67 | ||
| 68 | test("a window the run reported wins over the table", () => { | |
| 69 | expect(contextOf(app.db, answered("gpt-4.1", 100_000, 400_000))?.share).toBeCloseTo(0.25); | |
| 70 | }); | |
| 71 | ||
| 72 | test("the head meter shows for a known model above the threshold and not for an unknown one", async () => { | |
| 73 | const headers = { cookie: `forge_session=${createSession(app.db, alice.id).token}` }; | |
| 74 | const page = async (id: string) => (await fetch(`${servers.url}/talk/${id}`, { headers })).text(); | |
| 75 | expect(await page(answered("sonnet", 150_000))).toContain("context used"); | |
| 76 | expect(await page(answered("sonnet", 50_000))).not.toContain("context used"); | |
| 77 | expect(await page(answered("mystery-1", 150_000))).not.toContain("context used"); | |
| 78 | }); | |
| 79 | ||
| 80 | test("the full rules fall back on tokens when the window is unknown", () => { | |
| 81 | expect(fullness(contextOf(app.db, answered("mystery-1", 170_000)))).toBeCloseTo(0.85); | |
| 82 | expect(fullness(contextOf(app.db, answered("gpt-4.1", 170_000)))).toBeCloseTo(0.17); | |
| 83 | expect(fullness(undefined)).toBe(0); | |
| 84 | }); | |
| 85 | }); |
test/talk-fresh-say.test.ts +30
| @@ -69,6 +69,16 @@ const half = (c: string) => | ||
| 69 | 69 | ) |
| 70 | 70 | .run(`m-${c}`, c, alice.id); |
| 71 | 71 | |
| 72 | /** | |
| 73 | * The same measure from a run that reported no window: only the model's name says how big it is. | |
| 74 | */ | |
| 75 | const halfOf = (c: string, model: string) => | |
| 76 | app.db | |
| 77 | .query( | |
| 78 | "INSERT INTO conversation_run (id, conversation_id, user_id, subscription_id, prompt, resumes, session_id, started_at, finished_at, state, context_tokens, context_window, model) VALUES (?1, ?2, ?3, '', 'measured', 0, 'measured', '2999-01-01T00:00:00.000Z', '2999-01-01T00:00:00.000Z', 'ok', 100000, 0, ?4)", | |
| 79 | ) | |
| 80 | .run(`n-${c}`, c, alice.id, model); | |
| 81 | ||
| 72 | 82 | const conversation = (): string => { |
| 73 | 83 | const c = createConversation(app.db, alice.id); |
| 74 | 84 | if (!c.ok) throw new Error(c.error); |
| @@ -152,3 +162,23 @@ test("a long thread alone never starts a carried-on turn: one that ended well st | ||
| 152 | 162 | await sayAndSettle(bin, c, "second"); |
| 153 | 163 | expect(runs(c)).toHaveLength(2); |
| 154 | 164 | }); |
| 165 | ||
| 166 | test("a full thread on a model the table knows, reporting no window, starts fresh (#17826)", async () => { | |
| 167 | const bin = stub("known", "ok"); | |
| 168 | configureConversation(app, options(bin)); | |
| 169 | const c = conversation(); | |
| 170 | await sayAndSettle(bin, c, "first"); | |
| 171 | halfOf(c, "sonnet"); | |
| 172 | await sayAndSettle(bin, c, "second"); | |
| 173 | expect(runs(c)).toEqual(["resumed", "fresh"]); | |
| 174 | }); | |
| 175 | ||
| 176 | test("a full thread on an unknown model still starts fresh: the rules count tokens, not the meter (#17826)", async () => { | |
| 177 | const bin = stub("unknown", "ok"); | |
| 178 | configureConversation(app, options(bin)); | |
| 179 | const c = conversation(); | |
| 180 | await sayAndSettle(bin, c, "first"); | |
| 181 | halfOf(c, "mystery-1"); | |
| 182 | await sayAndSettle(bin, c, "second"); | |
| 183 | expect(runs(c)).toEqual(["resumed", "fresh"]); | |
| 184 | }); |
new above
offline
Split this ternary over lines. Note that callers in crew/conversation.ts use
share ?? 0, so an unknown model never counts as full: the fresh-session and carry-on rules stop working for it.