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
Studio: finish a reply that hit Max Tokens instead of asking whether to (#9382)
Daniel Han0436f60cb652
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 09d4e6d6aef..e6a33aa9d96 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -134,6 +134,9 @@ import {modeAllowsContinuation,readIncompleteInfo,readTextThoughtSignature,+ claimAutoContinue,+ recordAutoContinue,+ shouldAutoContinueMessage,} from "@/features/chat/utils/continuation";import { McpComposerButton } from "@/features/chat/mcp-composer-button";import { getExternalReasoningCapabilities } from "@/features/chat/provider-capabilities";@@ -274,6 +277,7 @@ import {FastForwardIcon,GlobeIcon,HeadphonesIcon,+ Loader2Icon,MoreHorizontalIcon,PlusIcon,RefreshCwIcon,@@ -6493,24 +6497,111 @@ const ContinueMessageBarForLastMessage: FC = () => {status?.type === "incomplete" && status?.reason === "cancelled";const reason = cancelled ? ("cancelled" as const) : stamped?.reason;- // Newest turn only: appending to an older one would strand the replies after it.- // A turn cut mid-thought has no text to resume from, so Retry stays the way out.- if (- !reason ||- !isLast ||- isRunning ||- researchRunId ||- researchActive ||- !continuable ||- !modeAllowsContinuation({+ // Every gate the bar itself answers to. Resuming without asking has to clear the same+ // ones, or it would resume a turn the bar would have refused to offer.+ const resumable =+ Boolean(reason) &&+ isLast &&+ !isRunning &&+ !researchRunId &&+ !researchActive &&+ continuable &&+ modeAllowsContinuation({fromAudioInput,audioOutputModel,deepResearchArmed,- }) ||- !partial.trim()- ) {+ }) &&+ Boolean(partial.trim());++ // The parent is what every round of one logical turn shares; the message id changes+ // each round, because a continuation runs as a sibling.+ const parentId = useAuiState(({ thread, message }) => {+ const index = thread.messages.findIndex((m) => m.id === message.id);+ return index > 0 ? thread.messages[index - 1].id : null;+ });++ const startContinuation = useCallback(() => {+ const messages = aui.thread().getState().messages;+ const index = messages.findIndex((message) => message.id === messageId);+ if (index < 0) {+ return;+ }+ // Sibling of the truncated turn, so the branch picker can still reach the partial.+ const parent = index > 0 ? messages[index - 1].id : null;+ aui.thread().startRun({+ parentId: parent,+ runConfig: {+ custom: {+ [CONTINUATION_RUN_CONFIG_KEY]: { partial, thoughtSignature },+ },+ },+ });+ }, [aui, messageId, partial, thoughtSignature]);++ // The resumed turn's own fit. Resuming replays the partial as the final assistant turn,+ // which the fit protects, so a partial too big to sit beside the system turn makes the+ // request irreducible and every further round fails identically.+ const truncation = useAuiState(({ message }) => {+ const custom = (message.metadata as { custom?: Record<string, unknown> } | undefined)+ ?.custom;+ return (custom?.contextTruncation ?? null) as+ | { fits?: boolean; prompt_target?: number }+ | null;+ });++ // Hitting Max Tokens is the reply running out of room mid-sentence, not a decision the+ // user made, so it resumes on its own and the bar never appears. Bounded, and only for+ // `length`: see `shouldAutoContinue`. Asked per MESSAGE, not just per turn: the round+ // budget belongs to the turn and one spent round out of three still says yes, so+ // arriving at a message the claim below has already taken -- the branch picker back to+ // the truncated sibling, or returning to the chat -- would otherwise show a spinner for+ // a run `claimAutoContinue` refuses to start, on top of the Continue button it hides.+ const autoContinuing =+ resumable &&+ shouldAutoContinueMessage(messageId, reason, parentId, {+ fits: truncation?.fits,+ // The same cheap estimator the backend fit uses, which is all that is needed to+ // spot a partial that has already eaten the whole budget.+ partialTokens: Math.ceil(partial.length / 4),+ promptTarget: truncation?.prompt_target,+ });+ useEffect(() => {+ if (!autoContinuing || !parentId) {+ return;+ }+ // Claimed in module scope, not a ref. `<StrictMode>` in src/main.tsx replays this+ // effect on the same fiber with the same `autoContinuing`, so nothing inside would+ // have differed, and rechecking the round budget would not help either: one recorded+ // round still leaves the limit unspent. A ref fixed the replay but not a real+ // remount, so leaving the chat with a truncated branch selected and returning fired+ // it again, creating another sibling and another paid request. The claim survives+ // both, and is the same seam `resetAutoContinue()` clears.+ if (!claimAutoContinue(messageId)) {+ return;+ }+ // Recorded BEFORE the run, so a round that produces nothing still spends its budget+ // instead of re-firing this effect forever.+ recordAutoContinue(parentId);+ startContinuation();+ }, [autoContinuing, parentId, messageId, startContinuation]);++ // Newest turn only: appending to an older one would strand the replies after it.+ // A turn cut mid-thought has no text to resume from, so Retry stays the way out.+ // `reason` is repeated rather than left to `resumable`, which is a boolean and so+ // narrows nothing: the label below needs it proven non-undefined.+ if (!resumable || !reason) {return null;}+ if (autoContinuing) {+ // The run is starting this tick; showing the bar first would flash a question that is+ // already being answered.+ return (+ <div className="aui-continue-bar mt-2 flex items-center gap-2 rounded-md border border-border/70 bg-muted/50 p-2.5 text-sm text-muted-foreground">+ <Loader2Icon className="size-3.5 animate-spin" strokeWidth={1.75} />+ Continuing automatically.+ </div>+ );+ }const handleContinue = () => {const messages = aui.thread().getState().messages;diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.tsindex 51180fbc8df..b3029390a0f 100644--- a/studio/frontend/src/features/chat/utils/continuation.ts+++ b/studio/frontend/src/features/chat/utils/continuation.ts@@ -282,3 +282,157 @@ export function readContinuationRequest(}return null;}++/**+ * Resuming a Max Tokens cut WITHOUT asking.+ *+ * Hitting the cap is not a decision the user made; it is the reply running out of room+ * mid-sentence, and the only sensible answer to "the answer is not finished" is to finish+ * it. Every other reason is left alone: `cancelled` is the user pressing Stop, so+ * resuming would restart the thing they just stopped, and `interrupted` means the+ * connection dropped, where a silent retry can hide a broken link.+ *+ * Bounded, because a model that will not stop would otherwise loop forever, and each+ * round grows the transcript and drives compaction harder. After the budget is spent the+ * bar comes back and the user decides.+ */+export const AUTO_CONTINUE_LIMIT = 3;++/**+ * Rounds already spent per logical turn, keyed by the parent the continuation hangs off.+ *+ * Keyed on the PARENT, not the message: a continuation runs as a sibling of the turn it+ * resumes, so each round produces a new message id and a per-message counter would reset+ * every time and never reach its limit. The parent is the one id every round of the same+ * turn shares. In memory only; a reload is a fresh decision by a present user.+ */+const spent = new Map<string, number>();++/**+ * Whether this cut should resume on its own.+ *+ * `fits` and `promptTarget` come from the resumed turn's own truncation metadata, and+ * both exist because resuming FIGHTS the context window. A continuation replays the+ * partial as the final assistant turn, and the fit protects the final group, so the+ * partial is the one thing compaction may not evict. Once it is large enough that the+ * system turn plus the carried-forward block will not fit beside it, the request is+ * irreducible and every further round produces the same refusal.+ *+ * Measured at a 4,864-token context: a 3,217-token partial plus system and X came to+ * 4,218 against a 3,648-token target, so the answer could not be resumed at all -- and+ * three automatic rounds each asked anyway and each failed identically.+ */+export function shouldAutoContinue(+ reason: IncompleteReason | null | undefined,+ key: string | null | undefined,+ {+ limit = AUTO_CONTINUE_LIMIT,+ fits,+ partialTokens,+ promptTarget,+ }: {+ limit?: number;+ /** `contextTruncation.fits` of the turn being resumed. */+ fits?: boolean;+ /** Estimated size of the partial that would be replayed. */+ partialTokens?: number;+ /** `contextTruncation.prompt_target`: what the window leaves for the prompt. */+ promptTarget?: number;+ } = {},+): boolean {+ if (reason !== "length" || !key) {+ return false;+ }+ if (fits === false) {+ // This turn's own fit was already refused. Resuming re-sends a partial that is only+ // ever longer, so the next round cannot fit either.+ return false;+ }+ if (+ typeof partialTokens === "number" &&+ typeof promptTarget === "number" &&+ promptTarget > 0 &&+ partialTokens >= promptTarget+ ) {+ // The partial alone meets the budget, so nothing can be sent beside it -- not the+ // system prompt, not the user's own question. Raising Context Length is the only+ // remedy and the bar says so.+ return false;+ }+ return (spent.get(key) ?? 0) < limit;+}++/** Record a round against `key`. Called before the run starts, so a run that fails to+ * produce anything still consumes its budget rather than retrying forever. */+export function recordAutoContinue(key: string): void {+ spent.set(key, (spent.get(key) ?? 0) + 1);+}++/** Rounds spent so far, for the indicator and for tests. */+export function autoContinueCount(key: string | null | undefined): number {+ return key ? (spent.get(key) ?? 0) : 0;+}++/**+ * Messages this session has already continued automatically, by message id.+ *+ * Separate from `spent`, which counts rounds per logical turn and is what bounds a+ * runaway loop. This answers a different question: has THIS message already been+ * resumed once. A component-local ref cannot, because it dies with the component.+ * Leave the chat with a truncated branch selected and come back, and the ref is fresh+ * while the parent still has budget, so the effect fires again and creates another+ * sibling and another paid request. Module scope outlives the remount; the ids are+ * short and bounded by how many replies a session truncates.+ */+const continued = new Set<string>();++/** Whether `messageId` still needs continuing. False once it has been claimed. */+export function claimAutoContinue(messageId: string | null | undefined): boolean {+ if (!messageId || continued.has(messageId)) {+ return false;+ }+ continued.add(messageId);+ return true;+}++/** Whether `messageId` was already continued automatically this session. */+export function wasAutoContinued(messageId: string | null | undefined): boolean {+ return Boolean(messageId && continued.has(messageId));+}++/**+ * Whether THIS message is the one to continue automatically.+ *+ * `shouldAutoContinue` answers about the turn: is the reason right, does the partial+ * still fit, is the round budget unspent. It keeps saying yes after a message has been+ * claimed, because the budget is per turn and one spent round out of three leaves the+ * turn resumable, while the claim is per message and is what actually decides whether a+ * run starts. Anything rendering off the turn's answer alone therefore reports an+ * already-claimed message as continuing while `claimAutoContinue` refuses to start+ * anything: a spinner that never resolves, over the manual Continue button it replaces.+ *+ * Reachable without a reload. The continuation runs as a sibling and the branch picker+ * leads straight back to the truncated partial, and leaving the chat and returning lands+ * on it too whenever it is still the selected branch.+ */+export function shouldAutoContinueMessage(+ messageId: string | null | undefined,+ reason: IncompleteReason | null | undefined,+ key: string | null | undefined,+ options: Parameters<typeof shouldAutoContinue>[2] = {},+): boolean {+ if (wasAutoContinued(messageId)) {+ return false;+ }+ return shouldAutoContinue(reason, key, options);+}++/** Test seam; also lets a new thread start from zero. */+export function resetAutoContinue(key?: string): void {+ if (key === undefined) {+ spent.clear();+ continued.clear();+ } else {+ spent.delete(key);+ }+}diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.tsindex 18f0039b615..11d9bda6251 100644--- a/studio/frontend/tests/chat-continuation.test.ts+++ b/studio/frontend/tests/chat-continuation.test.ts@@ -9,6 +9,8 @@ import { registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();const {+ AUTO_CONTINUE_LIMIT,+ autoContinueCount,budgetImpliesTruncation,incompleteLabel,isContinuableContent,@@ -18,7 +20,13 @@ const {readContinuationRequest,readIncompleteInfo,readTextThoughtSignature,+ claimAutoContinue,+ recordAutoContinue,rejectsAssistantPrefill,+ resetAutoContinue,+ wasAutoContinued,+ shouldAutoContinue,+ shouldAutoContinueMessage,resumesExactly,stripContinuationOverlap,} = await import("../src/features/chat/utils/continuation.ts");@@ -314,3 +322,174 @@ test("citations appended for display do not block Continue", () => {true,);});++test("a Max Tokens cut resumes on its own", () => {+ resetAutoContinue();+ // Not a decision the user made: the reply ran out of room mid-sentence, and asking+ // whether to finish it is asking a question with one sensible answer.+ assert.equal(shouldAutoContinue("length", "parent-1"), true);+});++test("pressing Stop is never undone by an automatic resume", () => {+ resetAutoContinue();+ // The one case where the user HAS decided. Resuming would restart what they stopped.+ assert.equal(shouldAutoContinue("cancelled", "parent-1"), false);+});++test("a dropped connection still asks, rather than retrying silently", () => {+ resetAutoContinue();+ // A silent retry here hides a broken link behind what looks like a slow answer.+ assert.equal(shouldAutoContinue("interrupted", "parent-1"), false);+});++test("automatic resumes are bounded, then the bar comes back", () => {+ resetAutoContinue();+ // A model that will not stop would otherwise loop forever, and every round grows the+ // transcript and drives compaction harder.+ for (let round = 0; round < AUTO_CONTINUE_LIMIT; round += 1) {+ assert.equal(shouldAutoContinue("length", "parent-1"), true);+ recordAutoContinue("parent-1");+ }+ assert.equal(autoContinueCount("parent-1"), AUTO_CONTINUE_LIMIT);+ assert.equal(shouldAutoContinue("length", "parent-1"), false);+});++test("the budget is per turn, so a later turn is not punished for an earlier one", () => {+ resetAutoContinue();+ for (let round = 0; round < AUTO_CONTINUE_LIMIT; round += 1) {+ recordAutoContinue("parent-1");+ }+ assert.equal(shouldAutoContinue("length", "parent-1"), false);+ assert.equal(shouldAutoContinue("length", "parent-2"), true);+});++test("the count is keyed on the parent, which every round of one turn shares", () => {+ resetAutoContinue();+ // A continuation runs as a SIBLING, so each round has a new message id. Keying on that+ // would reset the counter every round and the limit would never be reached.+ recordAutoContinue("parent-1");+ recordAutoContinue("parent-1");+ assert.equal(autoContinueCount("parent-1"), 2);+});++test("a turn with no parent is never resumed automatically", () => {+ resetAutoContinue();+ // The very first message has nothing to hang a sibling off, so there is no stable key+ // to count against and an unbounded loop is the failure mode.+ assert.equal(shouldAutoContinue("length", null), false);+});++test("a turn whose own fit was refused is never resumed automatically", () => {+ resetAutoContinue();+ // Resuming replays the partial as the final assistant turn, which the fit protects, so+ // the next round sends a partial that is only ever longer. Observed at a 4,864-token+ // context: three automatic rounds, each refused identically.+ assert.equal(+ shouldAutoContinue("length", "parent-1", { fits: false }),+ false,+ );+});++test("a partial that already fills the budget is not resumed", () => {+ resetAutoContinue();+ // 3,217 tokens of partial against a 3,648-token target left no room for the system turn+ // and the carried-forward block, so the request was irreducible before it was sent.+ assert.equal(+ shouldAutoContinue("length", "parent-1", {+ partialTokens: 3648,+ promptTarget: 3648,+ }),+ false,+ );+ // Comfortably inside the budget still resumes.+ assert.equal(+ shouldAutoContinue("length", "parent-1", {+ partialTokens: 400,+ promptTarget: 3648,+ }),+ true,+ );+});++test("an unknown fit does not block resuming", () => {+ resetAutoContinue();+ // A turn that never truncated carries no metadata, and that is the ordinary case.+ assert.equal(shouldAutoContinue("length", "parent-1", {}), true);+ assert.equal(+ shouldAutoContinue("length", "parent-1", { fits: true }),+ true,+ );+});++test("a message is claimed for automatic continuation exactly once", () => {+ resetAutoContinue();+ assert.equal(claimAutoContinue("m1"), true);+ assert.equal(claimAutoContinue("m1"), false);+ assert.equal(claimAutoContinue("m1"), false);+});++test("the claim survives a remount, which a component ref did not", () => {+ // Leave the chat with a truncated branch selected and come back: a ref was fresh+ // while the parent still had budget, so the effect fired again and created another+ // sibling and another paid provider request.+ resetAutoContinue();+ assert.equal(claimAutoContinue("m1"), true);+ assert.equal(shouldAutoContinue("length", "parent-1"), true);+ assert.equal(claimAutoContinue("m1"), false);+});++test("claims are tracked per message", () => {+ resetAutoContinue();+ assert.equal(claimAutoContinue("m1"), true);+ assert.equal(claimAutoContinue("m2"), true);+ assert.equal(claimAutoContinue("m1"), false);+});++test("a missing message id is refused rather than claimed", () => {+ resetAutoContinue();+ assert.equal(claimAutoContinue(null), false);+ assert.equal(claimAutoContinue(undefined), false);+ assert.equal(claimAutoContinue(""), false);+});++test("a claim is reported and cleared by a full reset", () => {+ resetAutoContinue();+ assert.equal(wasAutoContinued("m1"), false);+ claimAutoContinue("m1");+ assert.equal(wasAutoContinued("m1"), true);+ resetAutoContinue();+ assert.equal(wasAutoContinued("m1"), false);+ assert.equal(claimAutoContinue("m1"), true);+});++test("a message already claimed stops reporting itself as continuing", () => {+ resetAutoContinue();+ // The turn that fires it: nothing has claimed the message yet.+ assert.equal(shouldAutoContinueMessage("m1", "length", "parent-1"), true);+ claimAutoContinue("m1");+ recordAutoContinue("parent-1");++ // Back on the truncated branch, whether through the branch picker or by returning to+ // the chat: `claimAutoContinue` refuses the run, so the turn's own budget still saying+ // yes would leave a spinner nothing is answering, over a hidden manual Continue button.+ assert.equal(shouldAutoContinue("length", "parent-1"), true);+ assert.equal(shouldAutoContinueMessage("m1", "length", "parent-1"), false);+});++test("a claim on one message does not silence another", () => {+ resetAutoContinue();+ claimAutoContinue("m1");+ // The next round of the same turn is a new message with budget left, and continues.+ recordAutoContinue("parent-1");+ assert.equal(shouldAutoContinueMessage("m2", "length", "parent-1"), true);+});++test("a claimed message still honours the gates the turn itself fails", () => {+ resetAutoContinue();+ // Nothing about the claim resurrects a cut that was never automatic in the first place.+ assert.equal(shouldAutoContinueMessage("m1", "cancelled", "parent-1"), false);+ assert.equal(+ shouldAutoContinueMessage("m2", "length", "parent-1", { fits: false }),+ false,+ );+});