Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Take the shared prompt floor off the turn the client blames too (#9555)
Daniel Haneefcca293f5c
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 33c49cb54e3..132b590ec19 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -188,6 +188,9 @@ import {getImageInputUnavailableReason,} from "../utils/image-input-support";import {+ historyCannotHelp,+ latestTurnIsTheProblem,+ latestTurnOwnTokens,mergeContextTruncation,promptWasShortened,} from "../utils/context-truncation";@@ -7112,24 +7115,21 @@ export function createOpenAIStreamAdapter(// send the user to a new chat that fails identically.const budget =irreducible?.prompt_target ?? irreducible?.context_length ?? 0;- // `latest_turn_exact: false` means nothing could price the turn at all, so- // the count is the message's own JSON at four characters a token. Whitespace- // runs and escaped JSON tokenise several times denser than that, so printing- // it as "N tokens on its own" states a number the turn never cost. A turn the- // template renders as NOTHING on its own is not this case: the server prices- // that by difference against the prompt it measured and reports it exact.- // Absent means a server that predates the flag, which only ever sent a count.- const oneTurnIsTheProblem =- irreducible != null &&- (irreducible.latest_turn_tokens ?? 0) > budget &&- (irreducible.latest_turn_exact ?? true);+ // Both the gate and the number below take the shared prompt floor off the turn+ // first: `latest_turn_tokens` prices a whole rendered prompt, so on a+ // tool-enabled request it carries the entire tool catalogue, and quoting it+ // told the user a 6-token message was thousands of tokens "on its own".+ const oneTurnIsTheProblem = latestTurnIsTheProblem(+ irreducible,+ budget,+ );// Whose turn it is decides the advice: in a tool loop the offending turn is// often output the user never wrote and cannot edit, so "shorten this// message" names the wrong thing and offers no remedy.const userCanShortenIt =(irreducible?.latest_turn_role ?? "user") === "user";const tooLong =- `${irreducible?.latest_turn_tokens?.toLocaleString()} tokens on its own, ` ++ `${latestTurnOwnTokens(irreducible).toLocaleString()} tokens on its own, ` +`against the ${budget.toLocaleString()} tokens this ` +`${irreducible?.context_length?.toLocaleString()}-token window leaves for the prompt. ` +"The earlier turns were already removed and it still does not fit, so " +@@ -7143,12 +7143,23 @@ export function createOpenAIStreamAdapter(: `The last tool result is ${tooLong}` +'Raise "Context Length" in the chat Settings panel (⚙ in the top-right), ' +"or ask for less output from that tool."- : // llama-server runs with --no-context-shift, returning a hard- // error instead of silently dropping old KV-cache turns. Point- // the user at the control that raises the ceiling.- "The conversation has filled the model's context window. " +- 'Increase "Context Length" in the chat Settings panel (⚙ in the top-right), ' +- "or start a new chat.",+ : historyCannotHelp(irreducible)+ ? // No one turn to name, and the bulk is in the parts eviction never+ // touches, so "start a new chat" opens a chat that fails identically.+ // Both levers are named, neither claimed as the cause: the floor+ // bundles the template wrapper with the catalogue, so a large one does+ // not prove there are tools.+ "Even with every earlier turn dropped, this prompt would still be " ++ "too long, so shortening the conversation will not help. " ++ 'Raise "Context Length" in the chat Settings panel (⚙ in the top-right), ' ++ "or reduce what every request carries: the system prompt and any " ++ "tools that are enabled."+ : // llama-server runs with --no-context-shift, returning a hard+ // error instead of silently dropping old KV-cache turns. Point+ // the user at the control that raises the ceiling.+ "The conversation has filled the model's context window. " ++ 'Increase "Context Length" in the chat Settings panel (⚙ in the top-right), ' ++ "or start a new chat.",duration: 8000,});} else {diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex be1c199dbb4..c516298ad83 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -757,6 +757,11 @@ export interface OpenAIChatChunk {// template renders as nothing on its own is priced by difference and stays exact.// Only the counted one may be quoted as the turn's size.latest_turn_exact?: boolean;+ // The floor both counts above carry: what a rendered prompt costs with no messages in+ // it, which on a tool-enabled request is the whole tool catalogue. Subtract it before+ // comparing them, or the catalogue is blamed on the turn. Absent from an older server,+ // where zero reproduces the old behaviour.+ shared_prompt_tokens?: number;// Where the compaction boundary sits in the messages THIS request was sent with.// Absolute, unlike dropped_messages, so re-sending it after a turn that refit several// times cannot advance the boundary past the turns actually evicted.diff --git a/studio/frontend/src/features/chat/utils/context-truncation.ts b/studio/frontend/src/features/chat/utils/context-truncation.tsindex 9fa92a5f04a..2d215c63e7d 100644--- a/studio/frontend/src/features/chat/utils/context-truncation.ts+++ b/studio/frontend/src/features/chat/utils/context-truncation.ts@@ -44,6 +44,58 @@ export function compactionBoundary();}+function nonNegativeInt(value: number | undefined): number {+ // A propagated NaN would print "NaN tokens on its own" at the user.+ return Number.isFinite(value) ? Math.max(0, Math.trunc(value as number)) : 0;+}++export function latestTurnOwnTokens(+ truncation: ContextTruncation | null | undefined,+): number {+ // `latest_turn_tokens` prices a whole rendered PROMPT: template wrapper plus, on a+ // tool-enabled request, the entire tool catalogue. That sits inside `irreducible_tokens`+ // too and does not cancel (built-in catalogue alone is over a thousand tokens, MCP tools+ // uncapped), so a 6-token "hi" was reported as thousands "on its own".+ // `shared_prompt_tokens` is that floor, measured by the server on an empty prompt.+ const latest = nonNegativeInt(truncation?.latest_turn_tokens);+ // Never the whole turn: reporting it as zero tokens is a worse lie than the old one.+ const shared = Math.min(+ nonNegativeInt(truncation?.shared_prompt_tokens),+ Math.max(0, latest - 1),+ );+ return latest - shared;+}++export function latestTurnIsTheProblem(+ truncation: ContextTruncation | null | undefined,+ budget: number,+): boolean {+ if (!truncation) return false;+ // `latest_turn_exact: false` means nothing could price the turn, so the number is the+ // message's JSON at four characters a token while every other number here is a+ // tokenizer count of a rendered prompt: 16,400 characters of newlines estimate 8,207+ // against 557 rendered. A turn the template renders as nothing is NOT this case (the+ // server prices that by difference, exact). Absent means a server predating the flag.+ if (!(truncation.latest_turn_exact ?? true)) return false;+ // Measured WITHOUT the shared floor, so a turn only over budget once a tool catalogue+ // stands beside it is not blamed. An older server sends no floor, which reads as zero.+ return latestTurnOwnTokens(truncation) > budget;+}++export function historyCannotHelp(+ truncation: ContextTruncation | null | undefined,+): boolean {+ if (!truncation) return false;+ // `irreducible_tokens` prices what survives dropping every evictable group: template+ // wrapper, tool catalogue, system turns and the newest turn. At or over the WINDOW,+ // llama-server refuses on size alone however short the conversation gets, so "start a+ // new chat" opens a chat that fails identically. Below it, shortening really can work+ // (the fit refuses at `prompt_target` but passes the untrimmed messages on).+ const irreducible = nonNegativeInt(truncation.irreducible_tokens);+ const window = nonNegativeInt(truncation.context_length);+ return irreducible > 0 && window > 0 && irreducible >= window;+}+export function mergeContextTruncation(current: ContextTruncation | undefined,incoming: ContextTruncation,@@ -80,6 +132,9 @@ export function mergeContextTruncation(// Rides with the count it describes: alone it says nothing, and left behind it would// describe a number that is no longer there.delete merged.latest_turn_exact;+ // Likewise the floor: a stale one subtracted from a later fit's count moves the blame+ // rather than removing it.+ delete merged.shared_prompt_tokens;}return merged;}diff --git a/studio/frontend/tests/context-refusal-shared-floor.test.ts b/studio/frontend/tests/context-refusal-shared-floor.test.tsnew file mode 100644index 00000000000..c2a7277085b--- /dev/null+++ b/studio/frontend/tests/context-refusal-shared-floor.test.ts@@ -0,0 +1,285 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import {+ type ContextTruncation,+ historyCannotHelp,+ latestTurnIsTheProblem,+ latestTurnOwnTokens,+ mergeContextTruncation,+} from "../src/features/chat/utils/context-truncation.ts";++function refusal(extra: Partial<ContextTruncation>): ContextTruncation {+ return {+ dropped_messages: 0,+ fits: false,+ context_length: 4096,+ prompt_target: 3072,+ ...extra,+ };+}++// Emitted verbatim by `fit_rolling_context`, measured with the real llama.cpp tokenizer+// (b10360, gemma-4 vocab) through the bundled `gemma-4.jinja`: 4,096-token window, system+// prompt, six evictable turns, a 6,113-token MCP catalogue, and a last message of+// `{"role":"user","content":"hi"}` costing 6 rendered tokens.+const MCP_CATALOGUE_4096: ContextTruncation = {+ dropped_messages: 0,+ fits: false,+ prompt_tokens_before: 8237,+ prompt_tokens_after: 8237,+ irreducible_tokens: 6323,+ latest_turn_tokens: 6128,+ latest_turn_role: "user",+ shared_prompt_tokens: 6122,+ latest_turn_exact: true,+ context_length: 4096,+ prompt_target: 3072,+};++test("the tool catalogue is taken off the turn before the turn is blamed", () => {+ // Both counts price a whole rendered prompt and the catalogue does not cancel: 6,122 of+ // the turn's 6,128 tokens are tools the user did not send. Before the fix the toast read+ // "This message is 6,128 tokens on its own, against the 3,072 tokens this 4,096-token+ // window leaves for the prompt", about the word "hi".+ assert.equal(latestTurnOwnTokens(MCP_CATALOGUE_4096), 6);+ assert.equal(latestTurnIsTheProblem(MCP_CATALOGUE_4096, 3072), false);+});++test("the built-in catalogue alone is diagnosed the same way", () => {+ // Default install, measured the same way: 988 tokens of built-in tools, same six-token+ // "hi". Never crossed the budget even before the fix, but the toast printed 1,003.+ const builtin: ContextTruncation = {+ dropped_messages: 0,+ fits: false,+ prompt_tokens_before: 5512,+ prompt_tokens_after: 5512,+ irreducible_tokens: 3598,+ latest_turn_tokens: 1003,+ latest_turn_role: "user",+ shared_prompt_tokens: 997,+ latest_turn_exact: true,+ context_length: 4096,+ prompt_target: 3072,+ };+ assert.equal(latestTurnOwnTokens(builtin), 6);+ assert.equal(latestTurnIsTheProblem(builtin, 3072), false);+});++test("the catalogue does not cancel at any catalogue size", () => {+ // Measured at 7, 20, 200 and 2000 tools against the same thread: the floor tracks the+ // catalogue, the turn stays 6 tokens, and the raw ratio climbs from 0.279 to 0.991 while+ // the real one never moves. The verdict must not flip on how many tools are advertised.+ const measured: Array<[number, number, number]> = [+ // [catalogue floor, latest_turn_tokens, irreducible_tokens]+ [997, 1003, 3598],+ [2951, 2957, 5552],+ [29166, 29172, 31767],+ [290937, 290943, 293538],+ ];+ for (const [floor, latest, irreducible] of measured) {+ const turn = refusal({+ irreducible_tokens: irreducible,+ latest_turn_tokens: latest,+ shared_prompt_tokens: floor,+ latest_turn_role: "user",+ latest_turn_exact: true,+ });+ assert.equal(latestTurnOwnTokens(turn), 6, `floor ${floor}`);+ assert.equal(latestTurnIsTheProblem(turn, 3072), false, `floor ${floor}`);+ }+});++test("a turn that really is too big is still blamed once the floor is off", () => {+ // The fix must not silence the case the diagnosis exists for: 9,000 tokens of pasted+ // text beside the measured 997-token built-in floor, where halving it really would fit.+ const hugeTurn = refusal({+ irreducible_tokens: 10100,+ latest_turn_tokens: 9997,+ shared_prompt_tokens: 997,+ latest_turn_role: "user",+ latest_turn_exact: true,+ });+ assert.equal(latestTurnOwnTokens(hugeTurn), 9000);+ assert.equal(latestTurnIsTheProblem(hugeTurn, 3072), true);+});++test("a server that sends no floor behaves exactly as it did before the field", () => {+ // A newer client against a server predating `shared_prompt_tokens` must not subtract a+ // floor it was never told about, and must not change a number it prints.+ const oldServer = refusal({+ irreducible_tokens: 5050,+ latest_turn_tokens: 5000,+ latest_turn_role: "user",+ });+ assert.equal(latestTurnOwnTokens(oldServer), 5000);+ assert.equal(latestTurnIsTheProblem(oldServer, 3072), true);+ assert.equal(latestTurnIsTheProblem(oldServer, 8192), false);+});++test("a floor of zero is the same as no floor at all", () => {+ // The backend sends 0 for an estimated turn: that estimate prices the message's own+ // JSON and no catalogue, so it has no floor to remove.+ const estimated = refusal({+ irreducible_tokens: 5050,+ latest_turn_tokens: 5000,+ shared_prompt_tokens: 0,+ latest_turn_role: "tool",+ });+ assert.equal(latestTurnOwnTokens(estimated), 5000);+});++test("a floor can never eat the whole turn, however wrong it arrives", () => {+ // Reporting a turn as zero tokens is a worse lie than reporting the catalogue's size,+ // and a negative one prints a minus sign at the user.+ for (const bad of [5000, 5001, 999999]) {+ const turn = refusal({ latest_turn_tokens: 5000, shared_prompt_tokens: bad });+ assert.equal(latestTurnOwnTokens(turn), 1, `floor ${bad}`);+ }+ // `toLocaleString` renders NaN, Infinity and fractions straight at the user.+ for (const bad of [+ Number.NaN,+ Number.POSITIVE_INFINITY,+ Number.NEGATIVE_INFINITY,+ -1,+ 12.7,+ undefined,+ ]) {+ const own = latestTurnOwnTokens(+ refusal({ latest_turn_tokens: 5000, shared_prompt_tokens: bad }),+ );+ assert.ok(Number.isInteger(own), `floor ${String(bad)} produced ${own}`);+ assert.ok(own >= 1 && own <= 5000, `floor ${String(bad)} produced ${own}`);+ }+ // And a missing turn count stays zero rather than going negative through the clamp.+ assert.equal(latestTurnOwnTokens(refusal({ shared_prompt_tokens: 6000 })), 0);+ assert.equal(latestTurnOwnTokens(undefined), 0);+ assert.equal(latestTurnOwnTokens(null), 0);+});++test("no diagnosis at all blames nothing", () => {+ assert.equal(latestTurnIsTheProblem(null, 3072), false);+ assert.equal(latestTurnIsTheProblem(undefined, 3072), false);+});++test("the estimate flag still gates the claim, after the floor is off", () => {+ // The two guards are independent. `latest_turn_exact: false` is now only the last-resort+ // branch where nothing could price the turn (an unrenderable turn is priced by+ // difference and reported exact), and that estimate does not share units with+ // `irreducible_tokens`, so it must never be quoted as the turn's size however the+ // subtraction comes out. Measured on the bundled gemma-4 template: 16,400 characters of+ // newline and tab runs estimate 8,207 tokens against 557 rendered.+ const estimatedTurn = refusal({+ irreducible_tokens: 4449,+ latest_turn_tokens: 8207,+ shared_prompt_tokens: 0,+ latest_turn_role: "tool",+ latest_turn_exact: false,+ });+ assert.equal(latestTurnIsTheProblem(estimatedTurn, 3072), false);+ // Same payload, counted rather than guessed: now it is a claim we can make.+ assert.equal(+ latestTurnIsTheProblem({ ...estimatedTurn, latest_turn_exact: true }, 3072),+ true,+ );+});++test("the floor is dropped once a later fit succeeds", () => {+ // The tool loop refits per iteration, and a floor left behind from a failed fit would be+ // subtracted from a later fit's count, moving the blame instead of removing it.+ const failed = mergeContextTruncation(undefined, {+ dropped_messages: 0,+ fits: false,+ context_length: 4096,+ irreducible_tokens: 6100,+ latest_turn_tokens: 6020,+ shared_prompt_tokens: 6000,+ });+ assert.equal(failed.shared_prompt_tokens, 6000);++ const recovered = mergeContextTruncation(failed, {+ dropped_messages: 12,+ fits: true,+ context_length: 4096,+ });+ assert.ok(!("shared_prompt_tokens" in recovered));+ assert.ok(!("latest_turn_tokens" in recovered));+});++test("a prompt whose floor is already over the window is never sent to a new chat", () => {+ // The case has to land somewhere once the turn is no longer blamed: what survives+ // eviction is a measured 6,323 tokens against a 4,096 window, so a new chat renders the+ // same catalogue and fails identically.+ assert.equal(latestTurnIsTheProblem(MCP_CATALOGUE_4096, 3072), false);+ assert.equal(historyCannotHelp(MCP_CATALOGUE_4096), true);++ // Same counts under an 8,192-token window: the floor fits, so shortening is honest+ // advice again. The window picks the wording, not the ratio.+ assert.equal(+ historyCannotHelp({+ ...MCP_CATALOGUE_4096,+ context_length: 8192,+ prompt_target: 6144,+ }),+ false,+ );+ // Below the window shortening can work: the fit refuses at `prompt_target` but passes+ // the untrimmed messages on, and llama-server serves anything under the window.+ assert.equal(+ historyCannotHelp({ ...MCP_CATALOGUE_4096, irreducible_tokens: 4095 }),+ false,+ );+ // Exactly at it is refused too, so `>=` and not `>`.+ assert.equal(+ historyCannotHelp({ ...MCP_CATALOGUE_4096, irreducible_tokens: 4096 }),+ true,+ );+ // A payload missing either number cannot make the claim.+ assert.equal(+ historyCannotHelp({ dropped_messages: 0, fits: false, irreducible_tokens: 6323 }),+ false,+ );+ assert.equal(+ historyCannotHelp({ dropped_messages: 0, fits: false, context_length: 4096 }),+ false,+ );+ assert.equal(historyCannotHelp(null), false);+ assert.equal(historyCannotHelp(undefined), false);+});++test("the third toast branch names the levers that can actually work", () => {+ const source = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ // The band moved out of "this message is too long" must not fall through to "start a+ // new chat", the one action that provably cannot work here.+ assert.match(source, /historyCannotHelp\(irreducible\)/);+ assert.match(+ source,+ /Even with every earlier turn dropped, this prompt would still be/,+ );+ assert.match(+ source,+ /the system prompt and any \" \+\n\s*\"tools that are enabled\./,+ );+});++test("the toast quotes the turn's own size, never the count that carries the floor", () => {+ const source = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ // Printing `latest_turn_tokens` directly is the defect this guards against coming back.+ assert.match(+ source,+ /\$\{latestTurnOwnTokens\(irreducible\)\.toLocaleString\(\)\} tokens on its own/,+ );+ assert.doesNotMatch(+ source,+ /latest_turn_tokens\?\.toLocaleString\(\)\} tokens on its own/,+ );+});diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.tsindex ac65f8a5088..c1a4a1a354f 100644--- a/studio/frontend/tests/rolling-context-window.test.ts+++ b/studio/frontend/tests/rolling-context-window.test.ts@@ -377,7 +377,9 @@ test("the too-long advice depends on WHICH part does not fit", () => {// already been evicted and the single message is what overflows.assert.match(adapterSource, /contextTruncation\?\.fits === false/);assert.match(adapterSource, /shortening the conversation will not help/);- assert.match(adapterSource, /latest_turn_tokens/);+ // Matching the wire field name would pin nothing: after the floor fix its only+ // occurrence in that file is prose in a comment.+ assert.match(adapterSource, /latestTurnOwnTokens\(irreducible\)/);});test("a fits:false diagnosis is not a compaction", () => {@@ -417,5 +419,7 @@ test("the too-long check uses the prompt budget, not the raw window", () => {// message cannot fit a 4,096-token context. The raw window would blame the// conversation and send the user to a new chat that fails identically.assert.match(source, /irreducible\?\.prompt_target \?\? irreducible\?\.context_length/);- assert.match(source, /latest_turn_tokens \?\? 0\) > budget/);+ // Still measured against the budget, but through the helper that takes the prompt's+ // shared floor off the turn first.+ assert.match(source, /latestTurnIsTheProblem\(\s*irreducible,\s*budget,?\s*\)/);});