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: stop two tabs both auto-continuing the same truncated reply (#9425)
Daniel Han5869a66abf19
diff --git a/.github/scripts/run-studio-indicator-browser.sh b/.github/scripts/run-studio-indicator-browser.shindex 65fb21cac30..23d466d1635 100755--- a/.github/scripts/run-studio-indicator-browser.sh+++ b/.github/scripts/run-studio-indicator-browser.sh@@ -53,8 +53,15 @@ trap '_on_signal INT 2' INTtrap '_on_signal HUP 1' HUPhealthy=0-for _ in $(seq 1 180); do- if curl -fs "http://127.0.0.1:$port/api/health" >/dev/null; then+# --max-time, or only the loop counter is bounded and a server that binds the+# port then wedges parks the first iteration forever. And a real deadline+# rather than an iteration count, because once a probe can cost --max-time,+# 180 iterations is up to 18 minutes rather than the 180s it reads as. See+# wait-for-health.sh, which had both halves of the same hole.+health_deadline=$(( SECONDS + 180 ))+while [ "$SECONDS" -lt "$health_deadline" ]; do+ if curl -fs --connect-timeout 3 --max-time 5 \+ "http://127.0.0.1:$port/api/health" >/dev/null; thenhealthy=1breakfidiff --git a/.github/scripts/run-studio-permission-browser.sh b/.github/scripts/run-studio-permission-browser.shindex 81ea0d1ad83..d2dddb68cd3 100755--- a/.github/scripts/run-studio-permission-browser.sh+++ b/.github/scripts/run-studio-permission-browser.sh@@ -62,8 +62,15 @@ trap '_on_signal INT 2' INTtrap '_on_signal HUP 1' HUPhealthy=0-for _ in $(seq 1 180); do- if curl -fs "http://127.0.0.1:$port/api/health" >/dev/null; then+# --max-time, or only the loop counter is bounded and a server that binds the+# port then wedges parks the first iteration forever. And a real deadline+# rather than an iteration count, because once a probe can cost --max-time,+# 180 iterations is up to 18 minutes rather than the 180s it reads as. See+# wait-for-health.sh, which had both halves of the same hole.+health_deadline=$(( SECONDS + 180 ))+while [ "$SECONDS" -lt "$health_deadline" ]; do+ if curl -fs --connect-timeout 3 --max-time 5 \+ "http://127.0.0.1:$port/api/health" >/dev/null; thenhealthy=1breakfidiff --git a/.github/scripts/wait-for-health.sh b/.github/scripts/wait-for-health.shindex 270a36d9737..6d83e88a0f5 100755--- a/.github/scripts/wait-for-health.sh+++ b/.github/scripts/wait-for-health.sh@@ -62,8 +62,24 @@ done[ -n "$PORT" ] || { echo "wait-for-health.sh: --port is required" >&2; exit 2; }-for _ in $(seq 1 "$TIMEOUT_SECONDS"); do- if curl -fs "http://127.0.0.1:${PORT}/api/health" > "$TMP" \+# Two halves of one bound, and neither works without the other.+#+# --max-time, because curl sets no maximum transfer time by default and+# --connect-timeout stops helping the moment the handshake completes. A Studio+# that binds the port and then wedges its event loop -- the shape of a wedged+# server on a 4 vCPU runner with four of them on it -- parks the FIRST+# iteration forever, and an iteration count is not a deadline if an iteration+# can be infinite.+#+# A real deadline, because once each probe can cost up to --max-time, counting+# iterations turns "180s" into up to 180 x 6s = 18 minutes: a bound far looser+# than the one this file advertises, and looser than the lane budget that+# contains it. $SECONDS is the elapsed wall of this shell, so the wait is now+# TIMEOUT_SECONDS of real time no matter what each probe costs.+deadline=$(( SECONDS + TIMEOUT_SECONDS ))+while [ "$SECONDS" -lt "$deadline" ]; do+ if curl -fs --connect-timeout 3 --max-time 5 \+ "http://127.0.0.1:${PORT}/api/health" > "$TMP" \&& jq -e '.status == "healthy"' "$TMP" > /dev/null; thenecho "[health] 127.0.0.1:${PORT} reported healthy"exit 0diff --git a/.github/workflows/studio-windows-ui-smoke.yml b/.github/workflows/studio-windows-ui-smoke.ymlindex e67bb989b36..4412b73266b 100644--- a/.github/workflows/studio-windows-ui-smoke.yml+++ b/.github/workflows/studio-windows-ui-smoke.yml@@ -380,30 +380,122 @@ jobs:# split and why there are two lanes and not five. Wait on BOTH before# failing: backgrounding defeats `set -e`, and without an explicit# wait-and-collect one lane's breakage hides the other's.+ #+ # AND BOUND BOTH. Nothing here used to have a deadline shorter than the+ # job's own 45 minutes. Every wait inside the suites is per-operation --+ # 60s default, 540s a turn, 1080s for the rapid-submit predicate -- and+ # five turns of a stalled model reach the job cap before any single one of+ # them fires. On the #9425 branch this step started at 04:33:01 and never+ # returned; the runner killed the job at its cap and GitHub recorded the+ # result as "cancelled", which `gh pr checks` renders as a failure and+ # which reads exactly like ordinary concurrency supersession. See+ # studio-backend-ci.yml, wedged the same way and bounded the same way.+ #+ # And it left nothing to read. The lane .out files are only cat'ed after+ # both `wait`s return, so a stalled step prints NOTHING while it stalls;+ # the `if: always()` artifact upload does not run when the runner kills+ # the job at its cap; and Python block-buffers stdout into a file, so the+ # buffer went down with the process. 48 minutes, no logs, no artifacts.+ #+ # So: `timeout` per lane, a heartbeat while they run, unbuffered stdout so+ # what they printed survives being killed, and the server log tailed next+ # to the lane log because a lane killed mid-turn is usually explained by+ # the llama-server it was driving. A lane that wedges now fails, names+ # itself, and leaves evidence, and its sibling still reports its own+ # result instead of being buried with it.- name: Drive the UI suites in two parallel lanes+ # Bounds the whole step below the job's 45m cap even if `timeout` itself+ # is defeated, and -- the point -- leaves room for "Upload Playwright+ # artifacts" to actually run. ~7m of prologue precedes this step.+ timeout-minutes: 28env:GGUF_REPO: ${{ env.GGUF_REPO }}GGUF_VARIANT: ${{ env.GGUF_VARIANT }}+ # Block-buffered stdout is discarded when a wedged lane is killed,+ # which is the one run whose output is worth having.+ PYTHONUNBUFFERED: '1'run: |mkdir -p logs+ # The backstop, not the first line of defence: the suites' own wall+ # watchdogs should fire first and say which step they died on. 1500s+ # is 3.6x the measured lane wall (375s chat, 413s extra) and 3x the+ # slowest this step has ever been while succeeding (508s over 521+ # runs). The failures it is here for sat at 2900s. SIGINT first so a+ # suite can unwind and print the wait it was stuck on; SIGKILL 60s+ # later for the native Windows processes MSYS cannot signal politely.+ #+ lane_timeout=1500++ # Which `timeout` matters here. C:\Windows\System32\timeout.exe is on+ # PATH too, with entirely different semantics (`timeout /t N`), and+ # this job prepends a shim directory to GITHUB_PATH -- so the bare+ # name is not safe to resolve. Prefer the absolute coreutils path,+ # accept a bare one that proves itself with --version (which System32+ # does not answer), and fail loudly rather than silently running the+ # lanes unbounded again: MinGit trims usr/bin, so this is worth+ # checking rather than assuming.+ lane_timeout_bin=""+ for candidate in /usr/bin/timeout timeout; do+ if "$candidate" --version >/dev/null 2>&1; then+ lane_timeout_bin="$candidate"+ break+ fi+ done+ if [ -z "$lane_timeout_bin" ]; then+ echo "::error::no GNU coreutils timeout on this runner; the UI lanes would run unbounded and a wedge would burn the whole job again. Install coreutils or bound the lanes another way."+ exit 1+ fi+ echo "[lanes] bounding each lane with $lane_timeout_bin at ${lane_timeout}s"+pids=""for lane in chat extra; do- bash .github/scripts/run-studio-ui-lane.sh "$lane" \+ "$lane_timeout_bin" --signal=INT --kill-after=60 "$lane_timeout" \+ bash .github/scripts/run-studio-ui-lane.sh "$lane" \>"logs/lane-$lane.out" 2>&1 &pids="$pids $!:$lane"done++ # Without this the step is silent for its entire duration, so a stall+ # is indistinguishable from progress while it is happening.+ (+ while sleep 60; do+ for lane in chat extra; do+ [ -f "logs/lane-$lane.out" ] || continue+ echo "[heartbeat ${SECONDS}s] $lane: $(tail -n 1 "logs/lane-$lane.out" 2>/dev/null)"+ done+ done+ ) &+ heartbeat=$!+rc=0for entry in $pids; do- if ! wait "${entry%%:*}"; then- echo "::error::Windows UI lane ${entry##*:} failed"- rc=1- fi+ lane="${entry##*:}"+ status=0+ wait "${entry%%:*}" || status=$?+ [ "$status" -eq 0 ] && continue+ rc=1+ case "$status" in+ 124|137)+ echo "::error::Windows UI lane $lane did not finish within ${lane_timeout}s and was killed. Its last output and its server log are below, and in the uploaded artifacts."+ ;;+ *)+ echo "::error::Windows UI lane $lane failed (exit $status)"+ ;;+ esacdone+ kill "$heartbeat" 2>/dev/null || true+for f in logs/lane-*.out; doecho "::group::$f"cat "$f"echo "::endgroup::"done+ for f in logs/studio-lane-*.log; do+ [ -f "$f" ] || continue+ echo "::group::$f (tail)"+ tail -n 80 "$f"+ echo "::endgroup::"+ doneexit "$rc"diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex cb12af3fa84..a84136a363f 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -137,9 +137,11 @@ import {readIncompleteInfo,readTextThoughtSignature,claimAutoContinue,+ forgetAutoContinue,recordAutoContinue,shouldAutoContinueMessage,} from "@/features/chat/utils/continuation";+import { holdAutoContinueRun } from "@/features/chat/utils/auto-continue-run-keeper";import { McpComposerButton } from "@/features/chat/mcp-composer-button";import { getExternalReasoningCapabilities } from "@/features/chat/provider-capabilities";import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";@@ -6712,7 +6714,29 @@ const ContinueMessageBarForLastMessage: FC = () => {// 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.+ //+ // Another tab won the message. The claim resolves after this component has already+ // rendered off `shouldAutoContinueMessage`, which cannot see a race the lock decides,+ // so the answer has to come back as state: without it this tab keeps a spinner for a+ // run it never started, with the manual Continue button hidden behind it.+ //+ // Remembered as the message the answer was decided for, not as a bare flag: rows are+ // mounted by INDEX (`<MessageByIndexProvider key={index}>` in progressive-messages.tsx),+ // so selecting a different truncated branch at the same index re-renders THIS component+ // instead of remounting it. A boolean survived that and suppressed the automatic+ // continuation of a message no other tab had claimed, for as long as the row lived.+ // Comparing ids re-answers per message while still refusing the one that really lost.+ const [heldElsewhereFor, setHeldElsewhereFor] = useState<string | null>(null);+ const claimHeldElsewhere = heldElsewhereFor === messageId;+ // The runtime this bar belongs to, so its keeper renews and releases this claim and no+ // other pane's.+ // The thread this run will file itself under, which is what the lease belongs to and+ // what its lifetime is read from. `remoteId`, not `id`: it is the value assistant-ui+ // passes the adapter as `unstable_threadId` and the key the run appears under in+ // `runningByThreadId`, and an uninitialized thread has an `id` but no `remoteId`.+ const runThreadId = useAuiState(({ threadListItem }) => threadListItem.remoteId);const autoContinuing =+ !claimHeldElsewhere &&resumable &&shouldAutoContinueMessage(messageId, reason, parentId, {fits: truncation?.fits,@@ -6725,21 +6749,80 @@ const ContinueMessageBarForLastMessage: FC = () => {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]);+ let mounted = true;+ // Claimed in module scope, not a ref, and under a cross-tab lock. `<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.+ // A module claim survived both but not a second TAB, which has its own module scope+ // and its own empty claim; the lease behind this one is shared and settles that.+ void claimAutoContinue(messageId, runThreadId ?? "").then((claim) => {+ if (claim === "started") {+ // Is there still a message to resume? `aui.thread()` follows the SELECTION, not+ // the thread this bar belongs to, so a chat or branch switch inside the window the+ // Web Lock is pending leaves `startContinuation` looking at a different list, where+ // it finds nothing and issues no run at all.+ //+ // Asked BEFORE anything is held, because a hold whose run never appears is renewed+ // forever on purpose -- preflight has no upper bound, so no deadline can separate+ // "never coming" from "still on its way". A hold taken for a run that was never+ // issued therefore renews its lease for the life of the tab, and every other tab+ // reads that lease as live and refuses the message for just as long.+ //+ // Not the preflight case, and it cannot become it: this is `startRun` never having+ // been called, decided synchronously off the same store `startContinuation` reads a+ // line later in the same tick. A run that HAS been issued and is merely slow to+ // begin passes here and keeps its hold and its renewals.+ const stillThere = aui+ .thread()+ .getState()+ .messages.some((message) => message.id === messageId);+ if (!stillThere) {+ // Nothing held and nothing recorded, so the lease this claim took runs out its+ // own TTL -- the same thing a tab that closed mid-claim leaves behind -- and the+ // turn keeps the round no request was ever made for.+ //+ // The claim itself is given back, and only inside this tab: it is what makes+ // `claimAutoContinue` answer "skipped" for a message it has already continued,+ // and a message nothing was issued for has not been continued at all. Left in,+ // returning to this branch found the message skipped for the life of the tab.+ // The lease stays, so no second tab may start while this one is still deciding.+ forgetAutoContinue(messageId);+ return;+ }+ // Held for as long as THIS thread's run generates, wherever the user navigates+ // to meanwhile. The bar cannot hold it itself: the continuation's sibling becomes+ // the selected branch and unmounts this component almost at once.+ holdAutoContinueRun(messageId, runThreadId);+ // Started whether or not this component is still mounted: the run belongs to the+ // thread, not to the bar, and a claim taken and then dropped would leave the+ // message continued by nobody.+ //+ // Recorded BEFORE the run, so a round that produces nothing still spends its+ // budget instead of re-firing this effect forever.+ recordAutoContinue(parentId);+ startContinuation();+ return;+ }+ // `skipped` is this tab's own duplicate call, where the run is coming from the+ // other one and nothing on screen should move.+ if (claim === "held-elsewhere" && mounted) {+ setHeldElsewhereFor(messageId);+ }+ });+ return () => {+ mounted = false;+ };+ }, [+ aui,+ autoContinuing,+ parentId,+ messageId,+ startContinuation,+ runThreadId,+ ]);// 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.diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex b9b1c2c5c94..ed33ef6a97d 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -170,7 +170,10 @@ import {type LastLocalModelKind,} from "../utils/last-local-model-load";import { createRetryableSharedRead } from "../utils/retryable-shared-read";-import { getImageInputUnavailableReason } from "../utils/image-input-support";+import {+ createImageGateRunOwner,+ getImageInputUnavailableReason,+} from "../utils/image-input-support";import { mergeContextTruncation } from "../utils/context-truncation";import {createThinkTagTracker,@@ -4650,8 +4653,10 @@ export function createOpenAIStreamAdapter(// before the streaming path's setThreadRunning(true).const gatedThreadKey = resolvedThreadId || "__default";// Own token: siblings share "__default", so an ownerless clear would drop their- // entries while they are still generating.- const gateOwner = () => {};+ // entries while they are still generating. Marked as the gate's, so a reader that+ // means "this thread's run started" is not told one did by a pair of flags that+ // stand for a request nobody made.+ const gateOwner = createImageGateRunOwner();runtime.setThreadRunning(gatedThreadKey, true, { owner: gateOwner });runtime.setThreadRunning(gatedThreadKey, false, { owner: gateOwner });clearSelectedImageEditReference();diff --git a/studio/frontend/src/features/chat/utils/auto-continue-run-keeper.ts b/studio/frontend/src/features/chat/utils/auto-continue-run-keeper.tsnew file mode 100644index 00000000000..03413c9a440--- /dev/null+++ b/studio/frontend/src/features/chat/utils/auto-continue-run-keeper.ts@@ -0,0 +1,118 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Wires the automatic-continuation lease keeper to the runs actually in flight.+ *+ * The keeper itself is in `continuation.ts` and knows nothing about this app; all it asks+ * for is "is thread X generating right now", which `runningByThreadId` answers per thread+ * and regardless of what is on screen. The same store field is what the prompt queue uses+ * for completion detection, for the same reason: it "tracks the actual thread (not+ * aui.thread()), so detection survives navigation".+ */++import { useChatRuntimeStore } from "../stores/chat-runtime-store";+import {+ AUTO_CONTINUE_LEASE_RENEW_MS,+ createAutoContinueLeaseKeeper,+} from "./continuation";+import { isImageGateRunOnly } from "./image-input-support";+import {+ PROMPT_QUEUE_RUN_FAILED_EVENT,+ type PromptQueueRunFailedEventDetail,+} from "./prompt-queue-boundary";++const keeper = createAutoContinueLeaseKeeper({+ signal: {+ /**+ * Generating, and not the image gate settling its waiters.+ *+ * A continuation carrying an image that the loaded model cannot read -- a chat with a+ * picture in it, reopened on a truncated reply with a text-only model loaded, or with+ * Vision switched off since -- is refused before any request is made, and the gate+ * pulses this field true and then false so compare mode's `waitForRunEnd` resolves. To+ * a hold that is waiting for its own run to start, that pair reads as the run starting+ * and finishing: it arms on the first and is released on the second, with the `done`+ * marker that tells every other tab for a day that the message HAS been continued. The+ * failure that follows cannot undo it, because a released hold is gone. So the pulse is+ * not counted as a run, the hold never arms, and the failure discards it as it does any+ * other run that died before it started.+ *+ * Only when the gate is ALL that holds the flag. A real run sharing the key -- the+ * other compare pane, or a sibling under "__default" -- still answers yes.+ */+ isRunning: (threadId) => {+ const state = useChatRuntimeStore.getState();+ return (+ Boolean(state.runningByThreadId[threadId]) &&+ !isImageGateRunOnly(state.runOwnerByThreadId[threadId])+ );+ },+ subscribe: (onChange) => useChatRuntimeStore.subscribe(onChange),+ },+});++let timer: ReturnType<typeof setInterval> | null = null;++function tick(): void {+ keeper.tick();+ if (keeper.held() === 0 && timer !== null) {+ clearInterval(timer);+ timer = null;+ }+}++/**+ * A run that failed before it ever reached `runningByThreadId`.+ *+ * The adapter wrapper catches everything `adapter.run` throws -- this chat's settings+ * pairing running out, a model that will not load, a connection it refuses -- and announces+ * it per thread, which is the only signal that separates a preflight that FAILED from one+ * that is merely long. Nothing here reads a clock: a slow run emits no event and keeps its+ * hold and its renewals, which is what the absence of an arming deadline is for.+ */+function onRunFailed(event: Event): void {+ const threadId = (event as CustomEvent<PromptQueueRunFailedEventDetail>)+ .detail?.threadId;+ if (!threadId) {+ return;+ }+ keeper.failed(threadId);+ if (keeper.held() === 0 && timer !== null) {+ clearInterval(timer);+ timer = null;+ }+}++let listening = false;++/**+ * Hold `messageId`'s lease for as long as `threadId`'s own run is generating.+ *+ * Called by the continuation bar at the moment it starts a run, because that is the last+ * point at which anything knows both ids: the bar unmounts as soon as the continuation's+ * sibling becomes the selected branch, and the thread it ran on may not be the one on+ * screen a second later.+ *+ * `threadId` is the key the run files itself under, which is `threadListItem.remoteId` --+ * the same value assistant-ui passes the adapter as `unstable_threadId`. A thread with no+ * remote id yet (the first turn of a New Chat) files its run under a shared placeholder+ * that is not safe to watch, so nothing is held for it and its lease simply runs out its+ * TTL. That is the same outcome as a tab closing mid-run, and it is never an early release.+ */+export function holdAutoContinueRun(+ messageId: string,+ threadId: string | undefined,+): void {+ if (!threadId) {+ return;+ }+ keeper.hold(messageId, threadId);+ // Registered with the first hold rather than at import, so a module nobody continues in+ // adds no listener. Once, and never removed: it is one handler for the tab.+ if (!listening && typeof window !== "undefined") {+ listening = true;+ window.addEventListener(PROMPT_QUEUE_RUN_FAILED_EVENT, onRunFailed);+ }+ timer ??= setInterval(tick, AUTO_CONTINUE_LEASE_RENEW_MS);+}diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.tsindex b3029390a0f..0c954b4876a 100644--- a/studio/frontend/src/features/chat/utils/continuation.ts+++ b/studio/frontend/src/features/chat/utils/continuation.ts@@ -374,30 +374,744 @@ export function autoContinueCount(key: string | null | undefined): number {}/**- * 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.+ * How long a lease survives without being renewed.+ *+ * A lease, not a permanent flag: the tab that wins can be closed or crash mid-run, and a+ * flag it never gets to clear would leave the message unresumable for the life of the+ * profile. The winner renews for as long as its run is live (see+ * `renewAutoContinueLease`), so the TTL is not a guess at how long a continuation takes:+ * it is how long a tab that stopped renewing is still believed to be alive.+ *+ * Three minutes because renewals are timers, and a hidden tab is throttled to roughly one+ * timer callback a minute in Chrome. Three minutes leaves a backgrounded winner about+ * three chances to check in before anyone else may touch its message, while a tab that+ * really died gives the message back inside the pause a user notices anyway. The manual+ * Continue button is never gated on any of this, so the way out is always open.*/-const continued = new Set<string>();+export const AUTO_CONTINUE_LEASE_TTL_MS = 180_000;-/** 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;+/**+ * How often the holder renews while its run is live. Well inside the TTL even at the+ * once-a-minute rate a hidden tab's timers are throttled to.+ */+export const AUTO_CONTINUE_LEASE_RENEW_MS = 30_000;++/**+ * How long a record stays behind once the run it covered has finished.+ *+ * A lease answers "is somebody running this message"; this answers "has this message+ * already been continued", which is what the per-tab claim set answers inside the tab that+ * won and what no other tab has any way of learning. Nothing tells a second tab that the+ * sibling was written: `notifyChatHistoryUpdated` dispatches a same-window event, no chat+ * key has a `storage` listener, and persisted messages are re-read only by `history.load`+ * when a thread is opened. So a tab still holding the pre-continuation branch in memory+ * takes the message straight back the moment the record goes -- on the next remount of the+ * bar, which leaving the chat and returning is enough to produce -- and the user pays for a+ * second continuation from a history that is missing the first.+ *+ * Long enough to outlive the sitting the continuation happened in, not permanent: the ids+ * are pruned like any other record, so the key cannot grow without bound.+ */+export const AUTO_CONTINUE_CONTINUED_TTL_MS = 86_400_000;++/** The `localStorage` key holding the leases, one record per claimed message id. */+export const AUTO_CONTINUE_LEASE_KEY = "unsloth_chat_auto_continue_leases";++/** The Web Locks name every read-modify-write of that key is taken under. */+export const AUTO_CONTINUE_LOCK_NAME = "unsloth_chat_auto_continue_claim";++/**+ * What a claim attempt did.+ *+ * Three answers, not a boolean, because the two ways of not starting a run want opposite+ * things on screen. `held-elsewhere` is another tab running this message: this one has to+ * drop the "Continuing automatically" spinner and put its manual Continue button back, or+ * it shows a spinner for a run it will never own. `skipped` is this tab declining its own+ * duplicate call -- a `<StrictMode>` replay, or a claim already in flight -- where the run+ * IS coming and changing what is on screen would be wrong.+ */+export type AutoContinueClaim = "started" | "skipped" | "held-elsewhere";++/** The slice of `Storage` the lease needs. Narrow so a test can hand over a fake. */+export type AutoContinueLeaseStorage = {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+ removeItem(key: string): void;+};++/** The slice of `navigator.locks` the claim needs: an exclusive request by name. */+export type AutoContinueLockManager = {+ request<T>(name: string, callback: () => T | Promise<T>): Promise<T>;+};++type Lease = {+ token: string;+ expires: number;+ /**+ * The run this record covered reached a terminal state, so the message HAS been+ * continued. A plain lease that lapses means only that its holder stopped answering and+ * the message is free again; this one means the work is done and nobody should repeat it.+ */+ done?: boolean;+};++/**+ * The browser's own storage, or nothing when there is not one to read.+ *+ * Resolved per call rather than once at import: `localStorage` is absent under the test+ * runner and in SSR, and Safari's private mode throws on the property itself, not just on+ * a write. Every caller treats null as "no cross-tab seam" and falls back to the module+ * claim below, which is exactly what shipped before the lease existed.+ */+function browserLeaseStorage(): AutoContinueLeaseStorage | null {+ try {+ if (typeof window === "undefined") {+ return null;+ }+ return (+ (window.localStorage as AutoContinueLeaseStorage | undefined) ?? null+ );+ } catch {+ return null;}- continued.add(messageId);- return true;}-/** Whether `messageId` was already continued automatically this session. */+/**+ * The browser's lock manager, or nothing where there is not one.+ *+ * `navigator.locks` is what makes the claim exclusive: read, decide and write happen+ * inside one held lock, so no other tab can be between them. localStorage alone cannot do+ * this -- its individual operations are atomic, but a read-modify-write across three+ * statements is not, and the storage mutex that used to serialize such sequences was+ * dropped from the spec, so nothing holds a lock across them.+ */+function browserLockManager(): AutoContinueLockManager | null {+ try {+ const locks = (globalThis.navigator as { locks?: unknown } | undefined)+ ?.locks as AutoContinueLockManager | undefined;+ return typeof locks?.request === "function" ? locks : null;+ } catch {+ return null;+ }+}++function readLeases(storage: AutoContinueLeaseStorage): Record<string, Lease> {+ const raw = storage.getItem(AUTO_CONTINUE_LEASE_KEY);+ if (!raw) {+ return {};+ }+ const parsed = JSON.parse(raw) as unknown;+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {+ return {};+ }+ const out: Record<string, Lease> = {};+ for (const [id, value] of Object.entries(parsed as Record<string, unknown>)) {+ const token = (value as Lease | undefined)?.token;+ const expires = (value as Lease | undefined)?.expires;+ if (typeof token === "string" && typeof expires === "number") {+ out[id] = (value as Lease).done === true+ ? { token, expires, done: true }+ : { token, expires };+ }+ }+ return out;+}++function newLeaseToken(): string {+ const uuid = (globalThis.crypto as Crypto | undefined)?.randomUUID;+ if (typeof uuid === "function") {+ return uuid.call(globalThis.crypto);+ }+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;+}++/**+ * One tab's view of which messages have been continued.+ *+ * Constructible because a second instance is precisely what a second browser tab is: its+ * own module scope, its own empty claim set, the same saved thread, and the same storage+ * and lock manager underneath. That is the case the lease exists for, and the only way to+ * write it down as a test.+ */+export function createAutoContinueTab({+ storage,+ locks,+}: {+ /** Omit for the browser's `localStorage`; pass null for a tab with no seam. */+ storage?: AutoContinueLeaseStorage | null;+ /** Omit for `navigator.locks`; pass null for a browser that has none. */+ locks?: AutoContinueLockManager | null;+} = {}): {+ claim: (+ messageId: string | null | undefined,+ options?: { now?: number; holder?: string },+ ) => Promise<AutoContinueClaim>;+ claimed: (+ messageId: string | null | undefined,+ options?: { now?: number },+ ) => boolean;+ renew: (+ messageId: string | null | undefined,+ holder: string,+ options?: { now?: number },+ ) => Promise<void>;+ release: (+ messageId: string | null | undefined,+ holder: string,+ options?: { now?: number },+ ) => Promise<void>;+ forget: (messageId: string | null | undefined) => void;+ reset: () => void;+} {+ /**+ * Messages this tab 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>();++ /** Claims this tab has in flight. The lock is async, so a second call can arrive. */+ const claiming = new Set<string>();++ /**+ * Lease tokens this tab holds, by message id, each tagged with the holder that took it.+ *+ * Tagged, because "this tab" is not one runtime. Compare mode mounts two of them side by+ * side, each with its own thread and its own run, and either can be resuming a truncated+ * reply while the other is idle. A holder renews and releases what IT took; the pane that+ * finishes first must not hand the other pane's still-generating message to anyone.+ */+ const ownTokens = new Map<string, { token: string; holder: string }>();++ const leaseSeam = (): AutoContinueLeaseStorage | null =>+ storage === undefined ? browserLeaseStorage() : storage;++ const lockSeam = (): AutoContinueLockManager | null =>+ locks === undefined ? browserLockManager() : locks;++ /**+ * Run `mutate` with nobody else inside it.+ *+ * With a lock manager this is genuinely exclusive across tabs. Without one -- an older+ * browser, an embedded webview, the test runner -- it degrades to running the body+ * straight through, which is the write-then-read-back below and no worse than what+ * shipped before. A lock manager that rejects the request is treated the same way,+ * and a body that has already run is never run twice.+ */+ async function exclusively<T>(mutate: () => T, fallback: T): Promise<T> {+ const manager = lockSeam();+ if (!manager) {+ return mutate();+ }+ let ran = false;+ try {+ return await manager.request(AUTO_CONTINUE_LOCK_NAME, () => {+ ran = true;+ return mutate();+ });+ } catch {+ return ran ? fallback : mutate();+ }+ }++ /**+ * Drop what has lapsed, so the key cannot grow with every truncated reply.+ *+ * The one mutation here that is deliberately not per message. It only ever removes+ * records that are already dead by their own expiry -- `liveLease` reads them as free+ * whether they are in the key or not -- so it cannot end anybody's hold, and it is the+ * only thing bounding the size of a key every tab writes to.+ */+ function prune(+ leases: Record<string, Lease>,+ now: number,+ ): Record<string, Lease> {+ const out: Record<string, Lease> = {};+ for (const [id, lease] of Object.entries(leases)) {+ if (lease.expires > now) {+ out[id] = lease;+ }+ }+ return out;+ }++ /** A lease held by ANY tab, this one included, or null. Expired reads as free. */+ function liveLease(messageId: string, now: number): Lease | null {+ const store = leaseSeam();+ if (!store) {+ return null;+ }+ try {+ const lease = readLeases(store)[messageId];+ return lease && lease.expires > now ? lease : null;+ } catch {+ // Unreadable storage is no worse than no storage: fall back to module scope.+ return null;+ }+ }++ /**+ * Take the lease, or report who has it. Runs inside the lock.+ *+ * A storage that cannot be read or written is not an error: the tab keeps the+ * module-only claim, which is what single-tab use has always relied on, rather than+ * refusing a continuation the user is waiting for.+ */+ function takeLease(+ messageId: string,+ now: number,+ holder: string,+ ): AutoContinueClaim {+ const store = leaseSeam();+ if (!store) {+ return "started";+ }+ let leases: Record<string, Lease>;+ try {+ leases = readLeases(store);+ } catch {+ return "started";+ }+ const held = leases[messageId];+ if (+ held &&+ held.expires > now &&+ held.token !== ownTokens.get(messageId)?.token+ ) {+ return "held-elsewhere";+ }+ const token = newLeaseToken();+ const next = prune(leases, now);+ next[messageId] = { token, expires: now + AUTO_CONTINUE_LEASE_TTL_MS };+ try {+ store.setItem(AUTO_CONTINUE_LEASE_KEY, JSON.stringify(next));+ // Read back, which is the only defence left when there is no lock manager: whoever+ // wrote last is the token in storage, and the other tab does not find its own.+ if (readLeases(store)[messageId]?.token !== token) {+ return "held-elsewhere";+ }+ } catch {+ return "started";+ }+ ownTokens.set(messageId, { token, holder });+ return "started";+ }++ /** Whether `holder` is the one this tab took `messageId`'s lease for. */+ function heldFor(messageId: string, holder: string): boolean {+ return ownTokens.get(messageId)?.holder === holder;+ }++ /**+ * Rewrite ONE lease with a new expiry, if this holder is the one that took it. Runs+ * inside the lock, and reports whether the lease is still this tab's to stamp.+ *+ * One message, never a holder's whole set. A holder is a runtime, and a runtime outlives+ * the run inside it: rounds of the same turn are claimed one after another under the same+ * holder, and the next round is claimed BEFORE the finished one is given back, because+ * React runs the bar's effect before the thread's. Anything that operated on "every lease+ * this holder owns" would settle the round that just started along with the round that+ * ended.+ */+ function restamp(+ messageId: string,+ holder: string,+ expires: number,+ now: number,+ done = false,+ ): boolean {+ const held = ownTokens.get(messageId);+ if (!held || held.holder !== holder) {+ return false;+ }+ const store = leaseSeam();+ if (!store) {+ return false;+ }+ try {+ const leases = prune(readLeases(store), now);+ if (leases[messageId]?.token !== held.token) {+ // Lapsed, or taken over while this tab was not looking. Not ours to stamp.+ ownTokens.delete(messageId);+ return false;+ }+ leases[messageId] = done+ ? { token: held.token, expires, done: true }+ : { token: held.token, expires };+ store.setItem(AUTO_CONTINUE_LEASE_KEY, JSON.stringify(leases));+ return true;+ } catch {+ // An unwritable seam holds no lease of ours to renew or release either.+ return false;+ }+ }++ return {+ async claim(messageId, { now = Date.now(), holder = "" } = {}) {+ if (!messageId || continued.has(messageId) || claiming.has(messageId)) {+ return "skipped";+ }+ if (liveLease(messageId, now)) {+ // Cheap answer before touching the lock. Not recorded locally: if the tab holding+ // it dies, this one takes the message back when the lease lapses.+ return "held-elsewhere";+ }+ claiming.add(messageId);+ try {+ const outcome = await exclusively(+ () => takeLease(messageId, now, holder),+ "held-elsewhere" as AutoContinueClaim,+ );+ if (outcome === "started") {+ continued.add(messageId);+ }+ return outcome;+ } finally {+ claiming.delete(messageId);+ }+ },+ claimed(messageId, { now = Date.now() } = {}) {+ if (!messageId) {+ return false;+ }+ // A claim of this tab's own that is still in flight deliberately does NOT count: the+ // spinner it is rendering is the right thing to show, and treating it as taken would+ // flash the manual bar in the middle of winning. Its duplicate calls are refused by+ // `claim` itself.+ return continued.has(messageId) || Boolean(liveLease(messageId, now));+ },+ async renew(messageId, holder, { now = Date.now() } = {}) {+ if (!messageId) {+ return;+ }+ if (!heldFor(messageId, holder)) {+ return;+ }+ await exclusively(+ () => restamp(messageId, holder, now + AUTO_CONTINUE_LEASE_TTL_MS, now),+ false,+ );+ },+ async release(messageId, holder, { now = Date.now() } = {}) {+ if (!messageId) {+ return;+ }+ if (!heldFor(messageId, holder)) {+ return;+ }+ await exclusively(+ () =>+ restamp(+ messageId,+ holder,+ now + AUTO_CONTINUE_CONTINUED_TTL_MS,+ now,+ true,+ ),+ false,+ );+ // Held no longer, and marked done rather than handed back: the message HAS been+ // continued now, and the only thing that could hand it to another tab is a lease that+ // lapses, which is reserved for a holder that stopped answering. Only this message, so+ // the next round of the same turn -- claimed under this same holder before this+ // release lands -- keeps its own lease and its own renewals.+ ownTokens.delete(messageId);+ },+ /**+ * Take back a claim whose run was never issued.+ *+ * Only this tab's own record of having continued the message. The storage lease is left+ * exactly where it is, to run out its own TTL: that is what a tab closed mid-claim+ * already leaves behind, and dropping it here would hand the message to a second tab+ * while this one may still be deciding what to do with it.+ *+ * Without this the message stays in `continued` for the life of the tab, and every+ * later claim of it -- the branch picker back to the truncated sibling, or returning to+ * the chat -- answers "skipped", so the automatic continuation never runs again for a+ * request that was never made.+ */+ forget(messageId) {+ if (!messageId) {+ return;+ }+ continued.delete(messageId);+ },+ reset() {+ continued.clear();+ claiming.clear();+ const store = leaseSeam();+ if (!store || ownTokens.size === 0) {+ ownTokens.clear();+ return;+ }+ // Synchronous, and so outside the lock: a reset is a test seam and a new thread+ // starting from zero, neither of which races another tab for this key.+ try {+ const leases = readLeases(store);+ for (const [id, held] of ownTokens) {+ if (leases[id]?.token === held.token) {+ delete leases[id];+ }+ }+ store.setItem(AUTO_CONTINUE_LEASE_KEY, JSON.stringify(leases));+ } catch {+ // Nothing to undo: an unwritable seam held no lease of ours either.+ }+ ownTokens.clear();+ },+ };+}++/** This tab. */+const tab = createAutoContinueTab();++/**+ * Claim `messageId` for an automatic continuation, and say what happened.+ *+ * Asynchronous because exclusivity is: the read-decide-write is taken under a Web Lock so+ * that two tabs cannot both come out of it believing they won. The caller starts its run+ * on `started` and only on `started`.+ */+export function claimAutoContinue(+ messageId: string | null | undefined,+ holder: string,+): Promise<AutoContinueClaim> {+ return tab.claim(messageId, { holder });+}++/**+ * Whether `messageId` is already being continued automatically -- by this tab, or by+ * another one whose lease is still live.+ *+ * Asked at render time, so the answer has to match what `claimAutoContinue` will do a tick+ * later as closely as a synchronous read can. It cannot be exact, because the lock that+ * decides a genuine race resolves later; the caller therefore also re-renders off the+ * claim's own answer rather than trusting this alone.+ */export function wasAutoContinued(messageId: string | null | undefined): boolean {- return Boolean(messageId && continued.has(messageId));+ return tab.claimed(messageId);+}++/**+ * Give a claim back when the run it was taken for turned out never to be issued.+ *+ * The claim is what stops this tab continuing the same message twice, so it is only ever+ * dropped where nothing was started: the caller checked, in the same tick and off the same+ * store it starts the run from, that the message it claimed is no longer there to resume.+ * The cross-tab lease is deliberately untouched and lapses on its own.+ */+export function forgetAutoContinue(messageId: string | null | undefined): void {+ tab.forget(messageId);+}++/**+ * Keep ONE message's lease alive while the run resuming it is still going.+ *+ * Called on a timer for as long as that runtime's thread is running. Without it the TTL+ * would have to guess the longest continuation anyone might generate, and a slow local+ * model on a big Max Tokens would outlive that guess and have its message taken by another+ * tab mid-stream.+ *+ * Named by message and by holder, not by holder alone. The holder keeps two panes of+ * compare mode apart; the message id is what keeps one round of a turn apart from the next,+ * which the same holder claims moments later.+ */+export function renewAutoContinueLease(+ messageId: string,+ holder: string,+): Promise<void> {+ return tab.renew(messageId, holder);+}++/**+ * Give ONE message's lease back when the run resuming it reaches a terminal state,+ * cancelled included.+ *+ * It is cut to the settle window rather than deleted, so a tab still showing the+ * pre-continuation branch cannot immediately start the duplicate this file exists to+ * prevent, and the full TTL is left to mean one thing only: the holder stopped answering.+ *+ * By message, because a holder can own two at once and they are not in the same state. A+ * turn that hits Max Tokens again is claimed by the bar's effect before this thread's+ * effect observes the first run ending, so a holder-wide release settles a round that has+ * only just begun, and one settle window later another tab takes it.+ */+export function releaseAutoContinueLease(+ messageId: string,+ holder: string,+): Promise<void> {+ return tab.release(messageId, holder);+}++/**+ * Whether the thread a lease was taken for is generating right now.+ *+ * Deliberately NOT "is the thread on screen running". A run keeps streaming when the user+ * opens another chat -- the chat view is keyed by project so the provider is not remounted,+ * and the runtime just points its selection somewhere else -- so a lease whose lifetime is+ * read off the selected thread is released the moment the user looks away, and one settle+ * window later another tab can claim a message that is still being written. The signal has+ * to be per thread and indifferent to selection.+ */+export type AutoContinueRunSignal = {+ isRunning(threadId: string): boolean;+ subscribe(onChange: () => void): () => void;+};++/**+ * Holds the lease of each continuation this tab is running, for as long as its own run runs.+ *+ * A hold is (message, thread) and its lifetime is the run's: it arms when THAT thread starts+ * generating and is given back when THAT thread stops, whatever is on screen meanwhile and+ * whichever component has mounted or unmounted. Nothing here reads React state.+ *+ * Arming waits for a run that starts after the hold is taken. A round that hits Max Tokens+ * again is claimed while the finished round is still winding down, so a hold that armed on+ * "the thread is running" would arm on its predecessor's run and be released when THAT one+ * ended, mid-stream. So a hold taken while the thread is busy waits to see it idle first.+ *+ * A hold whose run has not appeared YET is kept and renewed, never timed out. No deadline+ * separates "this run is never coming" from "this run is still in preflight", because the+ * preflight has no bound: `chat-adapter.ts` awaits the thread's own settings pairing (up to+ * 30 seconds by itself), then `waitForModelReady`, which polls every 500ms for as long as a+ * model is loading -- minutes for a large local GGUF, and exactly the state a tab just+ * opened on a truncated reply is in. A fixed arming timeout dropped the hold in the middle+ * of that, its renewals stopped, and the lease lapsed under a run that had since started+ * streaming, so another tab could claim the message and pay for the same continuation twice.+ * Renewing instead costs only this: a claim whose run genuinely never starts holds its lease+ * until the tab is closed, and the manual Continue button is never gated on any of it.+ */+export function createAutoContinueLeaseKeeper({+ signal,+ renew = (messageId, holder, now) => tab.renew(messageId, holder, { now }),+ release = (messageId, holder, now) => tab.release(messageId, holder, { now }),+ now = Date.now,+}: {+ signal: AutoContinueRunSignal;+ renew?: (messageId: string, holder: string, now: number) => void;+ release?: (messageId: string, holder: string, now: number) => void;+ now?: () => number;+}): {+ hold: (messageId: string, threadId: string) => void;+ observe: () => void;+ failed: (threadId: string) => void;+ tick: () => void;+ held: () => number;+ stop: () => void;+} {+ type Hold = {+ messageId: string;+ threadId: string;+ /** Seen idle since the hold was taken, so the next run to start is this hold's own. */+ idle: boolean;+ /** That run has started. Only an armed hold is ever released. */+ armed: boolean;+ };+ const holds = new Map<string, Hold>();+ let unsubscribe: (() => void) | null = null;++ const key = (messageId: string, threadId: string) =>+ `${threadId}\u0000${messageId}`;++ /** Arm, release, or forget. No writes to storage beyond the release itself. */+ function observe(): void {+ const at = now();+ for (const [id, hold] of [...holds]) {+ if (signal.isRunning(hold.threadId)) {+ // Only a run that started after this hold was taken can be its own.+ hold.armed ||= hold.idle;+ continue;+ }+ hold.idle = true;+ if (hold.armed) {+ // This hold's own run has ended: finished, cancelled or failed.+ holds.delete(id);+ release(hold.messageId, hold.threadId, at);+ continue;+ }+ // Not armed yet, so its run is still in preflight, which has no upper bound (see the+ // note above this function). Kept and renewed rather than timed out: dropping it here+ // stopped the renewals while the run was still on its way, and the lease then lapsed+ // under a live continuation.+ }+ if (holds.size === 0 && unsubscribe) {+ unsubscribe();+ unsubscribe = null;+ }+ }++ return {+ hold(messageId, threadId) {+ if (!messageId) {+ return;+ }+ if (!threadId) {+ return;+ }+ holds.set(key(messageId, threadId), {+ messageId,+ threadId,+ // Claimed while the thread is between runs, which is the ordinary case: the bar+ // only fires on a reply that has finished.+ idle: !signal.isRunning(threadId),+ armed: false,+ });+ unsubscribe ??= signal.subscribe(observe);+ },+ observe,+ /**+ * `threadId`'s run failed on its way out, before it ever reached the run signal.+ *+ * The one thing that can end a hold which never armed, and it is a fact rather than a+ * deadline: the adapter threw, so this run is not slow, it is over. Not a timeout by+ * another name -- a preflight that is merely long emits nothing here and keeps its hold+ * and its renewals, which is the whole reason arming has no deadline.+ *+ * Armed holds are left alone. Their run did reach the signal, so the thread going idle+ * is what settles them, with the `done` marker that says the message HAS been continued+ * -- which a run that never produced a token has no right to write. This one only+ * discards: the lease it stops renewing lapses on its own TTL and the message comes+ * back to whoever is still looking at it, rather than being renewed for the life of the+ * tab and refused to every other one.+ */+ failed(threadId) {+ if (!threadId) {+ return;+ }+ for (const [id, hold] of [...holds]) {+ if (hold.threadId === threadId && !hold.armed) {+ holds.delete(id);+ }+ }+ if (holds.size === 0 && unsubscribe) {+ unsubscribe();+ unsubscribe = null;+ }+ },+ tick() {+ observe();+ const at = now();+ for (const hold of holds.values()) {+ // Armed or still waiting for its run: either way this tab is alive and expects to+ // be running that message, which is the whole question the lease asks.+ renew(hold.messageId, hold.threadId, at);+ }+ },+ held() {+ return holds.size;+ },+ stop() {+ holds.clear();+ unsubscribe?.();+ unsubscribe = null;+ },+ };}/**@@ -427,11 +1141,22 @@ export function shouldAutoContinueMessage(return shouldAutoContinue(reason, key, options);}-/** Test seam; also lets a new thread start from zero. */+/**+ * Test seam; also lets a new thread start from zero.+ *+ * A full reset gives back the leases this tab wrote as well, so "start from zero" means+ * the same thing it did before the lease existed. Leases other tabs hold are left alone:+ * they are not this tab's to release, and a run they are driving is still going.+ *+ * Deliberately wholesale, unlike renewal and release, which are per holder. A run ending+ * is one runtime saying it is finished, and says nothing about the others; a reset is the+ * whole tab being told it has no claims at all, which is what a test between cases and a+ * cleared history both mean. Nothing in the run lifecycle calls it.+ */export function resetAutoContinue(key?: string): void {if (key === undefined) {spent.clear();- continued.clear();+ tab.reset();} else {spent.delete(key);}diff --git a/studio/frontend/src/features/chat/utils/image-input-support.ts b/studio/frontend/src/features/chat/utils/image-input-support.tsindex 7b75817de32..b4747a6033e 100644--- a/studio/frontend/src/features/chat/utils/image-input-support.ts+++ b/studio/frontend/src/features/chat/utils/image-input-support.ts@@ -104,3 +104,44 @@ export function getImageInputUnavailableReason({`${label} cannot accept images. Load a vision-capable model${suffix}`);}++/**+ * The owners of the running-flag pulse the gate fires when it refuses a turn.+ *+ * `chat-adapter.ts` flips `runningByThreadId` on and straight back off before it throws,+ * so compare mode's `waitForRunEnd` resolves instead of hanging on a run that never+ * reached the streaming path. It is a settlement for waiters, not a run: nothing was+ * requested, nothing was generated, and anything reading that field as "this thread's run+ * started, and then it ended" is reading a request that was never issued as a finished one.+ *+ * A WeakSet rather than a flag on the function, because the store types an owner as a bare+ * `() => void` and the identity is all either side needs. Fresh per pulse: siblings share+ * the "__default" key and `setThreadRunning` clears by owner, so two gates firing on one+ * key must not clear each other's entry.+ */+const imageGateRunOwners = new WeakSet<() => void>();++/** A run-owner token that marks its `setThreadRunning` pair as the gate's own pulse. */+export function createImageGateRunOwner(): () => void {+ const owner = () => {};+ imageGateRunOwners.add(owner);+ return owner;+}++/**+ * Whether everything holding this thread's running flag is a gate pulse.+ *+ * Asked by readers that mean "is this thread generating", so a real run sharing the key --+ * an unresolved sibling under "__default", or a gate firing on one pane while the other+ * streams -- still answers yes. An empty list is a run from before per-run tracking and is+ * taken at face value.+ */+export function isImageGateRunOnly(+ owners: readonly { owner: () => void }[] | undefined,+): boolean {+ return (+ owners !== undefined &&+ owners.length > 0 &&+ owners.every((entry) => imageGateRunOwners.has(entry.owner))+ );+}diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.tsindex 11d9bda6251..db8449dc918 100644--- a/studio/frontend/tests/chat-continuation.test.ts+++ b/studio/frontend/tests/chat-continuation.test.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";+import { readFileSync } from "node:fs";import test from "node:test";import { registerBundlerResolver } from "./helpers/kit.ts";@@ -9,8 +10,14 @@ import { registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();const {+ AUTO_CONTINUE_CONTINUED_TTL_MS,+ AUTO_CONTINUE_LEASE_KEY,+ AUTO_CONTINUE_LEASE_RENEW_MS,+ AUTO_CONTINUE_LEASE_TTL_MS,AUTO_CONTINUE_LIMIT,autoContinueCount,+ createAutoContinueLeaseKeeper,+ createAutoContinueTab,budgetImpliesTruncation,incompleteLabel,isContinuableContent,@@ -31,9 +38,19 @@ const {stripContinuationOverlap,} = await import("../src/features/chat/utils/continuation.ts");+const { createImageGateRunOwner, isImageGateRunOnly } = await import(+ "../src/features/chat/utils/image-input-support.ts"+);+const PARTIAL ="There are three steps to proofing dough properly. First, warm the bowl and";+/**+ * The runtime a claim belongs to. One Thread is one holder; compare mode has two, which is+ * what the two-pane test below stands up.+ */+const PANE = "pane-1";+test("a token-exact continuation is appended verbatim", () => {// A local model's prompt ended inside the partial turn, so the continuation opens// on the next word with nothing repeated.@@ -421,52 +438,52 @@ test("an unknown fit does not block resuming", () => {);});-test("a message is claimed for automatic continuation exactly once", () => {+test("a message is claimed for automatic continuation exactly once", async () => {resetAutoContinue();- assert.equal(claimAutoContinue("m1"), true);- assert.equal(claimAutoContinue("m1"), false);- assert.equal(claimAutoContinue("m1"), false);+ assert.equal(await claimAutoContinue("m1", PANE), "started");+ assert.equal(await claimAutoContinue("m1", PANE), "skipped");+ assert.equal(await claimAutoContinue("m1", PANE), "skipped");});-test("the claim survives a remount, which a component ref did not", () => {+test("the claim survives a remount, which a component ref did not", async () => {// 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(await claimAutoContinue("m1", PANE), "started");assert.equal(shouldAutoContinue("length", "parent-1"), true);- assert.equal(claimAutoContinue("m1"), false);+ assert.equal(await claimAutoContinue("m1", PANE), "skipped");});-test("claims are tracked per message", () => {+test("claims are tracked per message", async () => {resetAutoContinue();- assert.equal(claimAutoContinue("m1"), true);- assert.equal(claimAutoContinue("m2"), true);- assert.equal(claimAutoContinue("m1"), false);+ assert.equal(await claimAutoContinue("m1", PANE), "started");+ assert.equal(await claimAutoContinue("m2", PANE), "started");+ assert.equal(await claimAutoContinue("m1", PANE), "skipped");});-test("a missing message id is refused rather than claimed", () => {+test("a missing message id is refused rather than claimed", async () => {resetAutoContinue();- assert.equal(claimAutoContinue(null), false);- assert.equal(claimAutoContinue(undefined), false);- assert.equal(claimAutoContinue(""), false);+ assert.equal(await claimAutoContinue(null, PANE), "skipped");+ assert.equal(await claimAutoContinue(undefined, PANE), "skipped");+ assert.equal(await claimAutoContinue("", PANE), "skipped");});-test("a claim is reported and cleared by a full reset", () => {+test("a claim is reported and cleared by a full reset", async () => {resetAutoContinue();assert.equal(wasAutoContinued("m1"), false);- claimAutoContinue("m1");+ await claimAutoContinue("m1", PANE);assert.equal(wasAutoContinued("m1"), true);resetAutoContinue();assert.equal(wasAutoContinued("m1"), false);- assert.equal(claimAutoContinue("m1"), true);+ assert.equal(await claimAutoContinue("m1", PANE), "started");});-test("a message already claimed stops reporting itself as continuing", () => {+test("a message already claimed stops reporting itself as continuing", async () => {resetAutoContinue();// The turn that fires it: nothing has claimed the message yet.assert.equal(shouldAutoContinueMessage("m1", "length", "parent-1"), true);- claimAutoContinue("m1");+ await claimAutoContinue("m1", PANE);recordAutoContinue("parent-1");// Back on the truncated branch, whether through the branch picker or by returning to@@ -476,9 +493,9 @@ test("a message already claimed stops reporting itself as continuing", () => {assert.equal(shouldAutoContinueMessage("m1", "length", "parent-1"), false);});-test("a claim on one message does not silence another", () => {+test("a claim on one message does not silence another", async () => {resetAutoContinue();- claimAutoContinue("m1");+ await claimAutoContinue("m1", PANE);// 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);@@ -493,3 +510,1411 @@ test("a claimed message still honours the gates the turn itself fails", () => {false,);});++// --- cross-tab claim ------------------------------------------------------------------+// The module claim above is per TAB: each one loads its own copy of the module with its+// own empty set. Open the same saved thread twice with a `length` reply last and both+// tabs claim it, both start a run, and the user pays for two continuations and gets two+// sibling branches. A tab here is a second `createAutoContinueTab` over one shared store+// and one shared lock manager, which is what two browser tabs are.++/**+ * An in-memory `localStorage`.+ *+ * `onSet` runs after a write and `onGet` after a read has taken its value, which is where+ * another tab is interleaved: both hooks land in the middle of a read-modify-write, which+ * is the sequence localStorage does not make atomic.+ */+function storageFake(+ onSet?: (store: Map<string, string>) => void,+ onGet?: (store: Map<string, string>) => void,+) {+ const store = new Map<string, string>();+ return {+ store,+ storage: {+ getItem: (key: string) => {+ const value = store.get(key) ?? null;+ // After the value is taken, so the caller carries on with the snapshot it read+ // and whatever the other tab does next is invisible to it. That staleness is the+ // whole bug.+ onGet?.(store);+ return value;+ },+ setItem: (key: string, value: string) => {+ store.set(key, value);+ onSet?.(store);+ },+ removeItem: (key: string) => {+ store.delete(key);+ },+ },+ };+}++/** A win, in the pre-fix boolean shape as well as the current one. */+function startedARun(outcome: unknown): boolean {+ return outcome === "started" || outcome === true;+}++/**+ * A `navigator.locks` stand-in: one queue per name, exclusive, FIFO.+ *+ * The property the real API gives and a bare read-modify-write does not: a second request+ * for a held name does not run until the first has returned.+ */+function lockManagerFake() {+ const tails = new Map<string, Promise<unknown>>();+ return {+ request<T>(name: string, callback: () => T | Promise<T>): Promise<T> {+ const tail = tails.get(name) ?? Promise.resolve();+ const run = tail.then(() => callback());+ // The queue advances on settle, so one throwing holder cannot wedge the name.+ tails.set(+ name,+ run.then(+ () => undefined,+ () => undefined,+ ),+ );+ return run;+ },+ };+}++test("a second tab with the same thread open does not start its own continuation", async () => {+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const first = createAutoContinueTab({ storage, locks });+ const second = createAutoContinueTab({ storage, locks });+ const now = 1_000;++ assert.equal(await first.claim("m1", { now }), "started");+ // Fresh module scope, empty claim set, same truncated reply on screen. Before the lease+ // this said yes and the second tab fired a second paid request.+ assert.equal(await second.claim("m1", { now }), "held-elsewhere");+ // And it reports the message as being continued, so it shows no spinner of its own.+ assert.equal(second.claimed("m1", { now }), true);+});++test("a lease covers only the message it was taken for", async () => {+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const first = createAutoContinueTab({ storage, locks });+ const second = createAutoContinueTab({ storage, locks });+ const now = 1_000;++ assert.equal(await first.claim("m1", { now }), "started");+ // The next round of the same turn is a different message and is nobody's yet.+ assert.equal(await second.claim("m2", { now }), "started");+});++test("two tabs claiming at once leave exactly one winner", async () => {+ // ITEM A. Write-then-read-back is not a compare-and-swap: both tabs read the slot free,+ // both write, and each verifies the token it just wrote if the two verifications happen+ // before the two writes interleave -- so both start a run. Individual localStorage+ // operations are atomic; a read-modify-write across statements is not, and the storage+ // mutex that once serialized such sequences is no longer in the spec.+ //+ // Started together, with no await between them, which is what two tabs reaching the+ // effect in the same instant are. The lock is what makes the second one wait for the+ // first, see the lease it wrote, and stand down.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const first = createAutoContinueTab({ storage, locks });+ const second = createAutoContinueTab({ storage, locks });+ const now = 1_000;++ const outcomes = await Promise.all([+ first.claim("m1", { now }),+ second.claim("m1", { now }),+ ]);+ assert.equal(outcomes.filter(startedARun).length, 1);+ assert.equal(+ outcomes.filter((outcome) => outcome === "held-elsewhere").length,+ 1,+ );+});++test("a tab that reads the slot free does not win it behind another tab's back", async () => {+ // ITEM A, at the exact interleaving that survives a write-then-read-back: the second+ // tab claims in full between the first tab READING the slot free and writing to it. The+ // first tab then writes over a lease it never saw and reads its own token back, so both+ // tabs believe they won and the user pays twice. Nothing about the sequence is atomic;+ // only holding a lock across it is.+ const now = 1_000;+ let intruder: (() => unknown) | null = null;+ let secondOutcome: unknown;+ let reads = 0;+ const { storage } = storageFake(undefined, () => {+ reads += 1;+ // The second read is the one the write is about to be based on: a free check, then+ // the read-modify-write itself. Slipping the other tab in there is what leaves the+ // first tab holding a snapshot that is already out of date.+ if (reads !== 2) {+ return;+ }+ const run = intruder;+ intruder = null;+ if (run) {+ secondOutcome = run();+ }+ });+ const locks = lockManagerFake();+ const first = createAutoContinueTab({ storage, locks });+ const second = createAutoContinueTab({ storage, locks });++ intruder = () => second.claim("m1", { now });+ const outcomes = [await first.claim("m1", { now }), await secondOutcome];+ assert.equal(+ outcomes.filter(startedARun).length,+ 1,+ "exactly one tab may start the run",+ );+});++test("a claim that loses says so, rather than just failing", async () => {+ // ITEM B. The two ways of not starting a run need opposite things on screen, so they+ // cannot both be a bare false. `held-elsewhere` is the loser, and is what puts this+ // tab's manual Continue button back in place of a spinner for a run it never owned.+ // `skipped` is this tab's own second call -- a StrictMode replay, or a claim already in+ // flight -- where the run is coming and nothing should move.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const winner = createAutoContinueTab({ storage, locks });+ const loser = createAutoContinueTab({ storage, locks });+ const now = 1_000;++ assert.equal(startedARun(await winner.claim("m1", { now })), true);+ const lost = await loser.claim("m1", { now });+ // The winner's own replay is not a loss and must not repaint anything, so the two+ // cannot be the same answer. One bare false for both is what left the losing tab+ // spinning: its effect returned early, changed no state, and hid its own button.+ const replay = await winner.claim("m1", { now });+ assert.notEqual(lost, replay);+ assert.equal(lost, "held-elsewhere");+ assert.equal(replay, "skipped");+ // Nor is a second call while the first is still inside the lock.+ const inFlight = winner.claim("m2", { now });+ assert.equal(await winner.claim("m2", { now }), "skipped");+ assert.equal(await inFlight, "started");+});++test("two tabs writing in the same tick leave exactly one winner", async () => {+ // The same race with no lock manager to settle it, which is what an older browser or an+ // embedded webview gets. The write-then-read-back is all that is left: a record that+ // appears between this tab's write and its read-back means the tab does not find its+ // own token, and stands down.+ const now = 1_000;+ let interleave = true;+ const { storage } = storageFake((store) => {+ if (!interleave) {+ return;+ }+ interleave = false;+ store.set(+ AUTO_CONTINUE_LEASE_KEY,+ JSON.stringify({+ m1: { token: "other-tab", expires: now + AUTO_CONTINUE_LEASE_TTL_MS },+ }),+ );+ });+ const first = createAutoContinueTab({ storage, locks: null });++ assert.equal(await first.claim("m1", { now }), "held-elsewhere");+ // Nothing recorded locally either, so once that lease lapses this tab can take over.+ assert.equal(+ await first.claim("m1", { now: now + AUTO_CONTINUE_LEASE_TTL_MS + 1 }),+ "started",+ );+});++test("a browser with no lock manager still continues", async () => {+ const { storage } = storageFake();+ const only = createAutoContinueTab({ storage, locks: null });+ assert.equal(await only.claim("m1"), "started");+ assert.equal(await only.claim("m1"), "skipped");+});++test("a lock manager that refuses the request does not block the claim", async () => {+ const { storage } = storageFake();+ const angryLocks = {+ request<T>(): Promise<T> {+ return Promise.reject(new Error("NotSupportedError"));+ },+ };+ const tab = createAutoContinueTab({ storage, locks: angryLocks });+ // Degraded to the read-back, not to a refusal: the user is waiting for this run.+ assert.equal(await tab.claim("m1"), "started");+ assert.equal(+ await createAutoContinueTab({ storage }).claim("m1"),+ "held-elsewhere",+ );+});++test("a tab with no storage keeps the claim it always had", async () => {+ // Private mode, an embedded webview, or the test runner: no seam to share. Falling back+ // to module scope is what shipped before the lease, and it must never refuse a+ // continuation the single tab in front of the user is waiting for.+ const only = createAutoContinueTab({ storage: null });+ assert.equal(await only.claim("m1"), "started");+ assert.equal(await only.claim("m1"), "skipped");+ assert.equal(only.claimed("m1"), true);+});++test("storage that throws is no worse than no storage", async () => {+ // A quota-exceeded write, or a getItem that throws before it returns anything.+ const angry = {+ getItem(): string | null {+ throw new Error("SecurityError");+ },+ setItem(): void {+ throw new Error("QuotaExceededError");+ },+ removeItem(): void {+ throw new Error("SecurityError");+ },+ };+ const tab = createAutoContinueTab({ storage: angry });+ assert.equal(await tab.claim("m1"), "started");+ assert.equal(await tab.claim("m1"), "skipped");+ // A second tab cannot see through a broken seam either, so it behaves as it did before+ // the lease: module-only. Duplicates are not made worse, and nothing crashes.+ assert.equal(+ await createAutoContinueTab({ storage: angry }).claim("m1"),+ "started",+ );+});++test("a lease lapses, so a tab that died mid-run does not wedge the message", async () => {+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const winner = createAutoContinueTab({ storage, locks });+ const later = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ assert.equal(await winner.claim("m1", { now: start }), "started");+ // Still inside the lease: the holder is presumed alive and nobody else touches it.+ assert.equal(+ await later.claim("m1", { now: start + AUTO_CONTINUE_LEASE_TTL_MS - 1 }),+ "held-elsewhere",+ );+ // Past it, with no renewal in between: a permanent flag would have left this message+ // unresumable for the life of the profile, because the tab that owned it is gone and+ // can never clear it.+ assert.equal(+ await later.claim("m1", { now: start + AUTO_CONTINUE_LEASE_TTL_MS + 1 }),+ "started",+ );+});++test("a running continuation keeps its lease past the TTL", async () => {+ // ITEM C. A local model on a large Max Tokens can generate for longer than the TTL, and+ // an unrenewed lease would hand its message to the next tab to open, mid-stream. The+ // holder renews for as long as its run is live, so the TTL only ever measures silence.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const running = createAutoContinueTab({ storage, locks });+ const other = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ assert.equal(+ startedARun(await running.claim("m1", { now: start, holder: PANE })),+ true,+ );+ // Three renewals at the interval the keeper uses, still inside the run.+ for (let tick = 1; tick <= 3; tick += 1) {+ await running.renew("m1", PANE, {+ now: start + tick * AUTO_CONTINUE_LEASE_RENEW_MS,+ });+ }+ const past =+ start + AUTO_CONTINUE_LEASE_TTL_MS + AUTO_CONTINUE_LEASE_RENEW_MS;+ assert.equal(await other.claim("m1", { now: past }), "held-elsewhere");+});++test("a finished run leaves the message continued, not free again", async () => {+ // Released on any terminal state, so the full TTL is left to mean one thing: a crash.+ // Marked done rather than handed back, because the tab that did not win never learns that+ // the sibling was written -- no chat-history event crosses tabs -- so a record that simply+ // lapsed handed the message to a stale tab and bought the same continuation twice.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const running = createAutoContinueTab({ storage, locks });+ const other = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ assert.equal(+ await running.claim("m1", { now: start, holder: PANE }),+ "started",+ );+ await running.release("m1", PANE, { now: start });+ assert.equal(+ await other.claim("m1", { now: start + AUTO_CONTINUE_LEASE_TTL_MS + 1 }),+ "held-elsewhere",+ );+ assert.equal(+ await other.claim("m1", {+ now: start + AUTO_CONTINUE_CONTINUED_TTL_MS - 1,+ }),+ "held-elsewhere",+ );+ // And a release holds nothing, so a later renewal cannot resurrect it as a live lease.+ await running.renew("m1", PANE, { now: start + AUTO_CONTINUE_LEASE_TTL_MS });+ assert.equal(+ await createAutoContinueTab({ storage, locks }).claim("m1", {+ now: start + AUTO_CONTINUE_LEASE_TTL_MS + 2,+ }),+ "held-elsewhere",+ );+ // Bounded, not permanent: the record is pruned like any other once it is old enough that+ // no tab can still be holding the pre-continuation branch in memory.+ assert.equal(+ await createAutoContinueTab({ storage, locks }).claim("m1", {+ now: start + AUTO_CONTINUE_CONTINUED_TTL_MS + 1,+ }),+ "started",+ );+});++test("a stale tab cannot take a message back once it has been continued", async () => {+ // The case the settle window left open. The second tab's render-time check refuses before+ // its effect ever runs, so it records nothing locally and holds no state saying it lost;+ // its `continued` set stays empty. Remount that bar -- leaving the chat and coming back is+ // enough, which is the same remount the module claim exists for -- and the only thing+ // between it and a second paid request is what storage remembers. Nothing refreshes its+ // in-memory history in the meantime: `notifyChatHistoryUpdated` dispatches a same-window+ // event, no chat key has a `storage` listener, and stored messages are re-read only by+ // `history.load`.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const winner = createAutoContinueTab({ storage, locks });+ const stale = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ assert.equal(await winner.claim("m1", { now: start, holder: PANE }), "started");+ // The stale tab renders the truncated reply while the winner is running: refused, and+ // nothing about that refusal is written down on its side.+ assert.equal(await stale.claim("m1", { now: start + 1 }), "held-elsewhere");+ // The winner finishes and writes the sibling. The stale tab still shows the partial.+ await winner.release("m1", PANE, { now: start + 60_000 });+ // Its bar remounts, long after any settle window would have passed.+ assert.equal(+ stale.claimed("m1", { now: start + 60_000 + AUTO_CONTINUE_LEASE_TTL_MS }),+ true,+ );+ assert.equal(+ await stale.claim("m1", {+ now: start + 60_000 + AUTO_CONTINUE_LEASE_TTL_MS,+ }),+ "held-elsewhere",+ );+});++test("a tab that died mid-run still hands the message back", async () => {+ // The other half of the same rule, and the reason a permanent flag is wrong: a record is+ // only marked done by a run that reached a terminal state. A tab killed without cleanup+ // renews nothing and marks nothing, so its lease lapses and the message is claimable+ // again. (Web Locks are released with the context too, so nothing is wedged there either.)+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const killed = createAutoContinueTab({ storage, locks });+ const survivor = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ assert.equal(await killed.claim("m1", { now: start, holder: PANE }), "started");+ // No release, no renewal: the tab is gone.+ assert.equal(+ await survivor.claim("m1", { now: start + AUTO_CONTINUE_LEASE_TTL_MS + 1 }),+ "started",+ );+});++/**+ * Two rounds of one turn, in the order the app produces them.+ *+ * A round ends on another Max Tokens cut, so the bar under the new reply claims the next+ * message while the thread is still winding the finished run down: React runs child+ * effects before parent ones, so the claim lands before the keeper observes `isRunning`+ * going false. `release` therefore has to name the message whose run ended, and nothing+ * wider: the same holder owns both.+ */+async function sequentialRounds(+ locks: ReturnType<typeof lockManagerFake> | null,+) {+ const { storage } = storageFake();+ const tab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ assert.equal(+ startedARun(await tab.claim("round-1", { now: start, holder: PANE })),+ true,+ );+ // The next round, claimed before the finished one is given back.+ assert.equal(+ startedARun(await tab.claim("round-2", { now: start, holder: PANE })),+ true,+ );+ await tab.release("round-1", PANE, { now: start });++ // The second round is the live one, and its keeper is still renewing it.+ for (let tick = 1; tick <= 3; tick += 1) {+ await tab.renew("round-2", PANE, {+ now: start + tick * AUTO_CONTINUE_LEASE_RENEW_MS,+ });+ }+ const past =+ start + AUTO_CONTINUE_LEASE_TTL_MS + AUTO_CONTINUE_LEASE_RENEW_MS;+ assert.equal(+ await otherTab.claim("round-2", { now: past }),+ "held-elsewhere",+ "the round that just started keeps its lease",+ );+ // The round that did finish is marked continued, and stays that way.+ assert.equal(+ await otherTab.claim("round-1", {+ now: start + AUTO_CONTINUE_LEASE_TTL_MS + 1,+ }),+ "held-elsewhere",+ );+}++test("the next round keeps its lease when the last one is released", async () => {+ // No lock manager, where the claim resolves soonest and so lands earliest.+ await sequentialRounds(null);+});++test("the next round keeps its lease with a lock manager in the way", async () => {+ // And with one, because the effect ordering is not guaranteed in our favour there+ // either -- the fix must not depend on which path ran.+ await sequentialRounds(lockManagerFake());+});++/**+ * The per-thread run signal the keeper reads, with no notion of what is on screen.+ *+ * Selection is deliberately absent: it is not an input to a lease's lifetime, and the whole+ * point of the case below is that changing it changes nothing.+ */+function runSignalFake(running: Set<string>) {+ const listeners = new Set<() => void>();+ return {+ signal: {+ isRunning: (threadId: string) => running.has(threadId),+ subscribe: (onChange: () => void) => {+ listeners.add(onChange);+ return () => listeners.delete(onChange);+ },+ },+ /** The store told everyone something changed. */+ change: () => {+ for (const listener of [...listeners]) {+ listener();+ }+ },+ };+}++test("a run on a background thread keeps its lease while the user reads another chat", async () => {+ // Switching chats does not stop a generation: the chat view is keyed by project, so the+ // provider is not remounted and the run keeps streaming on the thread the user left. A+ // lease whose lifetime was read off the SELECTED thread was released the moment they+ // looked away, and one settle window later a second tab could claim a message that was+ // still being written.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const start = 1_000;+ let clock = start;+ const pending: Promise<void>[] = [];++ // Thread A is generating; thread B, which the user is about to open, is idle.+ const running = new Set<string>();+ const runs = runSignalFake(running);+ const keeper = createAutoContinueLeaseKeeper({+ signal: runs.signal,+ renew: (messageId, holder, now) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: (messageId, holder, now) => {+ pending.push(tab.release(messageId, holder, { now }));+ },+ now: () => clock,+ });++ assert.equal(+ startedARun(await tab.claim("a-m1", { now: start, holder: "thread-A" })),+ true,+ );+ keeper.hold("a-m1", "thread-A");+ // The continuation starts on thread A.+ running.add("thread-A");+ runs.change();++ // The user opens idle thread B. Nothing about thread A changed, so nothing here does.+ for (let tick = 1; tick <= 5; tick += 1) {+ clock = start + tick * AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();+ }+ await Promise.all(pending);++ const past =+ start + AUTO_CONTINUE_LEASE_TTL_MS + AUTO_CONTINUE_LEASE_RENEW_MS;+ assert.equal(+ await otherTab.claim("a-m1", { now: past }),+ "held-elsewhere",+ "the background run keeps the message it is still writing",+ );++ // Thread A's own run ends. That, and only that, gives the lease back.+ clock = past;+ running.delete("thread-A");+ runs.change();+ await Promise.all(pending);+ assert.equal(+ await otherTab.claim("a-m1", {+ now: past + AUTO_CONTINUE_LEASE_TTL_MS + 1,+ }),+ "held-elsewhere",+ "the message was continued, so nobody continues it again",+ );+ assert.equal(keeper.held(), 0);+});++test("a hold waits for its own run, not the one already in flight", async () => {+ // The next round is claimed while the finished one is still winding down, so a hold that+ // armed on "the thread is busy" would arm on its predecessor's run and be released the+ // moment THAT one ended, mid-stream.+ const { storage } = storageFake();+ const tab = createAutoContinueTab({ storage, locks: null });+ const otherTab = createAutoContinueTab({ storage, locks: null });+ const start = 1_000;+ let clock = start;+ const pending: Promise<void>[] = [];+ const running = new Set<string>(["thread-A"]);+ const runs = runSignalFake(running);+ const keeper = createAutoContinueLeaseKeeper({+ signal: runs.signal,+ renew: (messageId, holder, now) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: (messageId, holder, now) => {+ pending.push(tab.release(messageId, holder, { now }));+ },+ now: () => clock,+ });++ await tab.claim("round-2", { now: start, holder: "thread-A" });+ keeper.hold("round-2", "thread-A");++ // The previous round ends, and the next one starts.+ running.delete("thread-A");+ runs.change();+ running.add("thread-A");+ runs.change();+ for (let tick = 1; tick <= 5; tick += 1) {+ clock = start + tick * AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();+ }+ await Promise.all(pending);+ const past =+ start + AUTO_CONTINUE_LEASE_TTL_MS + AUTO_CONTINUE_LEASE_RENEW_MS;+ assert.equal(await otherTab.claim("round-2", { now: past }), "held-elsewhere");+});++test("a hold keeps its lease while its run is still in preflight", async () => {+ // The adapter does a lot before the run reaches `runningByThreadId`: it awaits this+ // thread's own settings pairing, which alone waits up to 30 seconds, and then+ // `waitForModelReady`, which polls every 500ms for as long as a model is loading -- so a+ // tab opened on a truncated reply while a large local model loads can sit in preflight for+ // minutes. A hold dropped on a fixed arming timeout stopped renewing in the middle of+ // that, its lease lapsed, and another tab claimed a message that was about to stream.+ const { storage } = storageFake();+ const tab = createAutoContinueTab({ storage, locks: null });+ const otherTab = createAutoContinueTab({ storage, locks: null });+ const start = 1_000;+ let clock = start;+ const pending: Promise<void>[] = [];+ const running = new Set<string>();+ const runs = runSignalFake(running);+ const keeper = createAutoContinueLeaseKeeper({+ signal: runs.signal,+ renew: (messageId, holder, now) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: () => {+ assert.fail("a hold that never armed has nothing to give back");+ },+ now: () => clock,+ });++ await tab.claim("a-m1", { now: start, holder: "thread-A" });+ keeper.hold("a-m1", "thread-A");++ // Four minutes of preflight, renewed at the keeper's own interval throughout.+ for (let tick = 1; tick <= 8; tick += 1) {+ clock = start + tick * AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();+ }+ await Promise.all(pending);+ assert.equal(keeper.held(), 1, "the hold is still expecting its run");+ assert.equal(+ await otherTab.claim("a-m1", { now: clock }),+ "held-elsewhere",+ "nobody else may take a message this tab is still about to continue",+ );++ // The run finally starts, and the hold arms on it rather than on a predecessor.+ running.add("thread-A");+ runs.change();+ clock += AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();+ await Promise.all(pending);+ assert.equal(+ await otherTab.claim("a-m1", {+ now: clock + AUTO_CONTINUE_LEASE_TTL_MS - 1,+ }),+ "held-elsewhere",+ );+});++test("one compare pane finishing does not release the other pane's lease", async () => {+ // Compare mode mounts two Thread runtimes in ONE tab, each with its own thread and its+ // own run, and either can be resuming a truncated reply while the other is idle. A+ // release that restamped every lease the tab owns and then dropped the lot would end the+ // hold on the pane still generating: its renewals would find nothing held, and one settle+ // window later another tab could claim its message and pay for a second run.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const compareTab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const base = "pane-base";+ const lora = "pane-lora";+ const start = 1_000;++ assert.equal(+ startedARun(+ await compareTab.claim("base-m1", { now: start, holder: base }),+ ),+ true,+ );+ assert.equal(+ startedARun(+ await compareTab.claim("lora-m1", { now: start, holder: lora }),+ ),+ true,+ );++ // The base pane finishes first. Only its own lease goes back.+ await compareTab.release("base-m1", base, { now: start });++ // The lora pane is still generating, and its keeper is still renewing.+ for (let tick = 1; tick <= 3; tick += 1) {+ await compareTab.renew("lora-m1", lora, {+ now: start + tick * AUTO_CONTINUE_LEASE_RENEW_MS,+ });+ }+ const past =+ start + AUTO_CONTINUE_LEASE_TTL_MS + AUTO_CONTINUE_LEASE_RENEW_MS;+ assert.equal(+ await otherTab.claim("lora-m1", { now: past }),+ "held-elsewhere",+ "the still-running pane keeps its message",+ );+ // And the pane that did finish leaves its message continued.+ assert.equal(+ await otherTab.claim("base-m1", {+ now: start + AUTO_CONTINUE_LEASE_TTL_MS + 1,+ }),+ "held-elsewhere",+ );+});++test("a renewal touches this tab's leases and nobody else's", async () => {+ const { storage, store } = storageFake();+ const locks = lockManagerFake();+ const mine = createAutoContinueTab({ storage, locks });+ const theirs = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ await mine.claim("m1", { now: start, holder: PANE });+ await theirs.claim("m2", { now: start, holder: PANE });+ await mine.renew("m1", PANE, { now: start + AUTO_CONTINUE_LEASE_RENEW_MS });++ const leases = JSON.parse(store.get(AUTO_CONTINUE_LEASE_KEY) ?? "{}");+ assert.equal(+ leases.m1.expires,+ start + AUTO_CONTINUE_LEASE_RENEW_MS + AUTO_CONTINUE_LEASE_TTL_MS,+ );+ assert.equal(leases.m2.expires, start + AUTO_CONTINUE_LEASE_TTL_MS);+});++test("lapsed leases are pruned rather than accumulating", async () => {+ const { storage, store } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ await tab.claim("m1", { now: start });+ await createAutoContinueTab({ storage, locks }).claim("m2", {+ now: start + AUTO_CONTINUE_LEASE_TTL_MS + 1,+ });+ const leases = JSON.parse(store.get(AUTO_CONTINUE_LEASE_KEY) ?? "{}");+ assert.deepEqual(Object.keys(leases), ["m2"]);+});++test("reloading one tab does not fire a second continuation", async () => {+ // What stops this today is branch selection: the continuation runs as a sibling and+ // becomes the selected branch, so the truncated reply is no longer last and the effect+ // never asks. The lease is the belt to that pair of braces -- a reload lands on the+ // truncated branch, its module scope is empty, and storage is the only thing that+ // remembers. Nothing here changes what selection already refuses.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const before = createAutoContinueTab({ storage, locks });+ const start = 1_000;+ assert.equal(await before.claim("m1", { now: start }), "started");++ // The reload: same tab, same profile, brand new module scope.+ const after = createAutoContinueTab({ storage, locks });+ assert.equal(+ await after.claim("m1", { now: start + 5_000 }),+ "held-elsewhere",+ );+ assert.equal(after.claimed("m1", { now: start + 5_000 }), true);+});++test("a reset gives back this tab's lease and leaves other tabs alone", async () => {+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const mine = createAutoContinueTab({ storage, locks });+ const theirs = createAutoContinueTab({ storage, locks });+ const now = 1_000;++ assert.equal(await mine.claim("m1", { now }), "started");+ mine.reset();+ // Cleared in both places, so "start from zero" means what it did before the lease.+ assert.equal(await mine.claim("m1", { now }), "started");++ assert.equal(await theirs.claim("m2", { now }), "started");+ mine.reset();+ // Not mine to release: a run another tab is driving is still going.+ assert.equal(+ await createAutoContinueTab({ storage, locks }).claim("m2", { now }),+ "held-elsewhere",+ );+});++test("a stored lease survives a full reset by the module, being another tab's", async () => {+ // `resetAutoContinue()` clears the module claim and the round budget. It cannot know+ // about a lease it never wrote, and must not stamp on one.+ const { storage, store } = storageFake();+ const locks = lockManagerFake();+ await createAutoContinueTab({ storage, locks }).claim("m1", { now: 1_000 });+ resetAutoContinue();+ assert.equal(+ await createAutoContinueTab({ storage, locks }).claim("m1", { now: 1_000 }),+ "held-elsewhere",+ );+ assert.equal(store.has(AUTO_CONTINUE_LEASE_KEY), true);+});++test("a malformed lease record is ignored rather than blocking", async () => {+ const { storage, store } = storageFake();+ store.set(AUTO_CONTINUE_LEASE_KEY, "not json at all");+ assert.equal(await createAutoContinueTab({ storage }).claim("m1"), "started");++ const { storage: other, store: otherStore } = storageFake();+ otherStore.set(AUTO_CONTINUE_LEASE_KEY, JSON.stringify({ m1: { token: 7 } }));+ assert.equal(+ await createAutoContinueTab({ storage: other }).claim("m1"),+ "started",+ );+});++test("a hold whose run never starts holds its lease for the life of the tab", async () => {+ // Not a defect on its own: a hold that has not seen its run yet is deliberately renewed+ // rather than timed out, because preflight has no upper bound and a deadline that fired+ // during one lapsed the lease under a run that had since started streaming.+ //+ // It is the reason the bar must not take a hold for a run it never issued. This is what+ // that mistake costs, so the guard in `ContinueMessageBarForLastMessage` below has+ // something concrete to be measured against.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const running = new Set<string>();+ const pending: Promise<unknown>[] = [];+ const start = 1_000;+ let clock = start;+ const keeper = createAutoContinueLeaseKeeper({+ signal: {+ isRunning: (threadId: string) => running.has(threadId),+ subscribe: () => () => {},+ },+ renew: (messageId: string, holder: string, now: number) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: (messageId: string, holder: string, now: number) => {+ pending.push(tab.release(messageId, holder, { now }));+ },+ now: () => clock,+ });++ assert.equal(+ await tab.claim("m1", { now: start, holder: "thread-A" }),+ "started",+ );+ keeper.hold("m1", "thread-A");+ // `thread-A` never runs: the run this hold is waiting for was never issued.+ for (+ let day = 1;+ day <= (3 * 86_400_000) / AUTO_CONTINUE_LEASE_RENEW_MS;+ day += 1+ ) {+ clock = start + day * AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();+ }+ await Promise.all(pending);++ assert.equal(keeper.held(), 1, "nothing drops a pending hold, by design");+ assert.equal(+ await otherTab.claim("m1", { now: clock + AUTO_CONTINUE_LEASE_TTL_MS - 1 }),+ "held-elsewhere",+ "three days on, every other tab is still refused this message",+ );+});++test("a claim whose run was never issued is left to lapse, not held", async () => {+ // The bar claims under a Web Lock, so the answer lands a tick or more after the render+ // that asked for it, and `aui.thread()` follows the SELECTION rather than the thread the+ // bar belongs to (`runningByThreadId` exists precisely because "detection survives+ // navigation" and `aui.thread()` does not). Switch chats or branches inside that window+ // and `startContinuation` searches a different thread's messages, finds nothing, and+ // returns without calling `startRun`.+ //+ // Taking the hold anyway is the case above: renewed forever, and every other tab refused+ // the message until this one closes. So the message has to still be there before anything+ // is held. Pinned at the source, since there is no renderer here -- the same way+ // composer-keystroke-subscription-budget.test.ts pins its seams.+ const thread = readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ );+ const claimed = thread.indexOf(+ 'claimAutoContinue(messageId, runThreadId ?? "")',+ );+ assert.notEqual(claimed, -1, "the claim moved; this test needs rewriting");+ const branch = thread.slice(+ claimed,+ thread.indexOf("held-elsewhere", claimed),+ );++ const guard = branch.search(/messages\.some\(/);+ const hold = branch.indexOf("holdAutoContinueRun(");+ const record = branch.indexOf("recordAutoContinue(");+ const run = branch.indexOf("startContinuation()");+ assert.notEqual(+ guard,+ -1,+ "nothing checks the message is still there before holding",+ );+ assert.notEqual(hold, -1, "the hold is gone; this test needs rewriting");+ assert.ok(+ guard < hold && guard < record && guard < run,+ "the message has to be confirmed present before the lease is held or the round spent",+ );+ // And the guard must leave the claim alone rather than reach for a timer: the lease+ // lapsing on its own TTL is what a tab that closed mid-claim already produces.+ const between = branch.slice(guard, hold);+ assert.match(+ between,+ /\breturn;/,+ "the guard has to stop before the hold, not fall through",+ );+ assert.doesNotMatch(+ between,+ /setTimeout|setInterval/,+ "a deadline here is the arming timeout coming back, which lapses live continuations",+ );+});++test("a losing claim does not follow the row onto the next branch", () => {+ // The bar's "another tab has this one" answer is state, because the claim resolves after+ // the render that asked for it. A bare boolean is wrong state to keep it in: rows are+ // mounted by INDEX, so selecting a different truncated branch at the same index+ // re-renders this component rather than remounting it, and the flag set for the message+ // that lost carried over onto a message nobody has claimed at all -- no automatic+ // continuation for it, for as long as that row lives.+ const rows = readFileSync(+ new URL(+ "../src/components/assistant-ui/progressive-messages.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ rows,+ /<MessageByIndexProvider key=\{index\}/,+ "rows are no longer keyed by index; this test needs rewriting",+ );++ const thread = readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ );+ const start = thread.indexOf("const ContinueMessageBarForLastMessage");+ assert.notEqual(start, -1, "the bar moved; this test needs rewriting");+ const component = thread.slice(+ start,+ thread.indexOf("const WebSearchToolUIConfirmable", start),+ );+ const state =+ /const \[(\w+), (set\w+)\] = useState<string \| null>\(null\)/.exec(+ component,+ );+ assert.ok(+ state,+ "the losing answer is still a bare flag, so it outlives the message it was decided for",+ );+ assert.match(+ component,+ new RegExp(`claimHeldElsewhere =\\s*${state[1]} === messageId`),+ "the flag has to be re-answered against the message on screen now",+ );+ assert.match(+ component,+ new RegExp(`${state[2]}\\(messageId\\)`),+ "the message that lost is what gets remembered",+ );+});++test("a claim taken for a run that was never issued is given back", async () => {+ // The `stillThere` guard leaves the run unstarted, and the claim it took stays in this+ // tab's continued set: every later claim of that message answers "skipped", so the+ // automatic continuation never runs again for a request nobody ever made.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const start = 1_000;++ assert.equal(+ await tab.claim("m1", { now: start, holder: "thread-A" }),+ "started",+ );+ // The branch changed inside the lock's window, so nothing was issued. Roll it back.+ tab.forget("m1");+ // The storage lease is deliberately kept: this tab may still be deciding, and handing+ // the message over now is how two tabs pay for the same continuation.+ assert.equal(+ await otherTab.claim("m1", { now: start + 1 }),+ "held-elsewhere",+ "the rollback must not hand the message to a second tab",+ );+ // Once that lease lapses -- the same record a tab that closed mid-claim leaves behind --+ // the message is continuable again.+ assert.equal(+ await tab.claim("m1", {+ now: start + AUTO_CONTINUE_LEASE_TTL_MS + 1,+ holder: "thread-A",+ }),+ "started",+ "a claim that started nothing may not wedge the message for the life of the tab",+ );+});++test("the bar rolls its claim back when it issues no run", () => {+ // The behaviour above, pinned where it has to be called from: the early return that+ // decided no run would be issued.+ const thread = readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ );+ const claimed = thread.indexOf(+ 'claimAutoContinue(messageId, runThreadId ?? "")',+ );+ assert.notEqual(claimed, -1, "the claim moved; this test needs rewriting");+ const branch = thread.slice(+ claimed,+ thread.indexOf("held-elsewhere", claimed),+ );+ const guard = branch.search(/messages\.some\(/);+ const hold = branch.indexOf("holdAutoContinueRun(");+ const between = branch.slice(guard, hold);+ assert.match(+ between,+ /forgetAutoContinue\(messageId\)/,+ "the claim survives a run that was never issued, and skips every later one",+ );+});++test("a hold is settled when its run fails before it ever starts", async () => {+ // A preflight failure -- this chat's settings pairing running out, a model that will not+ // load, a connection the adapter refuses -- throws out of `adapter.run` before anything+ // reaches `setThreadRunning(..., true)`, so no `runningByThreadId` transition can ever+ // identify this run as terminal. Without a signal the hold renews its cross-tab lease+ // every 30 seconds for the life of the tab, one leaked hold per failure.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const running = new Set<string>();+ const runs = runSignalFake(running);+ const pending: Promise<unknown>[] = [];+ const start = 1_000;+ let clock = start;+ const keeper = createAutoContinueLeaseKeeper({+ signal: runs.signal,+ renew: (messageId: string, holder: string, now: number) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: () => {+ assert.fail(+ "a run that never started wrote nothing, so nothing may be marked continued",+ );+ },+ now: () => clock,+ });++ assert.equal(+ await tab.claim("m1", { now: start, holder: "thread-A" }),+ "started",+ );+ keeper.hold("m1", "thread-A");+ clock = start + AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();+ assert.equal(keeper.held(), 1, "a slow preflight is still a live hold");++ // The adapter threw. This is the run's own thread saying so.+ keeper.failed("thread-A");+ assert.equal(+ keeper.held(),+ 0,+ "nothing renews a run that failed on its way out",+ );++ const lapsed = clock + AUTO_CONTINUE_LEASE_TTL_MS + 1;+ clock = lapsed;+ keeper.tick();+ await Promise.all(pending);+ assert.equal(+ await otherTab.claim("m1", { now: lapsed }),+ "started",+ "the lease lapses, so another tab can recover a message that was never continued",+ );+});++test("a failure on a thread leaves a hold whose run is already streaming alone", async () => {+ // The same event fires for a failure mid-stream, where the run DID reach+ // `runningByThreadId` and the transition to idle is what settles the hold -- with the+ // `done` marker that says the message has been continued, which a preflight failure has+ // no right to write.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const running = new Set<string>();+ const runs = runSignalFake(running);+ const released: string[] = [];+ const pending: Promise<unknown>[] = [];+ const start = 1_000;+ let clock = start;+ const keeper = createAutoContinueLeaseKeeper({+ signal: runs.signal,+ renew: (messageId: string, holder: string, now: number) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: (messageId: string, holder: string, now: number) => {+ released.push(messageId);+ pending.push(tab.release(messageId, holder, { now }));+ },+ now: () => clock,+ });++ await tab.claim("m1", { now: start, holder: "thread-A" });+ keeper.hold("m1", "thread-A");+ running.add("thread-A");+ runs.change();+ clock = start + AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();++ // The run failed after it had started streaming. Its hold is armed, and armed holds are+ // settled by their own thread going idle, not here.+ keeper.failed("thread-A");+ assert.equal(keeper.held(), 1, "an armed hold is its run's to give back");+ assert.deepEqual(released, []);+ running.delete("thread-A");+ runs.change();+ await Promise.all(pending);+ assert.deepEqual(+ released,+ ["m1"],+ "and the thread going idle is what gives it back",+ );+ assert.equal(keeper.held(), 0);+});++test("the keeper is wired to the failure the adapter already reports", () => {+ // There is exactly one signal for a run that failed on its way out, and it is not a+ // deadline: the adapter wrapper catches everything `adapter.run` throws and announces it+ // per thread. Pinned at both ends, since neither side is exercised by a unit test.+ const adapter = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ const wrapper = adapter.slice(adapter.indexOf("yield* adapter.run(args)"));+ assert.match(+ wrapper,+ /catch \(error\) \{[\s\S]*notifyPromptQueueRunFailed\(/,+ "the adapter no longer reports a failed run per thread; this test needs rewriting",+ );++ const wiring = readFileSync(+ new URL(+ "../src/features/chat/utils/auto-continue-run-keeper.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ wiring,+ /PROMPT_QUEUE_RUN_FAILED_EVENT/,+ "nothing settles a hold whose run failed before it started",+ );+ assert.match(+ wiring,+ /keeper\.failed\(/,+ "the failure has to reach the keeper",+ );+ assert.doesNotMatch(+ wiring,+ /setTimeout\(/,+ "a deadline here is the arming timeout coming back, which lapses live continuations",+ );+});++/**+ * The same field the keeper reads in the app, owners and all.+ *+ * `runSignalFake` above answers from a bare set of thread ids, which is every case where+ * what holds the flag does not matter. Here it does: the image gate flips the flag on and+ * off around a request it never issued, and the real signal in+ * `auto-continue-run-keeper.ts` is what tells that pair from a run. Built on the shipped+ * predicate rather than a copy of it, so a change to either side fails here.+ */+function ownedRunSignalFake() {+ const running = new Map<string, { owner: () => void }[]>();+ const listeners = new Set<() => void>();+ const announce = () => {+ for (const listener of [...listeners]) {+ listener();+ }+ };+ return {+ signal: {+ isRunning: (threadId: string) => {+ const owners = running.get(threadId);+ return Boolean(owners?.length) && !isImageGateRunOnly(owners);+ },+ subscribe: (onChange: () => void) => {+ listeners.add(onChange);+ return () => listeners.delete(onChange);+ },+ },+ /** `setThreadRunning(threadId, true, { owner })`, and the notify it fires. */+ start: (threadId: string, owner: () => void) => {+ running.set(threadId, [...(running.get(threadId) ?? []), { owner }]);+ announce();+ },+ /** `setThreadRunning(threadId, false, { owner })`, clearing that run only. */+ end: (threadId: string, owner: () => void) => {+ const rest = (running.get(threadId) ?? []).filter(+ (entry) => entry.owner !== owner,+ );+ if (rest.length > 0) {+ running.set(threadId, rest);+ } else {+ running.delete(threadId);+ }+ announce();+ },+ };+}++test("a continuation refused by the image gate is not recorded as continued", async () => {+ // Reopen a chat containing a picture with a text-only model loaded -- or switch Vision+ // off for the one that wrote the truncated reply -- and the automatic continuation is+ // refused before a request is made. The gate pulses the thread's running flag true and+ // then false first, so compare mode's `waitForRunEnd` resolves rather than hanging. Read+ // as a run, that pair arms the hold and settles it one call later with the `done` marker+ // that tells every other tab for a day that the message HAS been continued -- for a+ // provider request that was never sent. The failure that follows cannot take it back: a+ // released hold is already gone.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const runs = ownedRunSignalFake();+ const pending: Promise<unknown>[] = [];+ const start = 1_000;+ let clock = start;+ const keeper = createAutoContinueLeaseKeeper({+ signal: runs.signal,+ renew: (messageId: string, holder: string, now: number) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: () => {+ assert.fail(+ "the gate issued no request, so nothing may be marked continued",+ );+ },+ now: () => clock,+ });++ assert.equal(+ await tab.claim("m1", { now: start, holder: "thread-A" }),+ "started",+ );+ keeper.hold("m1", "thread-A");++ // `chat-adapter.ts`: setThreadRunning(true, { owner: gateOwner }) then false, then throw.+ const gateOwner = createImageGateRunOwner();+ runs.start("thread-A", gateOwner);+ assert.equal(+ keeper.held(),+ 1,+ "a pulse that stands for a refusal does not arm the hold",+ );+ runs.end("thread-A", gateOwner);+ assert.equal(keeper.held(), 1, "and so cannot settle it either");++ // The throw reaches the wrapper's catch, which is the signal that ends an unarmed hold.+ keeper.failed("thread-A");+ assert.equal(keeper.held(), 0);++ const lapsed = clock + AUTO_CONTINUE_LEASE_TTL_MS + 1;+ clock = lapsed;+ keeper.tick();+ await Promise.all(pending);+ assert.equal(+ await otherTab.claim("m1", { now: lapsed }),+ "started",+ "the message was never continued, so it comes back rather than reading done for a day",+ );+});++test("a real run on the thread the gate refused still owns its lease", async () => {+ // Compare mode puts two runtimes on one key, and an unresolved thread files its run under+ // the shared "__default". A gate firing beside a run that is genuinely streaming must not+ // make the keeper read the thread as idle: that hold would be released mid-stream, and one+ // settle window later another tab could claim the message being written.+ const { storage } = storageFake();+ const locks = lockManagerFake();+ const tab = createAutoContinueTab({ storage, locks });+ const otherTab = createAutoContinueTab({ storage, locks });+ const runs = ownedRunSignalFake();+ const released: string[] = [];+ const pending: Promise<unknown>[] = [];+ const start = 1_000;+ let clock = start;+ const keeper = createAutoContinueLeaseKeeper({+ signal: runs.signal,+ renew: (messageId: string, holder: string, now: number) => {+ pending.push(tab.renew(messageId, holder, { now }));+ },+ release: (messageId: string, holder: string, now: number) => {+ released.push(messageId);+ pending.push(tab.release(messageId, holder, { now }));+ },+ now: () => clock,+ });++ await tab.claim("m1", { now: start, holder: "__default" });+ keeper.hold("m1", "__default");++ const streamingRun = () => {};+ runs.start("__default", streamingRun);+ clock = start + AUTO_CONTINUE_LEASE_RENEW_MS;+ keeper.tick();++ // The sibling's image turn is refused while this one streams.+ const gateOwner = createImageGateRunOwner();+ runs.start("__default", gateOwner);+ runs.end("__default", gateOwner);+ assert.deepEqual(released, [], "the run beside it is still generating");+ assert.equal(keeper.held(), 1);++ // Its own run ending is what gives the lease back, marked continued.+ runs.end("__default", streamingRun);+ await Promise.all(pending);+ assert.deepEqual(released, ["m1"]);+ assert.equal(+ await otherTab.claim("m1", {+ now: clock + AUTO_CONTINUE_LEASE_TTL_MS + 1,+ }),+ "held-elsewhere",+ "this one really was continued",+ );+});++test("only the gate's own tokens are read as a refusal", () => {+ // The predicate is asked about "is this thread generating", so anything it cannot prove+ // is a gate pulse has to answer yes: a run from before per-run tracking carries no owner+ // at all, and a key shared with a real run carries one of each.+ const gateOwner = createImageGateRunOwner();+ const runOwner = () => {};+ assert.equal(isImageGateRunOnly([{ owner: gateOwner }]), true);+ assert.equal(isImageGateRunOnly([{ owner: runOwner }]), false);+ assert.equal(+ isImageGateRunOnly([{ owner: gateOwner }, { owner: runOwner }]),+ false,+ );+ assert.equal(isImageGateRunOnly([]), false, "an ownerless flag is a run");+ assert.equal(isImageGateRunOnly(undefined), false);+ assert.notEqual(+ createImageGateRunOwner(),+ gateOwner,+ "one token per pulse, or two gates on a shared key clear each other",+ );+});++test("the gate's pulse is tagged where it is fired and read where it matters", () => {+ // Neither end is exercised by a unit test: the adapter's gate is deep inside a run, and+ // the keeper's real signal reads a zustand store. Pinned at both ends instead.+ const adapter = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ const gate = adapter.slice(adapter.indexOf("const imageGateReason ="));+ assert.match(+ gate,+ /const gateOwner = createImageGateRunOwner\(\)/,+ "an anonymous owner is indistinguishable from a run that really started",+ );+ assert.match(+ gate.slice(gate.indexOf("const gateOwner")),+ /setThreadRunning\([\s\S]*owner: gateOwner[\s\S]*setThreadRunning\([\s\S]*owner: gateOwner/,+ "the pulse compare mode waits on is still fired under that token",+ );++ const wiring = readFileSync(+ new URL(+ "../src/features/chat/utils/auto-continue-run-keeper.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ wiring,+ /isImageGateRunOnly\(state\.runOwnerByThreadId\[threadId\]\)/,+ "the keeper is arming holds on a request the gate refused to send",+ );+ assert.doesNotMatch(+ wiring,+ /setTimeout\(/,+ "a deadline here is the arming timeout coming back, which lapses live continuations",+ );+});diff --git a/tests/studio/playwright_loaded_models_indicator.py b/tests/studio/playwright_loaded_models_indicator.pyindex c5912a32f4d..90ba72ee505 100644--- a/tests/studio/playwright_loaded_models_indicator.py+++ b/tests/studio/playwright_loaded_models_indicator.py@@ -39,6 +39,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))from _playwright_robust import ( # noqa: E402chromium_launch_args,install_view_transition_killer,+ install_wall_clock_watchdog,wait_for_health,)@@ -51,6 +52,15 @@ ART.mkdir(parents = True, exist_ok = True)PLAYWRIGHT_BROWSER = os.environ.get("STUDIO_PLAYWRIGHT_BROWSER", "chromium").lower()PLAYWRIGHT_CHANNEL = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL") or None+# The wall this suite did not have. Its siblings (playwright_chat_ui.py,+# playwright_extra_ui.py) have carried one since a `page.evaluate` -- which+# takes no `timeout=` at all -- hung a job for 27 minutes in #5387. This suite+# has four raw `page.evaluate` calls of its own and is the LAST thing the+# Windows chat lane runs, so a wedge here used to be indistinguishable from the+# job simply never finishing. Same 720s default and same env knob as the+# siblings, so a slow runner is tuned in one place.+WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "720"))+# The card polls every 5s; two ticks plus slack is enough to see a change land.SETTLE_MS = int(os.environ.get("STUDIO_UI_INDICATOR_SETTLE_MS", "12000"))@@ -290,6 +300,11 @@ def main() -> int:return 1with sync_playwright() as p:+ install_wall_clock_watchdog(+ WALL_TIMEOUT_S,+ label = "ui-indicator",+ info = info,+ )browser_type = getattr(p, PLAYWRIGHT_BROWSER)launch_kwargs: dict = {"headless": True}if PLAYWRIGHT_BROWSER == "chromium":diff --git a/tests/studio/playwright_update_banner_layout.py b/tests/studio/playwright_update_banner_layout.pyindex be1d20ad023..f6c45cfd045 100644--- a/tests/studio/playwright_update_banner_layout.py+++ b/tests/studio/playwright_update_banner_layout.py@@ -35,9 +35,16 @@ from playwright.sync_api import sync_playwrightsys.path.insert(0, str(Path(__file__).resolve().parent))from _playwright_robust import ( # noqa: E402chromium_launch_args,+ install_wall_clock_watchdog,wait_for_health,)+# The wall this suite did not have, matching playwright_chat_ui.py and+# playwright_extra_ui.py. It has six raw `page.evaluate` calls, which take no+# `timeout=` at all, and it runs mid-lane on Windows sharing a server with the+# suite before it -- so a wedge here stalled the lane with nothing printed.+WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "720"))+BASE = os.environ["BASE_URL"]OLD = os.environ["STUDIO_OLD_PW"]NEW = os.environ["STUDIO_NEW_PW"]@@ -744,6 +751,11 @@ def main() -> int:return 1with sync_playwright() as p:+ install_wall_clock_watchdog(+ WALL_TIMEOUT_S,+ label = "ui-update-banner",+ info = info,+ )launch_kwargs: dict = {"headless": True}if PLAYWRIGHT_BROWSER == "chromium":launch_kwargs["args"] = chromium_launch_args()