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: read once per tab return instead of on both visibility and focus (#17300)
Daniel Han4189fa225d5c
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 70c36ae1ec1..18894b6817c 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -2536,6 +2536,7 @@ function useStudioRuntimeAdapters(globalThis,document,recoverCurrentThread,+ { wakeKey: () => aui.threadListItem().getState().remoteId },);}, [aui]);diff --git a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts b/studio/frontend/src/features/chat/utils/chat-generation-recovery.tsindex 75408fa210e..fbea9f6aa1e 100644--- a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts@@ -9,6 +9,7 @@ import {} from "./parse-assistant-content";import type { ContextUsageMarkers } from "./saved-context-usage";import { isExternalModelId } from "../external-providers";+import { createWakeDedupe } from "../../../lib/wake-dedupe";import { contextUsageReasoningKey, type ContextUsageReasoningFields } from "./context-usage-reasoning";export type StoredGenerationStatus = ChatGenerationStatus;@@ -734,15 +735,21 @@ export function subscribeGenerationRecoveryTriggers(windowTarget: RecoveryEventTarget,documentTarget: RecoveryVisibilityTarget,recover: () => void,+ options: { wakeKey?: () => string | undefined; now?: () => number } = {},): () => void {+ // Online and pageshow always run; focus and visible of one tab return read once per thread.+ const isFreshWake = createWakeDedupe(undefined, options.now);+ const wake = () => {+ if (isFreshWake(options.wakeKey?.() ?? "")) recover();+ };const onVisible = () => {if (documentTarget.visibilityState === "visible") {- recover();+ wake();}};const onFocus = () => {if (documentTarget.visibilityState !== "hidden") {- recover();+ wake();}};windowTarget.addEventListener("online", recover);diff --git a/studio/frontend/src/features/hub/lib/resident-status-refresh.ts b/studio/frontend/src/features/hub/lib/resident-status-refresh.tsindex e83eaf88762..7c1c17db1c1 100644--- a/studio/frontend/src/features/hub/lib/resident-status-refresh.ts+++ b/studio/frontend/src/features/hub/lib/resident-status-refresh.ts@@ -3,6 +3,8 @@// Re-read when the tab regains focus instead of polling: an API call may switch the resident model.+import { createWakeDedupe } from "../../../lib/wake-dedupe.ts";+export interface ResidentStatusRefreshTargets {window: Pick<EventTarget, "addEventListener" | "removeEventListener">;document: Pick<EventTarget, "addEventListener" | "removeEventListener"> & {@@ -17,11 +19,15 @@ function browserTargets(): ResidentStatusRefreshTargets {export function subscribeResidentStatusRefresh(refresh: () => void,targets: ResidentStatusRefreshTargets = browserTargets(),+ now: () => number = Date.now,): () => void {- const onFocus = () => refresh();+ const isFreshWake = createWakeDedupe(undefined, now);+ const onFocus = () => {+ if (isFreshWake()) refresh();+ };// Focus alone misses a backgrounded tab, visibility alone a window that never hid.const onVisibility = () => {- if (!targets.document.hidden) refresh();+ if (!targets.document.hidden && isFreshWake()) refresh();};targets.window.addEventListener("focus", onFocus);targets.document.addEventListener("visibilitychange", onVisibility);diff --git a/studio/frontend/src/features/loaded-models/use-loaded-models.ts b/studio/frontend/src/features/loaded-models/use-loaded-models.tsindex 4095159cceb..59326bdb38d 100644--- a/studio/frontend/src/features/loaded-models/use-loaded-models.ts+++ b/studio/frontend/src/features/loaded-models/use-loaded-models.ts@@ -3,6 +3,7 @@import { useT } from "@/i18n";import { toast } from "@/lib/toast";+import { createWakeDedupe } from "@/lib/wake-dedupe";import { useCallback, useEffect, useRef, useState } from "react";import {type ModelRuntime,@@ -174,8 +175,9 @@ export function useLoadedModels(if (document.hidden) return;refresh();}, POLL_INTERVAL_MS);+ const isFreshWake = createWakeDedupe();const onWake = () => {- if (!document.hidden) refresh();+ if (!document.hidden && isFreshWake()) refresh();};window.addEventListener("focus", onWake);document.addEventListener("visibilitychange", onWake);diff --git a/studio/frontend/src/lib/wake-dedupe.ts b/studio/frontend/src/lib/wake-dedupe.tsnew file mode 100644index 00000000000..3afe7b06b83--- /dev/null+++ b/studio/frontend/src/lib/wake-dedupe.ts@@ -0,0 +1,20 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A tab return fires visibilitychange and focus back to back: the first one does the read.+export const WAKE_DEDUPE_MS = 1_000;++export function createWakeDedupe(+ windowMs: number = WAKE_DEDUPE_MS,+ now: () => number = Date.now,+): (key?: string) => boolean {+ let last: { key: string; at: number } | null = null;+ return (key = "") => {+ const at = now();+ // A clock stepped backwards counts as a fresh wake rather than muting them.+ const elapsed = last && last.key === key ? at - last.at : Number.NaN;+ if (elapsed >= 0 && elapsed < windowMs) return false;+ last = { key, at };+ return true;+ };+}diff --git a/studio/frontend/tests/hub-resident-status.test.ts b/studio/frontend/tests/hub-resident-status.test.tsindex 9a316e1cdf2..3c58927bd04 100644--- a/studio/frontend/tests/hub-resident-status.test.ts+++ b/studio/frontend/tests/hub-resident-status.test.ts@@ -223,14 +223,20 @@ test("an empty status does not fight a load this tab started", () => {test("coming back to the window re-reads inference status", () => {// An API request can auto-switch at any time and the Hub only reads on mount.const targets = fakeTargets();+ let clock = 0;let reads = 0;- subscribeResidentStatusRefresh(() => {- reads += 1;- }, targets);+ subscribeResidentStatusRefresh(+ () => {+ reads += 1;+ },+ targets,+ () => clock,+ );assert.equal(reads, 0, "subscribing must not read on its own");targets.fire("window", "focus");assert.equal(reads, 1);+ clock += 5_000;targets.fire("document", "visibilitychange");assert.equal(reads, 2);});diff --git a/studio/frontend/tests/tab-return-wake-dedupe.test.ts b/studio/frontend/tests/tab-return-wake-dedupe.test.tsnew file mode 100644index 00000000000..c3a1f75a112--- /dev/null+++ b/studio/frontend/tests/tab-return-wake-dedupe.test.ts@@ -0,0 +1,150 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { subscribeResidentStatusRefresh } from "../src/features/hub/lib/resident-status-refresh.ts";+import { fakeTargets, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { subscribeGenerationRecoveryTriggers } = await import(+ "../src/features/chat/utils/chat-generation-recovery.ts"+);++function recoveryHarness(wakeKey = () => "thread-1" as string | undefined) {+ const windowTarget = new EventTarget();+ const documentTarget = Object.assign(new EventTarget(), {+ visibilityState: "hidden",+ });+ const clock = { now: 0 };+ let recoveries = 0;+ const unsubscribe = subscribeGenerationRecoveryTriggers(+ windowTarget,+ documentTarget,+ () => {+ recoveries += 1;+ },+ { wakeKey, now: () => clock.now },+ );+ const returnToTab = (focusFirst = false) => {+ documentTarget.visibilityState = "hidden";+ documentTarget.dispatchEvent(new Event("visibilitychange"));+ if (focusFirst) windowTarget.dispatchEvent(new Event("focus"));+ documentTarget.visibilityState = "visible";+ documentTarget.dispatchEvent(new Event("visibilitychange"));+ if (!focusFirst) windowTarget.dispatchEvent(new Event("focus"));+ };+ return {+ windowTarget,+ clock,+ returnToTab,+ unsubscribe,+ get recoveries() {+ return recoveries;+ },+ };+}++test("a tab return recovers the open chat thread once", () => {+ const harness = recoveryHarness();+ harness.returnToTab();+ assert.equal(harness.recoveries, 1, "visible + focus must cost one recovery");+ harness.unsubscribe();+});++test("a focus that lands while still hidden does not use up the wake", () => {+ const harness = recoveryHarness();+ harness.returnToTab(true);+ assert.equal(harness.recoveries, 1);+ harness.unsubscribe();+});++test("a wake after the dedupe window still recovers", () => {+ const harness = recoveryHarness();+ harness.returnToTab();+ harness.clock.now += 999;+ harness.windowTarget.dispatchEvent(new Event("focus"));+ assert.equal(harness.recoveries, 1);+ harness.clock.now += 1;+ harness.windowTarget.dispatchEvent(new Event("focus"));+ assert.equal(harness.recoveries, 2);+ harness.clock.now += 5_000;+ harness.returnToTab();+ assert.equal(harness.recoveries, 3);+ harness.unsubscribe();+});++test("online and pageshow always recover, even right after a wake", () => {+ const harness = recoveryHarness();+ harness.returnToTab();+ harness.windowTarget.dispatchEvent(new Event("online"));+ harness.windowTarget.dispatchEvent(new Event("pageshow"));+ harness.windowTarget.dispatchEvent(new Event("online"));+ assert.equal(harness.recoveries, 4);+ harness.unsubscribe();+});++test("the wake dedupe is per thread", () => {+ let thread = "thread-1";+ const harness = recoveryHarness(() => thread);+ harness.returnToTab();+ thread = "thread-2";+ harness.windowTarget.dispatchEvent(new Event("focus"));+ assert.equal(harness.recoveries, 2);+ harness.windowTarget.dispatchEvent(new Event("focus"));+ assert.equal(harness.recoveries, 2);+ harness.unsubscribe();+});++test("a tab return re-reads the resident model status once", () => {+ for (const order of [+ ["document", "window"],+ ["window", "document"],+ ] as const) {+ const targets = fakeTargets();+ let clock = 0;+ let reads = 0;+ subscribeResidentStatusRefresh(+ () => {+ reads += 1;+ },+ targets,+ () => clock,+ );+ const returnToTab = () => {+ for (const target of order) {+ targets.fire(+ target,+ target === "window" ? "focus" : "visibilitychange",+ );+ }+ };+ returnToTab();+ assert.equal(reads, 1, `${order.join(" then ")} must cost one read`);+ clock += 1_000;+ returnToTab();+ assert.equal(reads, 2, "the next tab return still reads");+ }+});++test("the loaded-models card wakes once per tab return", () => {+ const source = readFileSync(+ new URL(+ "../src/features/loaded-models/use-loaded-models.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const effect = source.slice(+ source.indexOf("const onWake = () => {"),+ source.indexOf('window.addEventListener("focus", onWake);'),+ );+ assert.match(+ effect,+ /if \(!document\.hidden && isFreshWake\(\)\) refresh\(\);/,+ );+ assert.match(source, /const isFreshWake = createWakeDedupe\(\);/);+});