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: add a setting to stop chats and Deep Research when the tab closes (#14062)
alkinun8e69f2058e32
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex c805f28bb57..d9cbfdce257 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -890,6 +890,11 @@ async def lifespan(app: FastAPI):except Exception as exc:_lifespan_log.warning("chat generation lease sweeper failed to start: %s", exc)+ # Stops the runs whose owner asked for them to end with the tab, once no tab follows them.+ from state import unattended_runs as _unattended_runs++ _unattended_runs.start()+reap_hub_orphan_workers()try:from hub.utils.download_manifest import migrate_ordinary_v2_manifests_for_downgrade@@ -920,6 +925,12 @@ async def lifespan(app: FastAPI):app.state.research_supervisor = ResearchSupervisor(app)app.state.research_supervisor.start()+ try:+ # The supervisor resumes runs that asked to stop with their tab; their watches died with the old process.+ from routes.research_runs import rearm_unattended_research_runs+ rearm_unattended_research_runs(app)+ except Exception as exc:+ _lifespan_log.warning("re-arming unattended research runs failed: %s", exc)from core.inference.chat_generation_runs import ChatGenerationSupervisor@@ -1033,6 +1044,10 @@ async def lifespan(app: FastAPI):except asyncio.CancelledError:pass+ from state import unattended_runs as _unattended_runs++ await _unattended_runs.stop()+_research_supervisor = getattr(app.state, "research_supervisor", None)if _research_supervisor is not None:await _research_supervisor.stop()diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.pyindex c728f78eaa5..9c933bd2502 100644--- a/studio/backend/routes/chat_generation_runs.py+++ b/studio/backend/routes/chat_generation_runs.py@@ -21,7 +21,7 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationErrorfrom auth.authentication import get_current_subjectfrom auth import policy-from state import active_generations, run_subscribers+from state import active_generations, run_subscribers, unattended_runsfrom utils.account_context import current_account, current_account_id, run_asfrom core.inference.llama_keepwarm import inference_lifecycle_gatefrom models.inference import ChatCompletionRequest@@ -88,6 +88,9 @@ class CreateChatGenerationRun(BaseModel):userMessageId: str = Field(min_length = 1, max_length = 256)assistantMessageId: str = Field(min_length = 1, max_length = 256)requestPayload: dict[str, Any]+ # The owner's "stop when I close the tab": cancel the run once no tab has followed it for a+ # while (state/unattended_runs.py) rather than letting it finish in the background.+ stopWhenUnattended: bool = Falsedef _normalized_key(key: object) -> str:@@ -284,6 +287,37 @@ def cancel_account_run(request: Request, run_id: str, *, supervisor_name: str) -_cancel_by_cancel_id_or_stash(run_id)+def _watch_unattended(request: Request, run_id: str) -> None:+ """Cancel ``run_id`` the way the cancel route does once no tab is following it."""+ account = current_account()++ def settled() -> bool:+ run = run_as(account, db.get_run, run_id)+ return run is None or run["status"] in db.TERMINAL_STATUSES or bool(run["cancelRequested"])++ async def cancel() -> None:+ run = await asyncio.to_thread(run_as, account, db.request_cancel, run_id)+ if (+ run is not None+ and run["status"] in {"cancelling", "cancelled"}+ and (+ getattr(request.app.state, "chat_generation_supervisor", None) is not None+ or policy.installation_has_managed_accounts()+ )+ ):+ # On the loop: the supervisor's cancel may cancel its asyncio task.+ run_as(+ account,+ cancel_account_run,+ request,+ run_id,+ supervisor_name = "chat_generation_supervisor",+ )++ # The id the events stream stamps, under the same account it stamps it with.+ unattended_runs.watch(run_id, current_account_id() or "", settled = settled, cancel = cancel)++def _require_available_supervisor_run_id(run_id: str) -> None:"""A legacy supervisor keys tasks by bare ID, and start() no-ops on a held id, so a foreignactive slot must be refused or an admitted owner run would never be scheduled."""@@ -351,6 +385,8 @@ async def create_chat_generation_run(thread_id = run["threadId"],model = run["requestPayload"].get("model"),)+ if payload.stopWhenUnattended and run["status"] not in db.TERMINAL_STATUSES:+ _watch_unattended(request, run["id"])return {**run, "created": created}diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex c0e7949efee..11ca2a7ee9f 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -606,6 +606,8 @@ class ChatSettingsPayload(BaseModel):# contextPolicy/headroom are the per-request overrides for UNSLOTH_CONTEXT_POLICY and# ROLLING_COMPACTION_HEADROOM_RATIO.autoCompactEnabled: Optional[bool] = None+ # Off: a chat or Deep Research run stops once no tab follows it (state/unattended_runs.py).+ keepRunningWhenTabClosed: Optional[bool] = NonecontextPolicy: Optional[Literal["inherit", "checkpoint", "rolling"]] = NonecompactionHeadroomRatio: Optional[float] = Field(default = None, ge = 0.0, le = 0.9)diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex 92531cb3196..54960c59742 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -5,7 +5,7 @@from __future__ import annotations-from utils.account_context import current_account, run_as+from utils.account_context import current_account, current_account_id, run_asimport asyncioimport jsonimport re@@ -24,6 +24,7 @@ from core.inference.web_access_policy import normalize_website_policyfrom storage import research_runs_db as dbfrom core.inference.providers import answers_decisions_only, provider_runs_local_toolsfrom models.providers import MAX_JSON_SAFE_INTEGER+from state import run_subscribers, unattended_runsfrom state.tool_policy import get_tool_policyfrom storage import mcp_servers_db, providers_dbfrom storage.studio_db import get_chat_message, get_chat_thread, upsert_chat_message@@ -86,6 +87,9 @@ class CreateResearchRun(BaseModel):websitePolicy: dict[str, list[str]] | None = Noneinstructions: str | None = Field(default = None, max_length = 32_000)question: str | None = Field(default = None, max_length = 2000)+ # The owner's "stop when I close the tab": cancel the run once no tab has followed it for a+ # while (state/unattended_runs.py). Stored in the config, so a retry and a restart keep it.+ stopWhenUnattended: bool = False@field_validator("budgets", mode = "before")@classmethod@@ -197,6 +201,80 @@ def _sync_assistant(run: dict, text: str | None = None) -> None:)+def _attendance_id(run_id: str) -> str:+ # Prefixed: chat run ids are the client's, so a bare research id could collide with one.+ return f"research:{run_id}"+++def _watch_if_unattended_stop(+ app: Any,+ run: dict,+ *,+ replace: bool = False,+) -> None:+ """Cancel ``run`` the way the cancel route does once no tab is following it, if its owner asked.++ ``replace`` for a new attempt under the run's id: a rebind or retry starts its own grace, and a+ rebound attempt that keeps running drops the watch the previous attempt left behind.+ """+ run_id = run["id"]+ if not (run.get("config") or {}).get("stopWhenUnattended"):+ if replace:+ unattended_runs.unwatch(_attendance_id(run_id), current_account_id() or "")+ return+ if run["status"] in db.TERMINAL_STATUSES or run["status"] == "cancelling":+ return+ account = current_account()+ # The watch belongs to this attempt only: a retry or rebind reuses the id and bumps retryCount.+ attempt = int(run.get("retryCount") or 0)++ def settled() -> bool:+ current = run_as(account, db.get_run, run_id)+ return (+ current is None+ or current["status"] in db.TERMINAL_STATUSES+ or current["status"] == "cancelling"+ or int(current.get("retryCount") or 0) != attempt+ )++ async def cancel() -> None:+ try:+ status = await asyncio.to_thread(+ run_as, account, db.request_cancel, run_id, expected_attempt = attempt+ )+ except KeyError:+ return+ if status is None:+ # A newer attempt took the id between this pass's settled() read and now.+ return+ supervisor = getattr(app.state, "research_supervisor", None)+ if supervisor is not None and status == "cancelling":+ run_as(account, supervisor.cancel, run_id)+ current = await asyncio.to_thread(run_as, account, db.get_run, run_id)+ if current is not None:+ await asyncio.to_thread(run_as, account, _sync_assistant, current)++ unattended_runs.watch(+ _attendance_id(run_id),+ current_account_id() or "",+ settled = settled,+ cancel = cancel,+ replace = replace,+ )+++def rearm_unattended_research_runs(app: Any) -> None:+ """Watch every unsettled run that asked to stop with its tab, after a restart emptied the watches.++ The supervisor resumes these runs on its own, so waiting for a follower to reattach would let a+ run whose tab never comes back finish despite the setting. Its grace starts now.+ """+ from core.training.account_jobs import job_accounts+ for account in job_accounts():+ for run in run_as(account, db.list_all_active):+ run_as(account, _watch_if_unattended_stop, app, run)++def _is_sensitive_key(key: object) -> bool:# Match after stripping separators/case so openaiApiKey, access_token, clientSecret all hit.normalized = re.sub(r"[^a-z0-9]", "", str(key).casefold())@@ -422,6 +500,7 @@ def _sanitize_config(# stamped once so a run spanning midnight or a settings change keeps its starting date."currentDate": current_date_prompt_line(request = http_request),"question": (payload.question or "").strip(),+ **({"stopWhenUnattended": True} if payload.stopWhenUnattended else {}),}@@ -484,6 +563,8 @@ def create_research_run(if supervisor is not None:supervisor.note_request_address(request)supervisor.wake()+ # A rebind reuses a stopped run's id, so this attempt replaces whatever watch that one left.+ _watch_if_unattended_stop(request.app, run, replace = True)return run@@ -593,6 +674,8 @@ def retry_research_run(supervisor.wake()run = _require_run(run_id)_sync_assistant(run)+ # A new attempt under the same id, with a grace of its own.+ _watch_if_unattended_stop(request.app, run, replace = True)return run@@ -607,14 +690,23 @@ async def research_events(last_event_id: str | None = Header(None, alias = "Last-Event-ID"),current_subject: str = Depends(get_current_subject),):- _require_run(run_id)+ opening = _require_run(run_id)header_after = int(last_event_id) if last_event_id and last_event_id.isdigit() else 0cursor = max(after or 0, header_after)+ # Re-armed by its follower too: idempotent, and a watch can only have been lost with the process.+ if (opening.get("config") or {}).get("stopWhenUnattended"):+ _watch_if_unattended_stop(request.app, opening)+ # One token per stream, so a closing tab clears only its own stamp (state/run_subscribers.py).+ attendance_id = _attendance_id(run_id)+ follower = run_subscribers.new_follower_token()+ follower_account = current_account_id() or ""async def stream():nonlocal cursorloop = asyncio.get_running_loop()while True:+ # What state/unattended_runs.py reads to tell a watched run from one whose tab is gone.+ run_subscribers.mark_subscriber_seen(attendance_id, follower, follower_account)# off the default executor: parked followers there starved the run's own db writes.events = await loop.run_in_executor(_EVENT_WAIT_EXECUTOR,@@ -647,8 +739,15 @@ async def research_events(if not events:yield ": keep-alive\n\n"+ async def stream_while_attended():+ try:+ async for frame in stream():+ yield frame+ finally:+ run_subscribers.subscriber_departed(attendance_id, follower, follower_account)+return StreamingResponse(- stream(),+ stream_while_attended(),media_type = "text/event-stream",headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},)diff --git a/studio/backend/state/unattended_runs.py b/studio/backend/state/unattended_runs.pynew file mode 100644index 00000000000..8942d359787--- /dev/null+++ b/studio/backend/state/unattended_runs.py@@ -0,0 +1,197 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Stop durable runs whose owner asked for them to end once no tab is watching.++A durable chat run or Deep Research run outlives its tab by design (#10365), which is what most+people want from a long research task. Some want the opposite: closing the tab should stop the+run, as the browser-owned stream always did. The client says so per run (``stopWhenUnattended``+on admission), and this watchdog cancels such a run once ``run_subscribers`` has heard from no+follower for ``_GRACE_S``.++Attendance, not the closing request: a phone that kills a background tab sends nothing at all.+The grace is what lets a reload, a follower reconnecting after a network blip (its backoff tops+out at 8s), or a second tab pick the run up before it is stopped. A run nobody ever attaches to+counts its grace from when it was watched, so a tab that closes between admission and its first+event stream still stops the run.++In memory, like ``run_subscribers``: a chat run does not survive a restart anyway, and a Deep+Research run is re-armed from its stored config at startup and whenever a follower reattaches.+"""++from __future__ import annotations++import asyncio+import math+import os+import threading+import time+from dataclasses import dataclass+from typing import Awaitable, Callable++from loggers import get_logger+from state import run_subscribers++logger = get_logger(__name__)++# Comfortably past a reload and the follower's longest reconnect backoff, short enough that a run+# the user meant to stop does not keep its model busy for long.+_GRACE_DEFAULT_S = 30.0+_CHECK_INTERVAL_S = 5.0+++def _grace_from_env() -> float:+ """Read the grace once, at import. A value nobody can parse falls back rather than raising on the chat path."""+ raw = os.environ.get("UNSLOTH_STUDIO_UNATTENDED_RUN_GRACE_S")+ if raw is None or not raw.strip():+ return _GRACE_DEFAULT_S+ try:+ value = float(raw)+ except ValueError:+ return _GRACE_DEFAULT_S+ if not math.isfinite(value) or value < 0:+ return _GRACE_DEFAULT_S+ return value+++_GRACE_S = _grace_from_env()+++@dataclass+class _Watch:+ attendance_id: str+ account_id: str+ # Blocking (it reads the run's database), so it is called off the loop.+ settled: Callable[[], bool]+ # Runs on the serving loop: a supervisor's cancel can touch its asyncio tasks.+ cancel: Callable[[], Awaitable[None]]+ unattended_since: float+++_LOCK = threading.Lock()+# (account_id, attendance_id) -> watch+_WATCHES: dict[tuple[str, str], _Watch] = {}+_task: asyncio.Task | None = None+++def _key(account_id: str, attendance_id: str) -> tuple[str, str]:+ return (account_id or "", attendance_id)+++def watch(+ attendance_id: str,+ account_id: str = "",+ *,+ settled: Callable[[], bool],+ cancel: Callable[[], Awaitable[None]],+ replace: bool = False,+) -> None:+ """Stop ``attendance_id`` once it has gone ``_GRACE_S`` with no follower.++ ``attendance_id`` is the id its followers stamp in ``run_subscribers``. Idempotent by default:+ a run already watched keeps the watch it has, so re-arming on every reattach cannot reset its+ grace. ``replace`` is for a new attempt under the same id (a rebound or retried Deep Research+ run), which must not inherit the previous attempt's grace. Safe from any thread; nothing here+ touches the loop.+ """+ if not attendance_id:+ return+ key = _key(account_id, attendance_id)+ with _LOCK:+ if key in _WATCHES and not replace:+ return+ _WATCHES[key] = _Watch(+ attendance_id = attendance_id,+ account_id = account_id or "",+ settled = settled,+ cancel = cancel,+ unattended_since = time.monotonic(),+ )+++def unwatch(attendance_id: str, account_id: str = "") -> None:+ """Let ``attendance_id`` run on unattended, e.g. a run id rebound to an attempt that keeps running."""+ with _LOCK:+ _WATCHES.pop(_key(account_id, attendance_id), None)+++def _drop(key: tuple[str, str], entry: _Watch) -> None:+ with _LOCK:+ # Only this entry: a run re-armed after it settled holds a newer one under the same key.+ if _WATCHES.get(key) is entry:+ del _WATCHES[key]+++async def check_once(now: float | None = None) -> list[str]:+ """One pass over the watched runs. Returns the attendance ids it stopped."""+ now = time.monotonic() if now is None else now+ with _LOCK:+ entries = list(_WATCHES.items())+ stopped: list[str] = []+ for key, entry in entries:+ try:+ if await asyncio.to_thread(entry.settled):+ _drop(key, entry)+ continue+ except Exception as exc:+ # A locked database or a deleted account must not end the watch for good.+ logger.warning("Unattended run check failed for %s: %s", entry.attendance_id, exc)+ continue+ if run_subscribers.is_attended(entry.attendance_id, entry.account_id):+ entry.unattended_since = now+ continue+ if now - entry.unattended_since < _GRACE_S:+ continue+ try:+ await entry.cancel()+ except Exception as exc:+ # Kept, so the next pass tries again: a lost writer-lock race must not let the run go on for good.+ logger.warning("Stopping unattended run %s failed: %s", entry.attendance_id, exc)+ continue+ _drop(key, entry)+ logger.info(+ "Stopped run %s: no tab has watched it for %.0fs", entry.attendance_id, _GRACE_S+ )+ stopped.append(entry.attendance_id)+ return stopped+++async def _run() -> None:+ while True:+ await asyncio.sleep(_CHECK_INTERVAL_S)+ try:+ await check_once()+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ logger.warning("Unattended run watchdog pass failed: %s", exc)+++def start() -> None:+ """Start the watchdog on the running loop. Idempotent within one lifespan."""+ global _task+ if _task is not None and not _task.done():+ return+ _task = asyncio.create_task(_run(), name = "unattended-run-watchdog")+++async def stop() -> None:+ global _task+ task, _task = _task, None+ if task is None or task.done():+ return+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+++def watched_for_tests(attendance_id: str, account_id: str = "") -> bool:+ with _LOCK:+ return _key(account_id, attendance_id) in _WATCHES+++def reset_for_tests() -> None:+ with _LOCK:+ _WATCHES.clear()diff --git a/studio/backend/storage/research_runs_db.py b/studio/backend/storage/research_runs_db.pyindex 6913733cc59..ebf41b3e519 100644--- a/studio/backend/storage/research_runs_db.py+++ b/studio/backend/storage/research_runs_db.py@@ -504,6 +504,20 @@ def list_active(thread_id: str) -> list[dict]:return [run for row in rows if (run := get_run(row["id"])) is not None]+def list_all_active() -> list[dict]:+ """Every unsettled run in this account, for startup work that is not scoped to one thread."""+ conn = get_connection()+ try:+ placeholders = ",".join("?" for _ in ACTIVE_STATUSES)+ rows = conn.execute(+ f"SELECT id FROM research_runs WHERE status IN ({placeholders}) ORDER BY created_at",+ tuple(sorted(ACTIVE_STATUSES)),+ ).fetchall()+ finally:+ conn.close()+ return [run for row in rows if (run := get_run(row["id"])) is not None]++def has_thread_claim(thread_id: str) -> bool:conn = get_connection()try:@@ -756,13 +770,23 @@ def approve(run_id: str, revision: int, plan_hash: str) -> str:conn.close()-def request_cancel(run_id: str) -> str:+def request_cancel(run_id: str, expected_attempt: int | None = None) -> str | None:+ """Stop ``run_id``. With ``expected_attempt``, only if that attempt is still the run's; else None.++ The attempt check shares the cancel's transaction, so a retry or rebind that commits first+ (both bump retry_count under the same id) can never be cancelled on its predecessor's behalf.+ """conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")- row = conn.execute("SELECT status FROM research_runs WHERE id = ?", (run_id,)).fetchone()+ row = conn.execute(+ "SELECT status, retry_count FROM research_runs WHERE id = ?", (run_id,)+ ).fetchone()if row is None:raise KeyError(run_id)+ if expected_attempt is not None and int(row["retry_count"] or 0) != expected_attempt:+ conn.commit()+ return Nonestatus = row["status"]if status in TERMINAL_STATUSES or status == "cancelling":conn.commit()diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.pyindex cd1bf98af56..1ecb6c3b042 100644--- a/studio/backend/tests/test_chat_settings_payload.py+++ b/studio/backend/tests/test_chat_settings_payload.py@@ -249,6 +249,13 @@ def test_auto_compact_settings_round_trip():}+def test_keep_running_when_tab_closed_round_trips_and_refuses_a_non_boolean():+ payload = ChatSettingsPayload.model_validate({"keepRunningWhenTabClosed": False})+ assert payload.model_dump(exclude_unset = True) == {"keepRunningWhenTabClosed": False}+ with pytest.raises(ValidationError):+ ChatSettingsPayload.model_validate({"keepRunningWhenTabClosed": "sometimes"})++def test_auto_compact_settings_can_inherit_the_server_policy():payload = ChatSettingsPayload.model_validate({"contextPolicy": "inherit"})assert payload.model_dump(exclude_unset = True) == {"contextPolicy": "inherit"}diff --git a/studio/backend/tests/test_unattended_runs.py b/studio/backend/tests/test_unattended_runs.pynew file mode 100644index 00000000000..d7806c10762--- /dev/null+++ b/studio/backend/tests/test_unattended_runs.py@@ -0,0 +1,386 @@+# 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 run whose owner chose "stop when I close the tab" ends once no tab follows it."""++import asyncio+import time+from types import SimpleNamespace++import pytest++from routes import chat_generation_runs as chat_routes+from routes import research_runs as research_routes+from state import run_subscribers, unattended_runs+from storage import chat_generation_runs_db as chat_db+from storage import research_runs_db as research_db+from storage import studio_db+from utils.account_context import current_account_id++[email protected](autouse = True)+def _clean_watchdog():+ unattended_runs.reset_for_tests()+ run_subscribers.reset_for_tests()+ yield+ unattended_runs.reset_for_tests()+ run_subscribers.reset_for_tests()+++def studio_home(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ studio_db.upsert_chat_thread(+ {+ "id": "thread-1",+ "title": "Chat",+ "modelType": "base",+ "modelId": "local-model",+ "createdAt": 1,+ }+ )+ studio_db.upsert_chat_message(+ {+ "id": "user-1",+ "threadId": "thread-1",+ "role": "user",+ "content": [{"type": "text", "text": "What changed?"}],+ "createdAt": 2,+ }+ )+ studio_db.upsert_chat_message(+ {+ "id": "assistant-1",+ "threadId": "thread-1",+ "parentId": "user-1",+ "role": "assistant",+ "content": [],+ "createdAt": 3,+ }+ )+ return tmp_path+++def _past_grace() -> float:+ return time.monotonic() + unattended_runs._GRACE_S + 1+++def _watch(attendance_id = "run-1", *, settled = False):+ cancelled: list[str] = []++ async def cancel():+ cancelled.append(attendance_id)++ unattended_runs.watch(attendance_id, settled = lambda: settled, cancel = cancel)+ return cancelled+++def test_an_unwatched_run_is_stopped_once_the_grace_runs_out():+ cancelled = _watch()+ assert asyncio.run(unattended_runs.check_once(time.monotonic())) == []+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == ["run-1"]+ assert cancelled == ["run-1"]+ assert not unattended_runs.watched_for_tests("run-1")+++def test_a_followed_run_keeps_going_and_its_grace_restarts_when_the_tab_goes():+ grace = unattended_runs._GRACE_S+ cancelled = _watch()+ run_subscribers.mark_subscriber_seen("run-1", "tab-a")+ seen_at = _past_grace()+ assert asyncio.run(unattended_runs.check_once(seen_at)) == []+ run_subscribers.subscriber_departed("run-1", "tab-a")+ # The grace counts from when the tab was last seen, not from when the run was watched.+ assert asyncio.run(unattended_runs.check_once(seen_at + grace / 2)) == []+ assert asyncio.run(unattended_runs.check_once(seen_at + grace + 1)) == ["run-1"]+ assert cancelled == ["run-1"]+++def test_another_tab_still_following_keeps_the_run():+ cancelled = _watch()+ run_subscribers.mark_subscriber_seen("run-1", "tab-a")+ run_subscribers.mark_subscriber_seen("run-1", "tab-b")+ run_subscribers.subscriber_departed("run-1", "tab-a")+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+ assert cancelled == []+++def test_a_settled_run_is_dropped_without_a_cancel():+ cancelled = _watch(settled = True)+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+ assert cancelled == []+ assert not unattended_runs.watched_for_tests("run-1")+++def test_rewatching_keeps_the_original_grace():+ first = _watch()+ second = _watch()+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == ["run-1"]+ assert first == ["run-1"] and second == []+++def test_watches_are_scoped_to_their_account():+ cancelled = []++ async def cancel():+ cancelled.append("alice")++ unattended_runs.watch("run-1", "alice", settled = lambda: False, cancel = cancel)+ # Bob following his own run-1 says nothing about Alice's.+ run_subscribers.mark_subscriber_seen("run-1", "tab-b", "bob")+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == ["run-1"]+ assert cancelled == ["alice"]+++def test_a_failed_cancel_keeps_the_watch_and_tries_again():+ attempts = []++ async def cancel():+ attempts.append(1)+ if len(attempts) == 1:+ raise RuntimeError("database is locked")++ unattended_runs.watch("run-1", settled = lambda: False, cancel = cancel)+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+ assert unattended_runs.watched_for_tests("run-1")+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == ["run-1"]+ assert len(attempts) == 2+ assert not unattended_runs.watched_for_tests("run-1")+++def test_a_replacing_watch_starts_a_fresh_grace_and_unwatch_ends_it():+ stale = _watch()+ # The first attempt has used up its grace by the time the second one is admitted.+ unattended_runs._WATCHES[("", "run-1")].unattended_since -= unattended_runs._GRACE_S + 1+ fresh: list[str] = []++ async def cancel():+ fresh.append("run-1")++ unattended_runs.watch("run-1", settled = lambda: False, cancel = cancel, replace = True)+ assert asyncio.run(unattended_runs.check_once(time.monotonic())) == []+ assert stale == [] and fresh == []+ unattended_runs.unwatch("run-1")+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+ assert stale == [] and fresh == []+++def test_a_failing_check_keeps_the_watch():+ def settled():+ raise RuntimeError("database is locked")++ async def cancel():+ raise AssertionError("must not cancel on a failed check")++ unattended_runs.watch("run-1", settled = settled, cancel = cancel)+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+ assert unattended_runs.watched_for_tests("run-1")+++def _research_payload(**overrides):+ payload = {+ "threadId": "thread-1",+ "userMessageId": "user-1",+ "inferenceRequest": {"model": "m"},+ }+ payload.update(overrides)+ return research_routes.CreateResearchRun(**payload)+++def test_research_config_records_the_choice_only_when_made():+ thread = {"modelId": "m"}+ assert "stopWhenUnattended" not in research_routes._sanitize_config(_research_payload(), thread)+ config = research_routes._sanitize_config(_research_payload(stopWhenUnattended = True), thread)+ assert config["stopWhenUnattended"] is True+++def _research_run(*, stop_when_unattended: bool):+ config = {+ "model": "local-model",+ "inferenceRequest": {"model": "local-model"},+ "budgets": {"maxSteps": 5, "maxSources": 15, "modelTimeoutSeconds": 30},+ }+ if stop_when_unattended:+ config["stopWhenUnattended"] = True+ return research_db.create_run(+ run_id = "run-1",+ owner_subject = "alice",+ thread_id = "thread-1",+ user_message_id = "user-1",+ assistant_message_id = "assistant-1",+ config = config,+ created_at = 10,+ )+++def _research_request():+ cancelled: list[str] = []+ request = SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(research_supervisor = SimpleNamespace(cancel = cancelled.append))+ )+ )+ return cancelled, request+++def test_research_left_running_is_not_watched(studio_home):+ _cancelled, request = _research_request()+ research_routes._watch_if_unattended_stop(+ request.app, _research_run(stop_when_unattended = False)+ )+ assert not unattended_runs.watched_for_tests("research:run-1", current_account_id() or "")+++def test_research_nobody_follows_is_cancelled(studio_home):+ cancelled, request = _research_request()+ research_routes._watch_if_unattended_stop(request.app, _research_run(stop_when_unattended = True))+ assert unattended_runs.watched_for_tests("research:run-1", current_account_id() or "")+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == ["research:run-1"]+ run = research_db.get_run("run-1")+ assert run["status"] in {"cancelling", "cancelled"}+ assert cancelled == (["run-1"] if run["status"] == "cancelling" else [])+++def test_followed_research_keeps_going(studio_home):+ cancelled, request = _research_request()+ research_routes._watch_if_unattended_stop(request.app, _research_run(stop_when_unattended = True))+ # Stamped the way the events stream stamps it, under the follower's account.+ run_subscribers.mark_subscriber_seen("research:run-1", "tab-a", current_account_id() or "")+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+ assert research_db.get_run("run-1")["status"] not in research_db.TERMINAL_STATUSES+ assert cancelled == []+++def _bump_attempt(run_id = "run-1"):+ # What retry and rebind_cancelled both do to a reused id, without the rest of either.+ conn = research_db.get_connection()+ try:+ conn.execute(+ "UPDATE research_runs SET retry_count = retry_count + 1 WHERE id = ?", (run_id,)+ )+ conn.commit()+ finally:+ conn.close()+++def test_research_cancel_only_stops_the_attempt_it_was_asked_about(studio_home):+ run = _research_run(stop_when_unattended = True)+ attempt = int(run["retryCount"] or 0)+ assert research_db.request_cancel("run-1", expected_attempt = attempt + 1) is None+ assert research_db.get_run("run-1")["status"] == run["status"]+ assert research_db.request_cancel("run-1", expected_attempt = attempt) in {+ "cancelling",+ "cancelled",+ }+++def test_an_obsolete_watch_cannot_cancel_the_attempt_that_replaced_it(studio_home):+ cancelled, request = _research_request()+ account = current_account_id() or ""+ research_routes._watch_if_unattended_stop(request.app, _research_run(stop_when_unattended = True))+ entry = unattended_runs._WATCHES[(account, "research:run-1")]+ # A retry commits after a pass has read settled() but before it awaits cancel().+ _bump_attempt()+ asyncio.run(entry.cancel())+ assert research_db.get_run("run-1")["status"] not in research_db.TERMINAL_STATUSES | {+ "cancelling"+ }+ assert cancelled == []+ # And a later pass reads the newer attempt as the end of this watch.+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+ assert not unattended_runs.watched_for_tests("research:run-1", account)+++def test_a_rebound_research_run_that_keeps_running_drops_the_old_watch(studio_home):+ _cancelled, request = _research_request()+ account = current_account_id() or ""+ research_routes._watch_if_unattended_stop(request.app, _research_run(stop_when_unattended = True))+ assert unattended_runs.watched_for_tests("research:run-1", account)+ # rebind_cancelled reuses the id; the new attempt keeps running, so the stale watch must go.+ rebound = {**research_db.get_run("run-1"), "config": {"model": "local-model"}}+ research_routes._watch_if_unattended_stop(request.app, rebound, replace = True)+ assert not unattended_runs.watched_for_tests("research:run-1", account)+++def test_startup_rearms_only_the_research_runs_that_asked_to_stop(studio_home):+ _cancelled, request = _research_request()+ _research_run(stop_when_unattended = True)+ account = current_account_id() or ""+ research_routes.rearm_unattended_research_runs(request.app)+ assert unattended_runs.watched_for_tests("research:run-1", account)+ # Nobody reconnects after the restart, so the resumed run still stops.+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == ["research:run-1"]+ assert research_db.get_run("run-1")["status"] in {"cancelling", "cancelled"}+++def test_startup_leaves_research_that_keeps_running_alone(studio_home):+ _cancelled, request = _research_request()+ _research_run(stop_when_unattended = False)+ research_routes.rearm_unattended_research_runs(request.app)+ assert not unattended_runs.watched_for_tests("research:run-1", current_account_id() or "")+++def test_chat_admission_takes_the_choice_and_defaults_to_running_on():+ base = {+ "runId": "run-1",+ "threadId": "thread-1",+ "userMessageId": "user-1",+ "assistantMessageId": "assistant-1",+ "requestPayload": {"model": "local-model", "messages": []},+ }+ assert chat_routes.CreateChatGenerationRun(**base).stopWhenUnattended is False+ assert chat_routes.CreateChatGenerationRun(**base, stopWhenUnattended = True).stopWhenUnattended+++def test_chat_run_nobody_follows_is_cancelled(studio_home):+ run, _created = chat_db.create_run(+ run_id = "run-1",+ owner_subject = "alice",+ thread_id = "thread-1",+ user_message_id = "user-1",+ assistant_message_id = "assistant-1",+ request_payload = {"model": "local-model", "messages": [], "stream": True},+ )+ assert run["status"] == "queued"+ cancelled: list[str] = []+ request = SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(+ chat_generation_supervisor = SimpleNamespace(cancel = cancelled.append)+ )+ )+ )+ chat_routes._watch_unattended(request, "run-1")+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == ["run-1"]+ assert chat_db.get_run("run-1")["status"] == "cancelled"+ assert cancelled == ["run-1"]+ # Settled, so a second pass has nothing left to stop.+ assert asyncio.run(unattended_runs.check_once(_past_grace())) == []+++def test_the_research_event_stream_counts_as_a_tab_following_the_run(studio_home):+ _cancelled, request = _research_request()+ run = _research_run(stop_when_unattended = True)++ async def is_disconnected():+ return False++ request.is_disconnected = is_disconnected+ account = current_account_id() or ""++ async def follow_once():+ response = await research_routes.research_events(+ run["id"], request, after = 0, last_event_id = None, current_subject = "alice"+ )+ frames = response.body_iterator+ await frames.__anext__()+ attended = run_subscribers.attendance_for_tests("research:run-1", account)+ await frames.aclose()+ return attended++ assert asyncio.run(follow_once()) == 1+ # Closing the stream lets the grace start now rather than when the stamp ages out.+ assert run_subscribers.attendance_for_tests("research:run-1", account) == 0+ # Attaching also arms the watch, which is how a run that outlived a restart gets one back.+ assert unattended_runs.watched_for_tests("research:run-1", account)diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 0330bcde5f6..e14a3b233d2 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -136,6 +136,7 @@ import {apiCompactionRequestFields,ggufCompactionRequestFields,} from "../utils/auto-compaction";+import { tabCloseRunFields } from "../utils/keep-running-when-tab-closed";import { resolveModelCatalogEntry } from "../model-catalog";import {lengthIncompleteReason,@@ -4916,6 +4917,7 @@ export function createOpenAIStreamAdapter(allowedDomains: [...runtime.researchWebsitePolicy.allowedDomains],blockedDomains: [...runtime.researchWebsitePolicy.blockedDomains],},+ ...tabCloseRunFields(runtime.keepRunningWhenTabClosed),});researchRunId = createdRun.id;if (researchStopRequested) {@@ -7216,6 +7218,9 @@ export function createOpenAIStreamAdapter(userMessageId: generationUserMessage!.id,assistantMessageId: unstable_assistantMessageId!,requestPayload,+ ...tabCloseRunFields(+ runtime.keepRunningWhenTabClosed,+ ),},runSignal,);diff --git a/studio/frontend/src/features/chat/api/chat-generation-api.ts b/studio/frontend/src/features/chat/api/chat-generation-api.tsindex b3485b8e490..2e4c0026fd5 100644--- a/studio/frontend/src/features/chat/api/chat-generation-api.ts+++ b/studio/frontend/src/features/chat/api/chat-generation-api.ts@@ -42,6 +42,8 @@ export interface CreateChatGenerationRunInput {userMessageId: string;assistantMessageId: string;requestPayload: OpenAIChatCompletionsRequest;+ /** Stop the run once no tab follows it, instead of finishing in the background. Sent only when set. */+ stopWhenUnattended?: boolean;}export interface ChatGenerationEvent {diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.tsindex d547722c7c0..101d7e4dee6 100644--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts@@ -80,6 +80,8 @@ export interface PersistedChatSettings {fitOnDeviceOnly?: boolean;/** Local GGUF chats: drop oldest turns instead of erroring at the window. */autoCompactEnabled?: boolean;+ /** Off: a reply or Deep Research run stops once no tab follows it, instead of finishing on the server. */+ keepRunningWhenTabClosed?: boolean;}interface ChatSettingsResponse {diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 6332d20b910..27989e01014 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -99,6 +99,7 @@ import {type QwenDefaultsMigration,} from "../utils/qwen-defaults-migration";import { DEFAULT_AUTO_COMPACT_ENABLED } from "../utils/auto-compaction";+import { DEFAULT_KEEP_RUNNING_WHEN_TAB_CLOSED } from "../utils/keep-running-when-tab-closed";import { preserveThinkingDefaultFromLoad } from "../lib/resolve-preserve-thinking-default";import {THREAD_SCOPED_PARAM_KEYS,@@ -2537,6 +2538,7 @@ type ChatRuntimeStore = {nudgeToolCalls: boolean;deduplicateToolCalls: boolean;autoCompactEnabled: boolean;+ keepRunningWhenTabClosed: boolean;maxToolCallsPerMessage: number;toolCallTimeout: number;kvCacheDtype: string | null;@@ -2837,6 +2839,7 @@ type ChatRuntimeStore = {setNudgeToolCalls: (enabled: boolean) => void;setDeduplicateToolCalls: (enabled: boolean) => void;setAutoCompactEnabled: (enabled: boolean) => void;+ setKeepRunningWhenTabClosed: (enabled: boolean) => void;setMaxToolCallsPerMessage: (value: number) => void;setToolCallTimeout: (value: number) => void;setGpuMemoryMode: (mode: "auto" | "manual") => void;@@ -2883,6 +2886,7 @@ type ScalarSettingKey =| "nudgeToolCalls"| "deduplicateToolCalls"| "autoCompactEnabled"+ | "keepRunningWhenTabClosed"| "maxToolCallsPerMessage"| "toolCallTimeout"| "reasoningEnabled"@@ -2935,6 +2939,7 @@ const SCALAR_SETTING_KEYS = ["nudgeToolCalls","deduplicateToolCalls","autoCompactEnabled",+ "keepRunningWhenTabClosed","maxToolCallsPerMessage","toolCallTimeout","reasoningEnabled",@@ -4394,6 +4399,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({nudgeToolCalls: true,deduplicateToolCalls: true,autoCompactEnabled: DEFAULT_AUTO_COMPACT_ENABLED,+ keepRunningWhenTabClosed: DEFAULT_KEEP_RUNNING_WHEN_TAB_CLOSED,maxToolCallsPerMessage: 25,toolCallTimeout: 5,kvCacheDtype: null,@@ -6103,6 +6109,18 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}),+ setKeepRunningWhenTabClosed: (keepRunningWhenTabClosed) =>+ set((state) => {+ setScalarSettingVersion(+ "keepRunningWhenTabClosed",+ keepRunningWhenTabClosed,+ state.keepRunningWhenTabClosed,+ );+ return {+ keepRunningWhenTabClosed,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),setMaxToolCallsPerMessage: (maxToolCallsPerMessage) =>set((state) => {setScalarSettingVersion(diff --git a/studio/frontend/src/features/chat/types/research.ts b/studio/frontend/src/features/chat/types/research.tsindex aab24b9da7a..b0e8edc5c43 100644--- a/studio/frontend/src/features/chat/types/research.ts+++ b/studio/frontend/src/features/chat/types/research.ts@@ -114,6 +114,8 @@ export interface CreateResearchRunInput {instructions?: string;/** research the question handed off by the model. */question?: string;+ /** Stop the run once no tab follows it, instead of finishing in the background. Sent only when set. */+ stopWhenUnattended?: boolean;}export interface ResearchRun {diff --git a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts b/studio/frontend/src/features/chat/utils/chat-settings-storage.tsindex a7ab63cf135..304eea60c90 100644--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts@@ -300,6 +300,7 @@ export function sanitizeChatSettings(value: unknown): PersistedChatSettings {const nudgeToolCalls = sanitizeBool(value.nudgeToolCalls);const deduplicateToolCalls = sanitizeBool(value.deduplicateToolCalls);const autoCompactEnabled = sanitizeBool(value.autoCompactEnabled);+ const keepRunningWhenTabClosed = sanitizeBool(value.keepRunningWhenTabClosed);const maxToolCallsPerMessage = sanitizeInt(value.maxToolCallsPerMessage, 0);const toolCallTimeout = sanitizeInt(value.toolCallTimeout, 1);@@ -337,6 +338,9 @@ export function sanitizeChatSettings(value: unknown): PersistedChatSettings {if (autoCompactEnabled !== undefined) {settings.autoCompactEnabled = autoCompactEnabled;}+ if (keepRunningWhenTabClosed !== undefined) {+ settings.keepRunningWhenTabClosed = keepRunningWhenTabClosed;+ }if (maxToolCallsPerMessage !== undefined) {settings.maxToolCallsPerMessage = maxToolCallsPerMessage;}@@ -403,6 +407,7 @@ export function isEmptyChatSettings(settings: PersistedChatSettings): boolean {settings.nudgeToolCalls === undefined &&settings.deduplicateToolCalls === undefined &&settings.autoCompactEnabled === undefined &&+ settings.keepRunningWhenTabClosed === undefined &&settings.maxToolCallsPerMessage === undefined &&settings.toolCallTimeout === undefined &&hasNoMirroredSettings(settings)diff --git a/studio/frontend/src/features/chat/utils/keep-running-when-tab-closed.ts b/studio/frontend/src/features/chat/utils/keep-running-when-tab-closed.tsnew file mode 100644index 00000000000..ce58dc8b4ac--- /dev/null+++ b/studio/frontend/src/features/chat/utils/keep-running-when-tab-closed.ts@@ -0,0 +1,18 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** On: a reply or Deep Research run outlives its tab, which is what a long research run needs. */+export const DEFAULT_KEEP_RUNNING_WHEN_TAB_CLOSED = true;++/**+ * What a durable chat or Deep Research run is admitted with for "Keep running after the tab closes".+ *+ * Off asks the server to stop the run once no tab has followed it for a while (backend+ * state/unattended_runs.py), so a reload or a second tab still keeps it. On sends nothing, which+ * keeps admission exactly what it was before the setting existed.+ */+export function tabCloseRunFields(keepRunningWhenTabClosed: boolean): {+ stopWhenUnattended?: true;+} {+ return keepRunningWhenTabClosed ? {} : { stopWhenUnattended: true };+}diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.tsindex 133d5b95a2a..0a0e90b8ceb 100644--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts@@ -49,6 +49,8 @@ const QUEUED_SETTING_KEYS = ["maxToolCallsPerMessage","toolCallTimeout","autoCompactEnabled",+ // A queued send keeps the tab-close choice it was sent with, like every setting above.+ "keepRunningWhenTabClosed",] as const;type ChatRuntimeState = ReturnType<typeof useChatRuntimeStore.getState>;diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 90b6f78f5da..39703f069a5 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -128,6 +128,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.chat.projectAttachments","settings.chat.rememberParamsPerModel","settings.chat.autoCompact",+ "settings.chat.keepRunningWhenTabClosed","settings.chat.toolResultLimit","settings.chat.firstTokenLabel","settings.chat.autoScroll",@@ -437,6 +438,8 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<"settings.resources.modelMemory.noRamReserve":"settings.resources.modelMemory.modelMemoryKeywords","settings.chat.autoCompact": "settings.chat.autoCompactKeywords",+ "settings.chat.keepRunningWhenTabClosed":+ "settings.chat.keepRunningWhenTabClosedKeywords","settings.chat.firstTokenLabel": "settings.chat.firstTokenKeywords","settings.chat.toolResultLimit": "settings.chat.toolResultLimitKeywords",// match action verbs omitted from these descriptive labels.diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsxindex 73f71fc6a48..a5a0cf137c1 100644--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx@@ -305,6 +305,12 @@ export function ChatTab() {const setAutoCompactEnabled = useChatRuntimeStore((state) => state.setAutoCompactEnabled,);+ const keepRunningWhenTabClosed = useChatRuntimeStore(+ (state) => state.keepRunningWhenTabClosed,+ );+ const setKeepRunningWhenTabClosed = useChatRuntimeStore(+ (state) => state.setKeepRunningWhenTabClosed,+ );const showGreetingSloth = useUserProfileStore((s) => s.showGreetingSloth);const setShowGreetingSloth = useUserProfileStore((s) => s.setShowGreetingSloth,@@ -530,6 +536,17 @@ export function ChatTab() {onCheckedChange={setAutoCompactEnabled}/></SettingsRow>+ <SettingsRow+ label={t("settings.chat.keepRunningWhenTabClosed")}+ description={t("settings.chat.keepRunningWhenTabClosedDescription")}+ hint={t("settings.chat.keepRunningWhenTabClosedHint")}+ >+ <Switch+ aria-label={t("settings.chat.keepRunningWhenTabClosed")}+ checked={keepRunningWhenTabClosed}+ onCheckedChange={setKeepRunningWhenTabClosed}+ />+ </SettingsRow>{isOwner ? <ToolResultLimitRow /> : null}{isOwner ? <FirstTokenTimeoutRow /> : null}<SettingsRowdiff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex f9557c26a4e..204c2862069 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -2673,6 +2673,13 @@ export const ar = {"تنتقل الأدوار الأقدم إلى أرشيف قابل للبحث عندما تمتلئ نافذة سياق المحادثة.",autoCompactKeywords:"ضغط تلقائي سياق نافذة اقتطاع منزلقة نقطة تحقق هامش أرشيف استرجاع بحث compaction rolling checkpoint headroom archive retrieval rag",+ keepRunningWhenTabClosed: "مواصلة التشغيل بعد إغلاق علامة التبويب",+ keepRunningWhenTabClosedDescription:+ "تستمر الردود والبحث على الويب وDeep Research على الخادم بعد إغلاق علامة التبويب. أوقف هذا الخيار لإيقافها بدلًا من ذلك.",+ keepRunningWhenTabClosedHint:+ "أعد فتح المحادثة على أي جهاز لمتابعة تشغيل استمر. عند إيقاف هذا الخيار، يتوقف التشغيل خلال دقيقة تقريبًا من إغلاق آخر علامة تبويب له، لذا لا توقفه إعادة التحميل. ينطبق على عمليات التشغيل التي تبدأ بعد التغيير. المحادثات المؤقتة، والردود من نماذج API أو على المرفقات، والأدوار التي تستخدم لوحة المتصفح تتوقف دائمًا مع علامة التبويب الخاصة بها.",+ keepRunningWhenTabClosedKeywords:+ "خلفية علامة تبويب إغلاق مغلقة مغادرة مواصلة التشغيل استمرار إيقاف إلغاء بحث الويب جهاز هاتف background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "حد انتظار أول رمز",firstTokenDescription: "المدة التي يمكن لنماذج GGUF المحلية انتظارها دون تقدم في معالجة الطلب قبل أول رمز. يسري على فترات الانتظار الجديدة لجميع الحسابات. مع «غير محدود» يستمر الانتظار حتى توقفه بنفسك.",firstTokenDefault: "20 دقيقة (افتراضي)",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex d0e94986eb1..05fd23043d2 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -2713,6 +2713,13 @@ export const de = {"Ältere Runden wandern in ein durchsuchbares Archiv, wenn ein Chat voll läuft.",autoCompactKeywords:"Komprimierung automatisch Kontext Fenster kürzen gleitend Prüfpunkt Reserve Archiv Abruf Suche compaction rolling checkpoint headroom archive retrieval rag",+ keepRunningWhenTabClosed: "Nach dem Schließen des Tabs weiterlaufen",+ keepRunningWhenTabClosedDescription:+ "Antworten, Websuche und Deep Research laufen auf dem Server weiter, wenn der Tab geschlossen wird. Ausschalten, um sie stattdessen zu stoppen.",+ keepRunningWhenTabClosedHint:+ "Öffne den Chat auf einem beliebigen Gerät erneut, um einen weitergelaufenen Lauf aufzugreifen. Wenn ausgeschaltet, stoppt ein Lauf etwa eine Minute nachdem sein letzter Tab geschlossen wurde, sodass ein Neuladen ihn nicht stoppt. Gilt für Läufe, die nach der Änderung gestartet werden. Temporäre Chats, Antworten von API-Modellen oder auf Anhänge und Schritte mit dem Browser-Panel stoppen immer mit ihrem Tab.",+ keepRunningWhenTabClosedKeywords:+ "Hintergrund Tab schließen geschlossen verlassen weiterlaufen fortsetzen stoppen abbrechen Websuche Gerät Handy background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "Wartelimit für das erste Token",firstTokenDescription: "Wie lange lokale GGUF-Modelle ohne Fortschritt bei der Prompt-Verarbeitung auf das erste Token warten dürfen. Gilt für neue Wartezeiten aller Konten. Bei „Unbegrenzt“ wird gewartet, bis du stoppst.",firstTokenDefault: "20 Min. (Standard)",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 7a459d0e59b..8bef26755e8 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2722,6 +2722,13 @@ export const en = {"Older turns move to a searchable archive when a chat fills its context.",autoCompactKeywords:"compaction compact auto-compact context window truncate rolling checkpoint headroom archive retrieval recall rag search",+ keepRunningWhenTabClosed: "Keep running after the tab closes",+ keepRunningWhenTabClosedDescription:+ "Replies, web search, and Deep Research keep going on the server after the tab closes. Turn off to stop them instead.",+ keepRunningWhenTabClosedHint:+ "Reopen the chat on any device to pick up a run that kept going. When off, a run stops within about a minute of its last tab closing, so a reload does not stop it. Applies to runs started after you change this. Temporary chats, replies from API models or to attachments, and turns that use the browser panel always stop with their tab.",+ keepRunningWhenTabClosedKeywords:+ "background tab close closed leave keep running continue stop cancel deep research web search resume reconnect device phone",firstTokenLabel: "First-token waiting limit",firstTokenDescription: "How long local GGUF models may wait without prompt-processing progress before the first token. Applies to new waits for all accounts. Unlimited keeps waiting until you stop.",firstTokenDefault: "20 min (default)",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 0c7a1de7033..8af0cfee4dc 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -2704,6 +2704,13 @@ export const es = {"Los turnos antiguos pasan a un archivo consultable al llenarse el contexto de un chat.",autoCompactKeywords:"compactación compactar automáticamente contexto ventana truncar deslizante checkpoint margen archivo recuperación búsqueda compaction rolling headroom archive retrieval rag",+ keepRunningWhenTabClosed: "Seguir ejecutándose al cerrar la pestaña",+ keepRunningWhenTabClosedDescription:+ "Las respuestas, la búsqueda web y Deep Research siguen en el servidor después de cerrar la pestaña. Desactívalo para detenerlas.",+ keepRunningWhenTabClosedHint:+ "Vuelve a abrir el chat en cualquier dispositivo para retomar una ejecución que siguió en marcha. Si está desactivado, una ejecución se detiene alrededor de un minuto después de cerrarse su última pestaña, así que recargar no la detiene. Se aplica a las ejecuciones iniciadas después de cambiarlo. Los chats temporales, las respuestas de modelos de API o a archivos adjuntos y los turnos que usan el panel del navegador siempre se detienen con su pestaña.",+ keepRunningWhenTabClosedKeywords:+ "segundo plano pestaña cerrar cerrada salir seguir ejecutando continuar detener cancelar búsqueda web dispositivo teléfono background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "Límite de espera del primer token",firstTokenDescription: "Cuánto pueden esperar los modelos GGUF locales sin avance en el procesamiento del prompt antes del primer token. Se aplica a las nuevas esperas de todas las cuentas. Con «Sin límite» se espera hasta que lo detengas.",firstTokenDefault: "20 min (predeterminado)",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 9b3cb29e8c6..db19ca43bf2 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -2710,6 +2710,13 @@ export const fr = {"Les anciens échanges vont dans une archive consultable quand un chat sature son contexte.",autoCompactKeywords:"compaction automatique contexte fenêtre tronquer glissante point de contrôle marge archive récupération recherche rolling checkpoint headroom retrieval rag",+ keepRunningWhenTabClosed: "Continuer après la fermeture de l’onglet",+ keepRunningWhenTabClosedDescription:+ "Les réponses, la recherche web et Deep Research continuent sur le serveur après la fermeture de l’onglet. Désactivez pour les arrêter à la place.",+ keepRunningWhenTabClosedHint:+ "Rouvrez la conversation sur n’importe quel appareil pour retrouver une exécution qui a continué. Désactivé, une exécution s’arrête environ une minute après la fermeture de son dernier onglet, donc un rechargement ne l’arrête pas. S’applique aux exécutions lancées après la modification. Les conversations temporaires, les réponses des modèles API ou à des pièces jointes et les tours qui utilisent le panneau du navigateur s’arrêtent toujours avec leur onglet.",+ keepRunningWhenTabClosedKeywords:+ "arrière-plan onglet fermer fermé quitter continuer arrêter annuler recherche web appareil téléphone background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "Limite d’attente du premier jeton",firstTokenDescription: "Durée pendant laquelle les modèles GGUF locaux peuvent attendre le premier jeton sans progression du traitement du prompt. S’applique aux nouvelles attentes de tous les comptes. Avec « Illimité », l’attente continue jusqu’à ce que vous arrêtiez.",firstTokenDefault: "20 min (par défaut)",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 2f8cbd697ca..e172f570536 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -2788,6 +2788,13 @@ export const he = {"סבבים ישנים יותר עוברים לארכיון הניתן לחיפוש כאשר צ'אט ממלא את ההקשר שלו.",autoCompactKeywords:"compaction compact auto-compact context window truncate rolling checkpoint headroom archive retrieval recall rag search כיווץ קיצוץ הקשר חלון ארכיון אחזור חיפוש",+ keepRunningWhenTabClosed: "להמשיך לרוץ אחרי סגירת הכרטיסייה",+ keepRunningWhenTabClosedDescription:+ "תשובות, חיפוש באינטרנט ו-Deep Research ממשיכים לרוץ בשרת אחרי שהכרטיסייה נסגרת. כבו כדי לעצור אותם במקום זאת.",+ keepRunningWhenTabClosedHint:+ "פתחו מחדש את הצ'אט בכל מכשיר כדי לחזור להרצה שהמשיכה. כשהאפשרות כבויה, הרצה נעצרת בתוך כדקה מסגירת הכרטיסייה האחרונה שלה, כך שטעינה מחדש לא עוצרת אותה. חל על הרצות שמתחילות אחרי השינוי. צ'אטים זמניים, תשובות ממודלי API או לקבצים מצורפים, ותורות שמשתמשים בחלונית הדפדפן תמיד נעצרים יחד עם הכרטיסייה שלהם.",+ keepRunningWhenTabClosedKeywords:+ "רקע כרטיסייה סגירה סגורה עזיבה להמשיך לרוץ המשך עצירה ביטול חיפוש באינטרנט מכשיר טלפון background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "מגבלת המתנה לטוקן הראשון",firstTokenDescription: "כמה זמן מודלי GGUF מקומיים רשאים להמתין ללא התקדמות בעיבוד הפרומפט לפני הטוקן הראשון. חל על המתנות חדשות בכל החשבונות. במצב ״ללא הגבלה״ ההמתנה נמשכת עד שתעצרו.",firstTokenDefault: "20 דק׳ (ברירת מחדל)",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 5c790bf590f..69f1f184899 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -2682,6 +2682,13 @@ export const hi = {"चैट का कॉन्टेक्स्ट भरने पर पुराने टर्न खोजे जा सकने वाले आर्काइव में चले जाते हैं।",autoCompactKeywords:"कॉम्पैक्शन कॉम्पैक्ट कॉन्टेक्स्ट विंडो ट्रंकेट स्लाइडिंग चेकपॉइंट हेडरूम आर्काइव पुनर्प्राप्ति खोज compaction rolling checkpoint headroom archive retrieval rag",+ keepRunningWhenTabClosed: "टैब बंद होने के बाद भी चलते रहें",+ keepRunningWhenTabClosedDescription:+ "टैब बंद होने के बाद भी जवाब, वेब खोज और Deep Research सर्वर पर चलते रहते हैं। इसके बजाय उन्हें रोकने के लिए बंद करें।",+ keepRunningWhenTabClosedHint:+ "जो रन चलता रहा, उसे देखने के लिए किसी भी डिवाइस पर चैट फिर से खोलें। बंद होने पर, रन अपने आख़िरी टैब के बंद होने के लगभग एक मिनट के भीतर रुक जाता है, इसलिए रीलोड करने से वह नहीं रुकता। यह बदलाव के बाद शुरू किए गए रन पर लागू होता है। अस्थायी चैट, API मॉडल के जवाब या अटैचमेंट के जवाब, और ब्राउज़र पैनल इस्तेमाल करने वाले टर्न हमेशा अपने टैब के साथ रुकते हैं।",+ keepRunningWhenTabClosedKeywords:+ "बैकग्राउंड टैब बंद छोड़ना चलते रहें जारी रोकें रद्द वेब खोज डिवाइस फ़ोन background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "पहले टोकन की प्रतीक्षा सीमा",firstTokenDescription: "पहले टोकन से पहले, प्रॉम्प्ट प्रोसेसिंग में कोई प्रगति न होने पर स्थानीय GGUF मॉडल कितनी देर प्रतीक्षा कर सकते हैं। सभी खातों की नई प्रतीक्षाओं पर लागू होता है। असीमित चुनने पर प्रतीक्षा तब तक चलती है जब तक आप रोक न दें।",firstTokenDefault: "20 मिनट (डिफ़ॉल्ट)",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex d9b5d1738f8..f1d68cba976 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -2618,6 +2618,13 @@ export const it = {"I turni più vecchi passano in un archivio consultabile quando una chat riempie il contesto.",autoCompactKeywords:"compattazione automatica contesto finestra troncare scorrevole checkpoint margine archivio recupero ricerca compaction rolling headroom archive retrieval rag",+ keepRunningWhenTabClosed: "Continua dopo la chiusura della scheda",+ keepRunningWhenTabClosedDescription:+ "Risposte, ricerca web e Deep Research continuano sul server dopo la chiusura della scheda. Disattiva per fermarle invece.",+ keepRunningWhenTabClosedHint:+ "Riapri la chat su qualsiasi dispositivo per riprendere un'esecuzione che è andata avanti. Se disattivato, un'esecuzione si ferma circa un minuto dopo la chiusura della sua ultima scheda, quindi un ricaricamento non la ferma. Vale per le esecuzioni avviate dopo la modifica. Le chat temporanee, le risposte dei modelli API o agli allegati e i turni che usano il pannello del browser si fermano sempre con la loro scheda.",+ keepRunningWhenTabClosedKeywords:+ "background scheda chiudere chiusa uscire continuare fermare annullare ricerca web dispositivo telefono tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "Limite di attesa del primo token",firstTokenDescription: "Per quanto tempo i modelli GGUF locali possono attendere il primo token senza progressi nell’elaborazione del prompt. Si applica alle nuove attese di tutti gli account. Con «Illimitato» l’attesa continua finché non interrompi.",firstTokenDefault: "20 min (predefinito)",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex fd6a72a8d8b..4bb7828ac77 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -2655,6 +2655,13 @@ export const ja = {"チャットの文脈が満杯になると、古いターンは検索可能なアーカイブに移ります。",autoCompactKeywords:"圧縮 自動圧縮 コンテキスト ウィンドウ 切り詰め スライディング チェックポイント 余裕 アーカイブ 検索 取得 compaction rolling headroom archive retrieval rag",+ keepRunningWhenTabClosed: "タブを閉じた後も実行を続ける",+ keepRunningWhenTabClosedDescription:+ "タブを閉じた後も、応答、ウェブ検索、Deep Research はサーバーで続行されます。オフにすると代わりに停止します。",+ keepRunningWhenTabClosedHint:+ "続行された実行は、どのデバイスでもチャットを開き直すと確認できます。オフの場合、最後のタブが閉じてから約 1 分以内に実行が停止するため、再読み込みでは停止しません。変更後に開始した実行に適用されます。一時チャット、API モデルからの応答や添付ファイルへの応答、ブラウザーパネルを使うターンは常にタブと一緒に停止します。",+ keepRunningWhenTabClosedKeywords:+ "バックグラウンド タブ 閉じる 離れる 実行を続ける 継続 停止 キャンセル ウェブ検索 デバイス スマートフォン background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "最初のトークンの待機上限",firstTokenDescription: "ローカル GGUF モデルが、プロンプト処理の進捗がないまま最初のトークンを待てる時間です。すべてのアカウントの新しい待機に適用されます。「無制限」では停止するまで待ち続けます。",firstTokenDefault: "20 分(既定)",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 78780407afe..f88637b4e1c 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -2664,6 +2664,13 @@ export const ko = {"채팅이 컨텍스트를 모두 채우면 오래된 턴은 검색 가능한 보관소로 옮겨집니다.",autoCompactKeywords:"압축 자동 컨텍스트 윈도우 자르기 슬라이딩 체크포인트 여유 보관 검색 회수 compaction rolling checkpoint headroom archive retrieval rag",+ keepRunningWhenTabClosed: "탭을 닫은 후에도 계속 실행",+ keepRunningWhenTabClosedDescription:+ "탭을 닫은 후에도 응답, 웹 검색, Deep Research가 서버에서 계속됩니다. 끄면 대신 중지됩니다.",+ keepRunningWhenTabClosedHint:+ "계속 실행된 작업은 어느 기기에서든 채팅을 다시 열어 이어서 볼 수 있습니다. 끄면 마지막 탭이 닫히고 약 1분 안에 실행이 중지되므로 새로고침으로는 중지되지 않습니다. 변경한 뒤 시작한 실행에 적용됩니다. 임시 채팅, API 모델의 응답이나 첨부 파일에 대한 응답, 브라우저 패널을 사용하는 턴은 항상 탭과 함께 중지됩니다.",+ keepRunningWhenTabClosedKeywords:+ "백그라운드 탭 닫기 닫힘 나가기 계속 실행 중지 취소 웹 검색 기기 휴대폰 background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "첫 토큰 대기 한도",firstTokenDescription: "로컬 GGUF 모델이 프롬프트 처리 진행 없이 첫 토큰을 기다릴 수 있는 시간입니다. 모든 계정의 새 대기에 적용됩니다. 무제한은 중지할 때까지 계속 기다립니다.",firstTokenDefault: "20분 (기본값)",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex fcb0cad29c0..c8781c03fda 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -2691,6 +2691,13 @@ export const ptBR = {"Os turnos antigos vão para um arquivo pesquisável quando um chat enche o contexto.",autoCompactKeywords:"compactação compactar automaticamente contexto janela truncar deslizante checkpoint margem arquivo recuperação busca compaction rolling headroom archive retrieval rag",+ keepRunningWhenTabClosed: "Continuar após fechar a aba",+ keepRunningWhenTabClosedDescription:+ "Respostas, pesquisa na web e Deep Research continuam no servidor depois que a aba é fechada. Desative para pará-las.",+ keepRunningWhenTabClosedHint:+ "Reabra o chat em qualquer dispositivo para retomar uma execução que continuou. Desativado, uma execução para cerca de um minuto depois que sua última aba é fechada, então recarregar não a interrompe. Vale para execuções iniciadas depois da mudança. Chats temporários, respostas de modelos de API ou a anexos e turnos que usam o painel do navegador sempre param com a aba.",+ keepRunningWhenTabClosedKeywords:+ "segundo plano aba fechar fechada sair continuar parar cancelar pesquisa web dispositivo celular background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "Limite de espera do primeiro token",firstTokenDescription: "Por quanto tempo os modelos GGUF locais podem esperar o primeiro token sem progresso no processamento do prompt. Vale para as novas esperas de todas as contas. Com “Ilimitado”, a espera continua até você parar.",firstTokenDefault: "20 min (padrão)",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 727cf425f24..4d8de89e1df 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -2688,6 +2688,13 @@ export const ru = {"Старые ходы уходят в доступный для поиска архив, когда чат заполняет контекст.",autoCompactKeywords:"сжатие автоматически контекст окно обрезка скользящее контрольная точка запас архив поиск извлечение compaction rolling checkpoint headroom archive retrieval rag",+ keepRunningWhenTabClosed: "Продолжать после закрытия вкладки",+ keepRunningWhenTabClosedDescription:+ "Ответы, веб-поиск и Deep Research продолжаются на сервере после закрытия вкладки. Выключите, чтобы вместо этого останавливать их.",+ keepRunningWhenTabClosedHint:+ "Откройте чат снова на любом устройстве, чтобы вернуться к продолжившемуся запуску. Если выключено, запуск останавливается примерно через минуту после закрытия его последней вкладки, поэтому перезагрузка страницы его не останавливает. Действует для запусков, начатых после изменения. Временные чаты, ответы API-моделей или на вложения и шаги с панелью браузера всегда останавливаются вместе со своей вкладкой.",+ keepRunningWhenTabClosedKeywords:+ "фон вкладка закрыть закрыта уйти продолжать работу остановить отменить веб-поиск устройство телефон background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "Лимит ожидания первого токена",firstTokenDescription: "Сколько локальные модели GGUF могут ждать первый токен без прогресса обработки промпта. Применяется к новым ожиданиям для всех учётных записей. В режиме «Без ограничений» ожидание длится, пока вы не остановите его.",firstTokenDefault: "20 мин (по умолчанию)",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 09a67f63005..f02f1b771b2 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -2873,6 +2873,13 @@ export const sv = {"Äldre turer flyttas till ett sökbart arkiv när en chatt fyller sin kontext.",autoCompactKeywords:"komprimering komprimera autokomprimering kontextfönster trunkera rullande kontrollpunkt marginal arkiv hämtning återkallning rag sök compaction compact auto-compact context window truncate rolling checkpoint headroom archive retrieval recall search",+ keepRunningWhenTabClosed: "Fortsätt när fliken stängs",+ keepRunningWhenTabClosedDescription:+ "Svar, webbsökning och Deep Research fortsätter på servern när fliken stängs. Stäng av för att stoppa dem i stället.",+ keepRunningWhenTabClosedHint:+ "Öppna chatten igen på valfri enhet för att återuppta en körning som fortsatte. När det är av stoppas en körning ungefär en minut efter att dess sista flik stängts, så en omladdning stoppar den inte. Gäller körningar som startas efter ändringen. Tillfälliga chattar, svar från API-modeller eller på bilagor och turer som använder webbläsarpanelen stoppas alltid med sin flik.",+ keepRunningWhenTabClosedKeywords:+ "bakgrund flik stäng stängd lämna fortsätt köra stoppa avbryt webbsökning enhet telefon background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "Väntegräns för första token",firstTokenDescription: "Hur länge lokala GGUF-modeller får vänta på första token utan framsteg i promptbearbetningen. Gäller nya väntetider för alla konton. Med Obegränsad fortsätter väntan tills du stoppar.",firstTokenDefault: "20 min (standard)",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 92395edf930..a7a141a65ee 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2631,6 +2631,13 @@ export const zhCN = {"聊天填满上下文时,较早的轮次会转入可检索的归档。",autoCompactKeywords:"压缩 自动压缩 上下文 窗口 截断 滑动 检查点 余量 归档 检索 搜索 compaction rolling checkpoint headroom archive retrieval rag",+ keepRunningWhenTabClosed: "关闭标签页后继续运行",+ keepRunningWhenTabClosedDescription:+ "关闭标签页后,回复、网页搜索和 Deep Research 会继续在服务器上运行。关闭此项则改为停止它们。",+ keepRunningWhenTabClosedHint:+ "在任意设备上重新打开聊天即可查看继续运行的任务。关闭此项时,任务会在最后一个标签页关闭后约一分钟内停止,因此刷新页面不会停止它。仅适用于更改后开始的任务。临时聊天、API 模型的回复或针对附件的回复,以及使用浏览器面板的回合,始终随标签页一起停止。",+ keepRunningWhenTabClosedKeywords:+ "后台 标签页 关闭 离开 继续运行 停止 取消 网页搜索 设备 手机 background tab close keep running continue stop cancel deep research web search resume",firstTokenLabel: "首个 token 等待上限",firstTokenDescription: "本地 GGUF 模型在提示词处理没有进展时,最多可等待首个 token 多久。适用于所有账户的新等待。选择“无限制”会一直等待,直到你手动停止。",firstTokenDefault: "20 分钟(默认)",diff --git a/studio/frontend/tests/keep-running-when-tab-closed.test.ts b/studio/frontend/tests/keep-running-when-tab-closed.test.tsnew file mode 100644index 00000000000..3f6c50f424b--- /dev/null+++ b/studio/frontend/tests/keep-running-when-tab-closed.test.ts@@ -0,0 +1,69 @@+// 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 test from "node:test";++import {+ DEFAULT_KEEP_RUNNING_WHEN_TAB_CLOSED,+ tabCloseRunFields,+} from "../src/features/chat/utils/keep-running-when-tab-closed.ts";+import {+ installLocalStorageFake,+ readSrc,+ registerStoreStubResolver,+} from "./helpers/kit.ts";++registerStoreStubResolver();+installLocalStorageFake();++const { sanitizeChatSettings, isEmptyChatSettings } = await import(+ "../src/features/chat/utils/chat-settings-storage.ts"+);+const { snapshotQueuedChatRunSettings } = await import(+ "../src/features/chat/utils/queued-chat-run-settings.ts"+);++test("runs keep going after the tab closes unless the setting says otherwise", () => {+ assert.equal(DEFAULT_KEEP_RUNNING_WHEN_TAB_CLOSED, true);+ // On sends nothing, so admission is what it was before the setting existed.+ assert.deepEqual(tabCloseRunFields(true), {});+ assert.deepEqual(tabCloseRunFields(false), { stopWhenUnattended: true });+});++test("the setting survives the round trip through stored settings", () => {+ assert.deepEqual(sanitizeChatSettings({ keepRunningWhenTabClosed: false }), {+ keepRunningWhenTabClosed: false,+ });+ assert.deepEqual(sanitizeChatSettings({ keepRunningWhenTabClosed: "no" }), {});+ assert.equal(isEmptyChatSettings({ keepRunningWhenTabClosed: false }), false);+});++test("both durable admissions carry the choice", () => {+ const adapter = readSrc("features/chat/api/chat-adapter.ts");+ const uses = adapter.match(+ /\.\.\.tabCloseRunFields\(\s*runtime\.keepRunningWhenTabClosed,?\s*\)/g,+ );+ // One for createResearchRun, one for createChatGenerationRunUntilAbort.+ assert.equal(uses?.length, 2);+});++test("a queued send keeps the choice it was sent with", () => {+ const state = {+ params: {},+ keepRunningWhenTabClosed: false,+ } as unknown as Parameters<typeof snapshotQueuedChatRunSettings>[0];+ assert.equal(+ snapshotQueuedChatRunSettings(state).keepRunningWhenTabClosed,+ false,+ );+ // Flipping it while a send waits must count as a settings change, like the settings beside it.+ const store = readSrc("features/chat/stores/chat-runtime-store.ts");+ const setter = store.slice(+ store.indexOf("setKeepRunningWhenTabClosed: (keepRunningWhenTabClosed) =>"),+ );+ assert.match(+ setter.slice(0, setter.indexOf("}),")),+ /queuedSettingsEpoch: state\.queuedSettingsEpoch \+ 1/,+ );+});