Skip to content

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.

Studio: stop blaming Max Tokens when a connected model fills its context window (#12567)

oobabooga6d3e91dfe84c
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 5d685d84ec5..ace0f84ae1e 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -120,6 +120,11 @@ import {
} from "../utils/pre-stream-run-reservation";
import { readThreadCreationClaim } from "../utils/chat-thread-creation-claim";
import { ggufCompactionRequestFields } from "../utils/auto-compaction";
+import {
+ lengthIncompleteReason,
+ lengthStopCause,
+ windowEvidenceCount,
+} from "./generation-length";
import {
studioToolHistoryRequestFields,
type ToolHistoryMessage,
@@ -200,6 +205,7 @@ import { syncModelCapabilities } from "../hooks/use-chat-model-runtime";
import {
clampReasoningEffortToLevels,
externalMaxOutputTokensNeedsConnectionCap,
+ externalStopWindow,
getExternalMaxOutputTokens,
getPublishedExternalMaxOutputTokens,
getGroundedExternalMaxOutputTokens,
@@ -321,6 +327,7 @@ import {
createContinuationMerger,
hasRenderableContent,
incompleteLabel,
+ incompleteReasonAfterError,
type IncompleteReason,
noteRunStartedThisSession,
readIncompleteInfo,
@@ -5619,6 +5626,8 @@ export function createOpenAIStreamAdapter(
let incompleteReason: IncompleteReason | null = null;
// MLX reports finish_reason "stop" even at the cap, so an exhausted budget is its only truncation signal.
let requestedMaxTokens: number | undefined;
+ // Served window: null if unknown, Infinity if only the output cap can bind.
+ let servedContextLength: number | null = null;
const isMlxRequest = !isExternalRequest && activeModel?.isMlx === true;
const reasoningDurationTracker = createReasoningDurationTracker();
if (resumedThought) {
@@ -6110,6 +6119,8 @@ export function createOpenAIStreamAdapter(
usage?: ServerUsage;
timings?: ServerTimings;
} | null = null;
+ // llama.cpp output count, including reasoning.
+ let windowCount: number | null = null;
// Colab-style proxies can swallow fetch aborts, so also POST /inference/cancel explicitly.
const onAbortCancel = () => {
@@ -6717,6 +6728,16 @@ export function createOpenAIStreamAdapter(
}
clearSelectedImageEditReference();
requestedMaxTokens = requestPayload.max_tokens;
+ // Ignore local settings for external requests; otherwise use loaded values.
+ // Match RAG's fallback order, treating maxSeqLength 0 as unknown.
+ servedContextLength = isExternalRequest
+ ? externalStopWindow(
+ externalProvider?.providerType,
+ externalProvider?.baseUrl,
+ )
+ : (runtime.loadedCustomContextLength ??
+ runtime.loadedContextLength ??
+ (params.maxSeqLength || null));
await ThreadAutosaveHandle.awaitFirstSave(resolvedThreadId);
if (generationDecision === "pending") {
// Keyed on `enabled_tools`, never on `requestPayload.tools`: see durable-gate.ts. Keying this on
@@ -6851,27 +6872,7 @@ export function createOpenAIStreamAdapter(
: streamChatCompletions(
requestPayload,
runSignal,
- // Only when the request targets the LOCAL model. loadedContextLength
- // stays populated for a resident GGUF even while an external model is
- // selected, so an external request with a 16K cap was being measured
- // against an unrelated 4096-token local window and reported as having
- // unlimited Max Tokens and no context left.
- // `maxSeqLength` last, and coerced from 0: a local safetensors or
- // MLX request on this path has neither GGUF field set, and reading
- // that as "no window" makes every context-length stop look like a
- // user-set Max Tokens one -- advice to raise a value already at the
- // model's maximum. Same order the RAG `context_length` above uses.
- // `loadedCustomContextLength`, not `customContextLength`: the
- // latter is the EDITABLE field, and the store's own definition of a
- // pending edit is the two differing. A model still serving at 4096
- // while the field reads 8192 would make its 4096 stop look
- // user-imposed, and the toast would advise raising Max Tokens
- // instead of reloading at the larger context.
- isExternalRequest
- ? null
- : (runtime.loadedCustomContextLength ??
- runtime.loadedContextLength ??
- (params.maxSeqLength || null)),
+ servedContextLength,
);
// Per run, not per module: two turns must not share a cycle.
const canPublish = createStreamPublishGate();
@@ -7402,13 +7403,16 @@ export function createOpenAIStreamAdapter(
continue;
}
+ const chunkTimings = (chunk as Record<string, unknown>).timings as
+ | ServerTimings
+ | undefined;
+ // Timings can arrive without usage.
+ windowCount = windowEvidenceCount(chunkTimings) ?? windowCount;
// OpenAI usage may arrive in an empty trailing chunk or on the terminal Codex chunk.
if (chunk.usage) {
serverMetadata = {
usage: chunk.usage,
- timings: (chunk as Record<string, unknown>).timings as
- | ServerTimings
- | undefined,
+ timings: chunkTimings,
};
if (chunk.choices?.length === 0) continue;
}
@@ -8182,6 +8186,16 @@ export function createOpenAIStreamAdapter(
) {
incompleteReason = "length";
}
+ if (incompleteReason === "length") {
+ incompleteReason = lengthIncompleteReason(
+ lengthStopCause({
+ cap: requestedMaxTokens ?? null,
+ contextLength: servedContextLength,
+ promptTokens: meta?.usage?.prompt_tokens ?? null,
+ completionTokens: windowCount,
+ }),
+ );
+ }
// Before the lookup below: its network time is not generation time.
const finishedAt = Date.now();
@@ -8483,15 +8497,16 @@ export function createOpenAIStreamAdapter(
// said why the model stopped.
incomplete: {
reason: resolveIncompleteReason(
- // An explicit Stop latched incompleteReason = "cancelled" at the abort
- // handler; that outranks the error-derived guess below.
- incompleteReason ??
- (err instanceof GenerationLengthError
- ? ("length" as const)
- : err instanceof ChatGenerationTerminalError &&
- err.generationStatus === "cancelled"
- ? ("cancelled" as const)
- : ("interrupted" as const)),
+ // Preserve cancellation while refining length stops.
+ incompleteReasonAfterError(
+ incompleteReason,
+ err instanceof GenerationLengthError
+ ? lengthIncompleteReason(err.stopCause)
+ : err instanceof ChatGenerationTerminalError &&
+ err.generationStatus === "cancelled"
+ ? "cancelled"
+ : "interrupted",
+ ),
contextWindowExceeded,
),
},
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 725df91a01d..0b97eff95a1 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -52,7 +52,11 @@ import {
runBoundedVariantsRequest,
} from "./gguf-variants-request";
import { assertCompletedPaddedBody } from "./padded-response";
-import { maxTokensIsTheLimit } from "./generation-length.ts";
+import {
+ type LengthStopCause,
+ lengthStopCause,
+ windowEvidenceCount,
+} from "./generation-length.ts";
export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
// Bumped alongside that event so other tabs, which never receive it, can drop caches they built
@@ -108,24 +112,35 @@ export class StreamInterruptedError extends Error {
}
}
+const LENGTH_STOP_ADVICE: Record<LengthStopCause, string> = {
+ max_tokens:
+ "The model reached the Max Tokens limit before producing a final answer. " +
+ "Increase Max Tokens or disable thinking, then retry.",
+ // The context window can bind even when Max Tokens is finite.
+ context_length:
+ "The model ran out of room to answer: thinking used what the context window " +
+ "had left after the prompt, before any answer was written. Raising Max " +
+ "Tokens cannot create room the window does not have -- increase the " +
+ "Context Length in Model settings, or disable thinking, then retry.",
+ // No Studio setting controls a connected model's window.
+ context_window:
+ "The conversation filled the model's context window before an answer was " +
+ "written. Start a new chat, or shorten this one, then retry.",
+ // Unknown cause: offer both remedies.
+ unknown:
+ "The model hit Max Tokens or its context window before answering. Increase " +
+ "Max Tokens, disable thinking, or start a new chat.",
+};
+
/** Thrown when a reasoning model consumes its output budget before emitting any standard content,
* so the chat UI can explain a completed stream holding only a thinking panel. */
export class GenerationLengthError extends Error {
- /** @param maxTokensWasSet whether the user actually configured a Max Tokens value. With Max Tokens on "Max"
- * the backend already requests the whole context length, so generation stops at the context wall and
- * "Increase Max Tokens" cannot be followed. The false branch also covers a finite cap the prompt left no room
- * for, hence the wording about raising the cap. */
- constructor(maxTokensWasSet = true) {
- super(
- maxTokensWasSet
- ? "The model reached the Max Tokens limit before producing a final answer. " +
- "Increase Max Tokens or disable thinking, then retry."
- : "The model ran out of room to answer: thinking used what the context window " +
- "had left after the prompt, before any answer was written. Raising Max " +
- "Tokens cannot create room the window does not have -- increase the " +
- "Context Length in Model settings, or disable thinking, then retry.",
- );
+ readonly stopCause: LengthStopCause;
+
+ constructor(stopCause: LengthStopCause) {
+ super(LENGTH_STOP_ADVICE[stopCause]);
this.name = "GenerationLengthError";
+ this.stopCause = stopCause;
}
}
@@ -1643,8 +1658,7 @@ function classifyStructuredDeltaContent(content: unknown): {
export async function* streamChatCompletions(
payload: OpenAIChatCompletionsRequest,
signal: AbortSignal,
- /** The window this request is served by, when the caller knows it. Used only to tell a user-chosen
- * Max Tokens apart from the backend's stand-in for "Max", which is the whole context length. */
+ /** Served context window for length-stop attribution; null or omitted when unknown. */
loadedContextLength?: number | null,
): AsyncGenerator<OpenAIChatChunk> {
const response = await authFetch("/v1/chat/completions", {
@@ -1680,6 +1694,9 @@ export async function* streamChatCompletions(
// Reported by the server on the final chunk. Needed to tell the two walls apart: a finite Max
// Tokens below the context length does not mean Max Tokens stopped the generation.
let promptTokens: number | null = null;
+ let windowCount: number | null = null;
+ // Anthropic's explicit model_context_window_exceeded signal.
+ let providerReportedWindow = false;
const throwIfReasoningOnlyLength = () => {
if (
@@ -1690,11 +1707,14 @@ export async function* streamChatCompletions(
// The backend substitutes the full context length when the user left Max Tokens on "Max", so a payload value
// equal to it is indistinguishable from unset, and both mean the setting is not the lever.
throw new GenerationLengthError(
- maxTokensIsTheLimit({
- cap: payload.max_tokens ?? null,
- contextLength: loadedContextLength ?? null,
- promptTokens,
- }),
+ providerReportedWindow
+ ? "context_window"
+ : lengthStopCause({
+ cap: payload.max_tokens ?? null,
+ contextLength: loadedContextLength ?? null,
+ promptTokens,
+ completionTokens: windowCount,
+ }),
);
}
};
@@ -1783,10 +1803,22 @@ export async function* streamChatCompletions(
separatorIndex = buffer.search(/\r?\n\r?\n/);
continue;
}
- const parsedUsage = (parsed as { usage?: { prompt_tokens?: number } }).usage;
+ const {
+ usage: parsedUsage,
+ timings: parsedTimings,
+ _toolEvent: parsedToolEvent,
+ } = parsed as {
+ usage?: { prompt_tokens?: number };
+ timings?: { predicted_n?: number };
+ _toolEvent?: { type?: string };
+ };
if (typeof parsedUsage?.prompt_tokens === "number") {
promptTokens = parsedUsage.prompt_tokens;
}
+ windowCount = windowEvidenceCount(parsedTimings) ?? windowCount;
+ if (parsedToolEvent?.type === "context_window_exceeded") {
+ providerReportedWindow = true;
+ }
// finish_reason is a valid terminal signal for providers that close without a [DONE] sentinel.
const parsedChoices = (
parsed as {
diff --git a/studio/frontend/src/features/chat/api/generation-length.ts b/studio/frontend/src/features/chat/api/generation-length.ts
index fddd78cfb74..14e37fc4f54 100644
--- a/studio/frontend/src/features/chat/api/generation-length.ts
+++ b/studio/frontend/src/features/chat/api/generation-length.ts
@@ -29,3 +29,49 @@ export function maxTokensIsTheLimit({
// token, so raising Max Tokens creates no room. The context length is the lever there.
return promptTokens + cap < window;
}
+
+/** `context_length` is local; `context_window` is external; `unknown` lacks evidence. */
+export type LengthStopCause =
+ | "max_tokens"
+ | "context_length"
+ | "context_window"
+ | "unknown";
+
+export function lengthStopCause({
+ cap,
+ contextLength,
+ promptTokens,
+ completionTokens,
+}: {
+ cap: number | null;
+ contextLength: number | null;
+ promptTokens: number | null;
+ completionTokens: number | null;
+}): LengthStopCause {
+ // Only pass counts accepted by windowEvidenceCount for an unknown window.
+ if (contextLength === null && cap !== null) {
+ if (completionTokens === null) {
+ return "unknown";
+ }
+ return completionTokens < cap ? "context_window" : "max_tokens";
+ }
+ return maxTokensIsTheLimit({ cap, contextLength, promptTokens })
+ ? "max_tokens"
+ : "context_length";
+}
+
+/** Save external window exhaustion separately to prevent automatic continuation. */
+export function lengthIncompleteReason(
+ cause: LengthStopCause,
+): "context_window" | "length" {
+ return cause === "context_window" ? "context_window" : "length";
+}
+
+/** llama.cpp counts include reasoning. Ignore usage counts: providers may exclude reasoning
+ * or enforce a lower output cap, so those counts cannot establish context exhaustion. */
+export function windowEvidenceCount(
+ timings: { predicted_n?: unknown } | null | undefined,
+): number | null {
+ const count = timings?.predicted_n;
+ return typeof count === "number" && Number.isFinite(count) ? count : null;
+}
diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.ts
index f52ec12bbce..a0d0ab5d9c1 100644
--- a/studio/frontend/src/features/chat/provider-capabilities.ts
+++ b/studio/frontend/src/features/chat/provider-capabilities.ts
@@ -614,6 +614,17 @@ export function isGeminiCustomOpenAICompatBase(
}
}
+/** Native Gemini rejects oversized input before generation: Infinity attributes length stops
+ * to Max Tokens. Other providers and custom gateways have unknown windows. */
+export function externalStopWindow(
+ providerType: string | null | undefined,
+ baseUrl: string | null | undefined,
+): number | null {
+ return providerType === "gemini" && !isGeminiCustomOpenAICompatBase(baseUrl)
+ ? Number.POSITIVE_INFINITY
+ : null;
+}
+
/** Whether this Gemini image model supports googleSearch. Documented on the Gemini 3 image
* family; older ids reject it with "Search as tool is not enabled for this model". */
function geminiImageModelAllowsGoogleSearch(modelId: string): boolean {
diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.ts
index b471560c043..6a1f612dc17 100644
--- a/studio/frontend/src/features/chat/utils/continuation.ts
+++ b/studio/frontend/src/features/chat/utils/continuation.ts
@@ -61,6 +61,17 @@ export function resolveIncompleteReason<T extends IncompleteReason | null>(
return contextWindowExceeded ? "context_window" : reason;
}
+/** Let a context-window error refine a latched length stop; preserve other latched reasons. */
+export function incompleteReasonAfterError(
+ latched: IncompleteReason | null,
+ fromError: IncompleteReason,
+): IncompleteReason {
+ if (latched === "length" && fromError === "context_window") {
+ return fromError;
+ }
+ return latched ?? fromError;
+}
+
/** Whether the provider reported this reason rather than the client inferring it; the provider
* wins where they disagree. */
export function isProviderReportedReason(
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index 3da219a3d79..9c97c41e48b 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -25,6 +25,7 @@ const {
budgetImpliesTruncation,
hasRenderableContent,
incompleteLabel,
+ incompleteReasonAfterError,
incompleteRemedy,
isContinuableContent,
isProviderReportedReason,
@@ -2944,3 +2945,33 @@ test("a merger with repair off is the identity, streaming or final", () => {
assert.equal(merge(full), full);
assert.equal(merge(full, { final: true }), full);
});
+
+const ERROR_PATH_REASON =
+ /incompleteReasonAfterError\(\s*incompleteReason,\s*err instanceof GenerationLengthError\s*\?\s*lengthIncompleteReason\(err\.stopCause\)/;
+
+test("a length error refines the length the terminal chunk latched", () => {
+ // The terminal chunk latches length before GenerationLengthError identifies the cause.
+ assert.equal(
+ incompleteReasonAfterError("length", "context_window"),
+ "context_window",
+ );
+ assert.equal(incompleteReasonAfterError("length", "length"), "length");
+ // An explicit Stop still outranks whatever the error says.
+ assert.equal(
+ incompleteReasonAfterError("cancelled", "context_window"),
+ "cancelled",
+ );
+ // Nothing latched: the error decides, as before.
+ assert.equal(
+ incompleteReasonAfterError(null, "context_window"),
+ "context_window",
+ );
+ assert.equal(incompleteReasonAfterError(null, "interrupted"), "interrupted");
+ // A latched reason is not overridden by an unrelated error.
+ assert.equal(incompleteReasonAfterError("length", "interrupted"), "length");
+});
+
+test("the adapter's error path asks the length error which limit it was", () => {
+ // Check the wiring without initializing the adapter's stores.
+ assert.match(CHAT_ADAPTER, ERROR_PATH_REASON);
+});
diff --git a/studio/frontend/tests/generation-length-cap-attribution.test.ts b/studio/frontend/tests/generation-length-cap-attribution.test.ts
index c8d8c06bceb..d1c5ff539eb 100644
--- a/studio/frontend/tests/generation-length-cap-attribution.test.ts
+++ b/studio/frontend/tests/generation-length-cap-attribution.test.ts
@@ -4,18 +4,33 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { maxTokensIsTheLimit } from "../src/features/chat/api/generation-length.ts";
+import {
+ lengthStopCause,
+ maxTokensIsTheLimit,
+ windowEvidenceCount,
+} from "../src/features/chat/api/generation-length.ts";
-import { readSrc } from "./helpers/kit.ts";
+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { externalStopWindow } = await import(
+ "../src/features/chat/provider-capabilities.ts"
+);
const CHAT_ADAPTER = readSrc("features/chat/api/chat-adapter.ts");
+const CHAT_API = readSrc("features/chat/api/chat-api.ts");
// Hoisted: biome's useTopLevelRegex flags a literal recompiled per call.
const LOCAL_WINDOW_ARGUMENT =
- /isExternalRequest\s*\n\s*\? null\s*\n\s*: \(runtime\.loadedCustomContextLength \?\?\s*\n\s*runtime\.loadedContextLength \?\?\s*\n\s*\(params\.maxSeqLength \|\| null\)\)/;
+ /isExternalRequest\s*\n\s*\? externalStopWindow\(\s*externalProvider\?\.providerType,\s*externalProvider\?\.baseUrl,\s*\)\s*\n\s*: \(runtime\.loadedCustomContextLength \?\?\s*\n\s*runtime\.loadedContextLength \?\?\s*\n\s*\(params\.maxSeqLength \|\| null\)\)/;
// The EDITABLE field must not be what a stop is judged against: the store defines a
// pending context edit as exactly `customContextLength !== loadedCustomContextLength`.
const PENDING_FIELD = /: \(runtime\.customContextLength \?\?/;
+const WINDOW_COUNT_FROM_TIMINGS = /windowEvidenceCount\(parsedTimings\)/;
+const ADAPTER_COUNT_FROM_TIMINGS = /windowEvidenceCount\(chunkTimings\)/;
+const PROVIDER_WINDOW_EVENT =
+ /parsedToolEvent\?\.type === "context_window_exceeded"/;
+const PROVIDER_WINDOW_WINS = /providerReportedWindow\s*\?\s*"context_window"/;
test("a cap the prompt left no room for is not the limit that was hit", () => {
// 4096 window, 3000-token prompt, Max Tokens 2048: generation stops at roughly 1096,
@@ -109,3 +124,143 @@ test("a pending Context Length edit does not decide what stopped the generation"
assert.match(CHAT_ADAPTER, LOCAL_WINDOW_ARGUMENT);
assert.doesNotMatch(CHAT_ADAPTER, PENDING_FIELD);
});
+
+test("a stop short of the cap against a window Studio cannot see filled that window", () => {
+ // Prompt + output fills a 4096-token window before reaching Max Tokens.
+ assert.equal(
+ lengthStopCause({
+ cap: 2048,
+ contextLength: null,
+ promptTokens: 3857,
+ completionTokens: 239,
+ }),
+ "context_window",
+ );
+ assert.equal(
+ lengthStopCause({
+ cap: 2048,
+ contextLength: null,
+ promptTokens: null,
+ completionTokens: 2048,
+ }),
+ "max_tokens",
+ );
+});
+
+test("with no window and no output count, neither wall is claimed", () => {
+ assert.equal(
+ lengthStopCause({
+ cap: 2048,
+ contextLength: null,
+ promptTokens: null,
+ completionTokens: null,
+ }),
+ "unknown",
+ );
+});
+
+test("a known window still decides from the prompt, as before", () => {
+ assert.equal(
+ lengthStopCause({
+ cap: 2048,
+ contextLength: 4096,
+ promptTokens: 3000,
+ completionTokens: 1096,
+ }),
+ "context_length",
+ );
+ assert.equal(
+ lengthStopCause({
+ cap: 512,
+ contextLength: 4096,
+ promptTokens: 3000,
+ completionTokens: 512,
+ }),
+ "max_tokens",
+ );
+});
+
+/** Classify a final chunk using the stream parser's inputs. */
+function causeOf(
+ chunk: {
+ usage?: { prompt_tokens?: number; completion_tokens?: number };
+ timings?: { predicted_n?: number };
+ },
+ cap: number,
+) {
+ return lengthStopCause({
+ cap,
+ contextLength: null,
+ promptTokens: chunk.usage?.prompt_tokens ?? null,
+ completionTokens: windowEvidenceCount(chunk.timings),
+ });
+}
+
+test("llama.cpp's own count tells a full window from Max Tokens", () => {
+ // The live case: 3,842 + 254 tokens filled a 4096 window with Max Tokens at 2048.
+ assert.equal(
+ causeOf({ timings: { predicted_n: 254 } }, 2048),
+ "context_window",
+ );
+ assert.equal(causeOf({ timings: { predicted_n: 2048 } }, 2048), "max_tokens");
+ assert.equal(windowEvidenceCount({ predicted_n: "254" }), null);
+});
+
+test("a count that leaves out reasoning does not claim a full window", () => {
+ // xAI excludes reasoning from completion_tokens.
+ assert.equal(
+ causeOf(
+ {
+ usage: { prompt_tokens: 32, completion_tokens: 9 },
+ },
+ 64,
+ ),
+ "unknown",
+ );
+});
+
+test("an output budget the server lowered does not claim a full window", () => {
+ // The server caps output at 4096 despite the requested 8192.
+ assert.equal(
+ causeOf({ usage: { prompt_tokens: 900, completion_tokens: 4096 } }, 8192),
+ "unknown",
+ );
+});
+
+test("the stream reads the window from llama.cpp timings and the provider's own report", () => {
+ assert.match(CHAT_API, WINDOW_COUNT_FROM_TIMINGS);
+ assert.match(CHAT_ADAPTER, ADAPTER_COUNT_FROM_TIMINGS);
+ assert.match(CHAT_API, PROVIDER_WINDOW_EVENT);
+ assert.match(CHAT_API, PROVIDER_WINDOW_WINS);
+});
+
+test("a Gemini length stop is always the output limit", () => {
+ // Native Gemini rejects oversized input before generation.
+ const window = externalStopWindow("gemini", null);
+ for (const [completionTokens, cap] of [
+ [60, 64],
+ [99, 100],
+ [8177, 8192],
+ ]) {
+ assert.equal(
+ lengthStopCause({
+ cap,
+ contextLength: window,
+ promptTokens: 1200,
+ completionTokens,
+ }),
+ "max_tokens",
+ );
+ }
+ assert.equal(
+ externalStopWindow(
+ "gemini",
+ "https://generativelanguage.googleapis.com/v1beta",
+ ),
+ Number.POSITIVE_INFINITY,
+ );
+ // Custom gateways and other providers keep an unknown window.
+ assert.equal(externalStopWindow("gemini", "http://localhost:4000/v1"), null);
+ assert.equal(externalStopWindow("custom", null), null);
+ assert.equal(externalStopWindow(undefined, null), null);
+});
diff --git a/studio/frontend/tests/generation-length-toast-advice.test.ts b/studio/frontend/tests/generation-length-toast-advice.test.ts
index 4e1b3671a2e..620337afa3a 100644
--- a/studio/frontend/tests/generation-length-toast-advice.test.ts
+++ b/studio/frontend/tests/generation-length-toast-advice.test.ts
@@ -23,6 +23,9 @@ const CAP_REMEDY = /Increase Max Tokens or disable thinking/;
const WINDOW_REMEDY = /cannot create room the window does not have/;
const NO_UNLIMITED_CLAIM = /already unlimited/;
const WINDOW_SETTING = /Length in Model settings/;
+const HIDDEN_WINDOW_REMEDY =
+ /Start a new chat, or shorten this one, then retry/;
+const BOTH_REMEDIES = /Max Tokens or its context window before answering/;
test("the toast repeats the advice the error chose, not the Max Tokens advice", () => {
// GenerationLengthError already decides between the Max Tokens and the Context
@@ -45,4 +48,7 @@ test("the two remedies really are different text, so passing it through matters"
assert.match(chatApi, WINDOW_REMEDY);
assert.match(chatApi, WINDOW_SETTING);
assert.doesNotMatch(chatApi, NO_UNLIMITED_CLAIM);
+ // External windows need different advice.
+ assert.match(chatApi, HIDDEN_WINDOW_REMEDY);
+ assert.match(chatApi, BOTH_REMEDIES);
});