Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Allow unlimited Deep Research time budgets (#9078)

alkinun41b93a9169ab
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index 9dbe49c7e62..1379fff7049 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -19,6 +19,7 @@ from typing import Any, AsyncIterator, Callable
import httpx
from auth import storage as auth_storage
+from core.inference.llama_admission import llama_admission_config_from_env
from core.inference.message_content import message_text_with_pastes
from core.inference.tool_loop_controller import is_tool_error, strip_result_for_model
from core.inference.tools import EMPTY_SEARCH_RESULTS, RAG_SOURCES_SENTINEL, execute_tool
@@ -114,6 +115,22 @@ _STREAM_CLEANUP_TIMEOUT_SECONDS = 5.0
# The SSE comment routes/inference.py sends while queued, not while the backend is silent.
_ADMISSION_WAIT_COMMENT = ": admission-wait"
_ADMISSION_DONE_COMMENT = ": admission-done"
+# Queue notices arrive on the configured heartbeat, so allow for a few missed ones.
+_ADMISSION_HEARTBEAT_MISSES = 3
+# Model-loading budget when the request budget is unlimited, and its ceiling for any budget:
+# the poll loop stays bounded however long generation itself may run.
+_DEFAULT_MODEL_TIMEOUT_SECONDS = 900.0
+_MAX_MODEL_WAIT_BUDGET_SECONDS = 3600.0
+# Headroom so the named stall guards expire before HTTPX's own read timeout does.
+_STREAM_READ_TIMEOUT_MARGIN_SECONDS = 30.0
+
+
+def _model_wait_budget(run: dict) -> float:
+ """Share of the request budget one model wait may spend, clamped so an unlimited or
+ oversized budget still leaves the poll loop bounded."""
+ timeout = float(run["config"]["budgets"]["modelTimeoutSeconds"])
+ capped = min(timeout or _DEFAULT_MODEL_TIMEOUT_SECONDS, _MAX_MODEL_WAIT_BUDGET_SECONDS)
+ return capped / (_MAX_MODEL_WAITS + 1)
def _select_synthesis_report(content: str, reasoning: str) -> str:
@@ -525,8 +542,11 @@ def _fit_decision_inputs(
@asynccontextmanager
-async def _wall_clock_timeout(seconds: float) -> AsyncIterator[None]:
+async def _wall_clock_timeout(seconds: float | None) -> AsyncIterator[None]:
"""Use asyncio.timeout when available, with the same behavior on Python 3.9/3.10."""
+ if seconds is None:
+ yield
+ return
timeout = getattr(asyncio, "timeout", None)
if timeout is not None:
async with timeout(seconds):
@@ -1007,7 +1027,7 @@ class ResearchSupervisor:
loop = asyncio.get_running_loop()
# Share the model budget across the allowed waits: spending all of it on one lets the
# enclosing wall clock fire first, burying the real refusal under a timeout.
- budget = float(run["config"]["budgets"]["modelTimeoutSeconds"]) / (_MAX_MODEL_WAITS + 1)
+ budget = _model_wait_budget(run)
if max_seconds is not None:
budget = min(budget, max_seconds)
deadline = loop.time() + budget
@@ -1030,8 +1050,7 @@ class ResearchSupervisor:
step = _retry_after_seconds(response) or _MODEL_SWITCH_RETRY_SECONDS
# Same budget share as _wait_for_local_model: one wait must leave room for the others and
# for the refusal, or the enclosing wall clock fires first and reports a timeout instead.
- budget = float(run["config"]["budgets"]["modelTimeoutSeconds"]) / (_MAX_MODEL_WAITS + 1)
- remaining = min(step * waits, _NAMED_MODEL_WAIT_SECONDS, budget)
+ remaining = min(step * waits, _NAMED_MODEL_WAIT_SECONDS, _model_wait_budget(run))
logger.info("research.waiting_for_model_switch run_id=%s seconds=%.0f", run_id, remaining)
while remaining > 0:
await self._check_active(run_id)
@@ -1271,16 +1290,33 @@ class ResearchSupervisor:
try:
await self._note_phase(run["id"], "phase.started", phase, call_id, step_position)
model_timeout = float(config["budgets"]["modelTimeoutSeconds"])
- # Configurable, capped by the run's wall clock; legacy runs use the default.
- first_output_budget = min(
- float(
- config["budgets"].get(
- "firstOutputTimeoutSeconds", _MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS
- )
- ),
- model_timeout,
+ # Configurable, capped by a finite run wall clock; legacy runs use the default.
+ first_output_budget = float(
+ config["budgets"].get(
+ "firstOutputTimeoutSeconds", _MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS
+ )
+ )
+ if model_timeout > 0:
+ first_output_budget = min(first_output_budget, model_timeout)
+ # Unlimited only drops the total wall clock; connect and headers stay bounded. This
+ # bound also caps the silence between queue notices, which no wall clock covers, so
+ # it has to clear the heartbeat those notices are paced by.
+ admission_gap_budget = max(
+ first_output_budget,
+ _MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS,
+ llama_admission_config_from_env().keepalive_interval_s
+ * _ADMISSION_HEARTBEAT_MISSES,
+ )
+ timeout = (
+ httpx.Timeout(model_timeout)
+ if model_timeout
+ else httpx.Timeout(
+ first_output_budget,
+ # Strictly looser than the guards above, so a stall is reported by name
+ # rather than as a message-less HTTPX ReadTimeout.
+ read = admission_gap_budget + _STREAM_READ_TIMEOUT_MARGIN_SECONDS,
+ )
)
- timeout = httpx.Timeout(model_timeout)
loop = asyncio.get_running_loop()
def semantic_deadline() -> tuple[float, type[BaseException]] | None:
@@ -1294,7 +1330,7 @@ class ResearchSupervisor:
)
async with (
- _wall_clock_timeout(model_timeout),
+ _wall_clock_timeout(model_timeout or None),
httpx.AsyncClient(timeout = timeout, trust_env = False) as client,
):
response: httpx.Response | None = None
@@ -1377,7 +1413,11 @@ class ResearchSupervisor:
# for it, and start the budget when the slot is granted. A plain
# ": keep-alive" means a silent backend, which is what we bound.
if line.startswith(_ADMISSION_WAIT_COMMENT):
- first_output_deadline = None
+ # Unlimited has no wall clock behind this, so bound the gap
+ # between queue notices; each notice refreshes it.
+ first_output_deadline = (
+ None if model_timeout else loop.time() + admission_gap_budget
+ )
elif line.startswith(_ADMISSION_DONE_COMMENT):
first_output_deadline = loop.time() + first_output_budget
continue
@@ -1453,6 +1493,13 @@ class ResearchSupervisor:
)
await flush_progress()
return report, reasoning, finish_reason, usage
+ except (ModelFirstOutputTimeout, ModelOutputIdleTimeout, ModelWallClockTimeout):
+ raise
+ except httpx.ReadTimeout as exc:
+ # Transport backstop: HTTPX raises this with no message, so name the stall instead.
+ if semantic_output_at is None:
+ raise ModelFirstOutputTimeout("Local model never produced output") from exc
+ raise ModelOutputIdleTimeout("Local model stopped producing output") from exc
except (TimeoutError, asyncio.TimeoutError) as exc:
raise ModelWallClockTimeout(
"Local model request exceeded its wall-clock timeout"
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 11d326a1222..ee5d40b5665 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -429,6 +429,9 @@ class ChatSettingsPayload(BaseModel):
webFetchToolsEnabled: Optional[bool] = None
deepResearchEnabled: Optional[bool] = None
researchWebsitePolicy: Optional[ChatResearchWebsitePolicy] = None
+ # Seconds per Deep Research model request; zero leaves the total wall clock off. Bounded
+ # like the run route so a value it would reject cannot be persisted and replayed.
+ researchModelTimeoutSeconds: Optional[int] = Field(default = None, ge = 0, le = 365 * 24 * 3600)
artifactsEnabled: Optional[bool] = None
showCanvasMenuItem: Optional[bool] = None
mcpEnabledForChat: Optional[bool] = None
@@ -455,6 +458,24 @@ class ChatSettingsPayload(BaseModel):
showAllQuantizations: Optional[bool] = None
fitOnDeviceOnly: Optional[bool] = None
+ @field_validator("researchModelTimeoutSeconds", mode = "before")
+ @classmethod
+ def _not_a_boolean(cls, value: Any) -> Any:
+ # bool subclasses int, so False coerces to the 0 sentinel and would persist as
+ # unlimited for every later run. The run route rejects booleans for the same reason.
+ if isinstance(value, bool):
+ raise ValueError("researchModelTimeoutSeconds must be an integer, not a boolean")
+ return value
+
+ @field_validator("researchModelTimeoutSeconds")
+ @classmethod
+ def _run_route_accepts_it(cls, value: Optional[int]) -> Optional[int]:
+ # The run route takes 0 (unlimited) or at least 10, so a persisted 1..9 would hydrate
+ # and then 400 every later run with nothing pointing at this setting.
+ if value is not None and 0 < value < 10:
+ raise ValueError("researchModelTimeoutSeconds must be 0 (unlimited) or at least 10")
+ return value
+
class ChatSettingsResponse(BaseModel):
settings: dict[str, Any]
diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.py
index 36f6f13491c..04730cf7cc1 100644
--- a/studio/backend/routes/research_runs.py
+++ b/studio/backend/routes/research_runs.py
@@ -15,7 +15,7 @@ from typing import Any
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request
from fastapi.responses import StreamingResponse
-from pydantic import AliasChoices, BaseModel, ConfigDict, Field
+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator
from auth.authentication import get_current_subject
from core.inference.message_content import message_text_with_pastes
@@ -47,6 +47,10 @@ _SENSITIVE_KEY_SUFFIXES = (
"sessiontoken",
)
_MAX_PLAN_STEPS = 30
+# Zero is the unlimited sentinel, so a finite value only has to cover the longest run anyone
+# would set: a year reads back in the 400, unlike a float-max ceiling.
+_MIN_FINITE_MODEL_TIMEOUT_SECONDS = 10
+_MAX_FINITE_MODEL_TIMEOUT_SECONDS = 365 * 24 * 3600
_DELTA_ONLY_EVENTS = {
"reasoning.updated",
"report.updated",
@@ -72,6 +76,17 @@ class CreateResearchRun(BaseModel):
websitePolicy: dict[str, list[str]] | None = None
instructions: str | None = Field(default = None, max_length = 32_000)
+ @field_validator("budgets", mode = "before")
+ @classmethod
+ def _reject_boolean_budgets(cls, value: Any) -> Any:
+ # bool is an int subclass, so False would coerce to the 0 "unlimited" sentinel and
+ # silently drop a deadline. Reject it here: by the time the field is typed it is 0.
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if isinstance(item, bool):
+ raise ValueError(f"{key} must be an integer, not a boolean")
+ return value
+
class ResearchPlanStep(BaseModel):
model_config = ConfigDict(extra = "forbid")
@@ -309,16 +324,24 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:
limits = {
"maxSteps": (1, _MAX_PLAN_STEPS),
"maxSources": (1, 100),
- "modelTimeoutSeconds": (10, 3600),
+ # Zero disables the total wall-clock deadline. Per-output stall deadlines still apply.
+ "modelTimeoutSeconds": (
+ _MIN_FINITE_MODEL_TIMEOUT_SECONDS,
+ _MAX_FINITE_MODEL_TIMEOUT_SECONDS,
+ ),
"toolTimeoutSeconds": (5, 600),
# Same range as its parent: slow CPU and offloaded models need minutes to first token.
"firstOutputTimeoutSeconds": (10, 3600),
}
for key, (minimum, maximum) in limits.items():
+ # The sentinel is not a short timeout, so it skips the floor rather than lowering it.
+ if key == "modelTimeoutSeconds" and budgets[key] == 0:
+ continue
if not minimum <= budgets[key] <= maximum:
- raise HTTPException(
- status_code = 400, detail = f"{key} must be between {minimum} and {maximum}"
- )
+ allowed = f"between {minimum} and {maximum}"
+ if key == "modelTimeoutSeconds":
+ allowed = f"0 (unlimited) or {allowed}"
+ raise HTTPException(status_code = 400, detail = f"{key} must be {allowed}")
# Server-controlled, not client tunable. OFF unless UNSLOTH_RESEARCH_AUTO_SCRAPE=1, and
# injected only when enabled, so a default run's budgets stay byte-identical to legacy.
from core.research_runs import _auto_scrape_default
diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.py
index 6ae5b205457..226e4e13c64 100644
--- a/studio/backend/tests/test_chat_settings_payload.py
+++ b/studio/backend/tests/test_chat_settings_payload.py
@@ -41,6 +41,7 @@ def test_mirrored_settings_round_trip():
"allowedDomains": ["unsloth.ai"],
"blockedDomains": [],
},
+ "researchModelTimeoutSeconds": 0,
"speculativeType": "ngram",
"gpuMemoryMode": "manual",
"fitOnDeviceOnly": True,
@@ -60,6 +61,7 @@ def test_mirrored_settings_round_trip():
"allowedDomains": ["unsloth.ai"],
"blockedDomains": [],
},
+ "researchModelTimeoutSeconds": 0,
"speculativeType": "ngram",
"gpuMemoryMode": "manual",
"fitOnDeviceOnly": True,
@@ -143,6 +145,13 @@ def test_unset_fields_stay_out_of_the_merge():
{"ragSource": {"type": "kb"}},
{"ragSource": {"type": "kb", "kbId": ""}},
{"researchWebsitePolicy": {"allowedDomains": "unsloth.ai"}},
+ # The run route takes 0 or at least 10, so a persisted 1..9 would 400 every run.
+ {"researchModelTimeoutSeconds": 1},
+ {"researchModelTimeoutSeconds": 9},
+ {"researchModelTimeoutSeconds": -1},
+ {"researchModelTimeoutSeconds": 365 * 24 * 3600 + 1},
+ # bool subclasses int, so False would persist as the 0 "unlimited" sentinel.
+ {"researchModelTimeoutSeconds": False},
{"unknownSetting": True},
],
)
diff --git a/studio/backend/tests/test_research_runs_hardening.py b/studio/backend/tests/test_research_runs_hardening.py
index 9ca19857c1d..07dd9d05cd8 100644
--- a/studio/backend/tests/test_research_runs_hardening.py
+++ b/studio/backend/tests/test_research_runs_hardening.py
@@ -416,6 +416,15 @@ def _make_payload(**overrides) -> CreateResearchRun:
return CreateResearchRun(**payload)
+def test_budgets_reject_a_boolean_instead_of_reading_it_as_unlimited():
+ # bool subclasses int, so False would land on the 0 sentinel and drop the deadline.
+ with pytest.raises(Exception, match = "not a boolean"):
+ _make_payload(budgets = {"modelTimeoutSeconds": False})
+ assert _make_payload(budgets = {"modelTimeoutSeconds": 0}).budgets == {
+ "modelTimeoutSeconds": 0,
+ }
+
+
def test_sanitize_config_rejects_nested_inference_credential():
payload = _make_payload(inferenceRequest = {"model": {"api_key": "sk-should-not-persist"}})
with pytest.raises(Exception):
@@ -724,7 +733,11 @@ def test_wait_for_local_model_still_honors_cancellation(monkeypatch):
asyncio.run(supervisor._wait_for_local_model(_waiting_run(30.0)))
-def _install_fake_client(monkeypatch, responses: list) -> list:
+def _install_fake_client(
+ monkeypatch,
+ responses: list,
+ timeouts: list[httpx.Timeout] | None = None,
+) -> list:
"""Serve ``responses`` in order to the completion path and record the sends. An entry that
is an exception is raised instead, standing in for a transport failure."""
sent: list = []
@@ -736,7 +749,8 @@ def _install_fake_client(monkeypatch, responses: list) -> list:
class _FakeClient:
def __init__(self, **kwargs):
- pass
+ if timeouts is not None:
+ timeouts.append(kwargs["timeout"])
async def __aenter__(self):
return self
@@ -820,6 +834,109 @@ def _run_stream(supervisor, timeout_seconds: float = 30.0) -> tuple:
)
+def test_unlimited_stream_keeps_header_and_idle_timeouts(monkeypatch):
+ timeouts: list[httpx.Timeout] = []
+ _install_fake_client(monkeypatch, [_response(200, body = _stream_body())], timeouts)
+ supervisor = _make_supervisor(_noop_check_active)
+ run = _waiting_run(0)
+ run["config"]["budgets"]["firstOutputTimeoutSeconds"] = 10
+
+ assert asyncio.run(
+ supervisor._stream_completion(run, [{"role": "user"}], report_progress = False)
+ ) == ("report", "", "stop", None)
+ assert len(timeouts) == 1
+ assert timeouts[0].connect == 10
+ # Strictly looser than the idle guard, so the named stall wins the race against HTTPX.
+ assert timeouts[0].read > research_runs._MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS
+
+
+class _QueuedThenSilentResponse:
+ """A backend that announces it is queueing and then never says anything else."""
+
+ status_code = 200
+
+ def raise_for_status(self):
+ return None
+
+ async def aclose(self):
+ return None
+
+ async def aiter_lines(self):
+ yield research_runs._ADMISSION_WAIT_COMMENT
+ await asyncio.sleep(3600)
+
+
+# Queueing is not charged to the request budget, so with no wall clock behind it a backend
+# that queues then goes quiet would hold the run open forever.
+def test_unlimited_still_bounds_silence_after_a_queue_notice(monkeypatch):
+ _install_fake_client(monkeypatch, [_QueuedThenSilentResponse()])
+ monkeypatch.setattr(research_runs, "_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS", 0.2)
+ supervisor = _make_supervisor(_noop_check_active)
+ run = _waiting_run(0)
+ run["config"]["budgets"]["firstOutputTimeoutSeconds"] = 1
+
+ with pytest.raises(research_runs.ModelFirstOutputTimeout):
+ asyncio.run(
+ asyncio.wait_for(
+ supervisor._stream_completion(run, [{"role": "user"}], report_progress = False),
+ timeout = 30,
+ )
+ )
+
+
+class _ReadTimeoutResponse:
+ """A transport that times out reading the body, which HTTPX reports with no message."""
+
+ status_code = 200
+
+ def __init__(self, lines = ()):
+ self._lines = list(lines)
+
+ def raise_for_status(self):
+ return None
+
+ async def aclose(self):
+ return None
+
+ async def aiter_lines(self):
+ for line in self._lines:
+ yield line
+ raise httpx.ReadTimeout("")
+
+
+# Unlimited leaves no wall clock to convert, so a bare ReadTimeout would reach the user as
+# an empty error string instead of naming the stall.
+ ("lines", "expected"),
+ (
+ ((), research_runs.ModelFirstOutputTimeout),
+ (
+ ('data: {"choices": [{"delta": {"content": "hi"}}]}',),
+ research_runs.ModelOutputIdleTimeout,
+ ),
+ ),
+)
+def test_a_bare_read_timeout_is_reported_as_a_named_stall(monkeypatch, lines, expected):
+ _install_fake_client(monkeypatch, [_ReadTimeoutResponse(lines)])
+ supervisor = _make_supervisor(_noop_check_active)
+ with pytest.raises(expected):
+ asyncio.run(
+ supervisor._stream_completion(
+ _waiting_run(0), [{"role": "user"}], report_progress = False
+ )
+ )
+
+
+def test_model_wait_budget_stays_bounded_for_any_request_budget():
+ waits = research_runs._MAX_MODEL_WAITS + 1
+ # Unchanged for every budget the shipped range already allowed.
+ assert research_runs._model_wait_budget(_waiting_run(3600)) == 3600 / waits
+ assert research_runs._model_wait_budget(_waiting_run(1800)) == 1800 / waits
+ # Unlimited uses the shipped default, and an oversized finite budget is capped.
+ assert research_runs._model_wait_budget(_waiting_run(0)) == 900 / waits
+ assert research_runs._model_wait_budget(_waiting_run(10**9)) == 3600 / waits
+
+
def test_stream_completion_keeps_channels_separate_and_streams_content(monkeypatch):
content_chunks = ["# Result\n" + ("a" * 300), "b" * 300, "c" * 300]
stream = _delta_stream_body(
@@ -1947,6 +2064,14 @@ def test_wall_clock_timeout_supports_python_without_asyncio_timeout(monkeypatch)
asyncio.run(run())
+def test_wall_clock_timeout_can_be_disabled():
+ async def run():
+ async with research_runs._wall_clock_timeout(None):
+ await asyncio.sleep(0.01)
+
+ asyncio.run(run())
+
+
def test_wall_clock_timeout_does_not_swallow_shutdown_cancellation(monkeypatch):
# raising=False: on Python 3.10 asyncio.timeout does not exist to begin with,
# which is the very case these tests cover.
@@ -2070,3 +2195,48 @@ def test_stream_completion_gives_a_model_switch_more_than_the_generic_backoff(mo
assert len(sent) == research_runs._MAX_MODEL_WAITS + 1
# Each wait is longer than the last: a swap that has not finished in 5s needs more, not less.
assert sum(delays) == 30.0
+
+
+def _slow_admission_stream(gap_seconds: float):
+ """A queue that announces itself on a slow heartbeat, then admits and answers."""
+
+ class _SlowQueue:
+ status_code = 200
+
+ def raise_for_status(self):
+ return self
+
+ async def aclose(self):
+ return None
+
+ async def aiter_lines(self):
+ for _ in range(2):
+ yield ": admission-wait"
+ await asyncio.sleep(gap_seconds)
+ yield ": admission-done"
+ for line in _stream_body().splitlines():
+ yield line
+
+ return _SlowQueue()
+
+
+def test_a_slow_admission_heartbeat_widens_the_queue_gap_bound(monkeypatch):
+ """The gap between queue notices is bounded by the heartbeat operators configured."""
+ monkeypatch.setenv("UNSLOTH_LLAMA_ADMISSION_KEEPALIVE_INTERVAL", "300")
+ timeouts: list[httpx.Timeout] = []
+ _install_fake_client(monkeypatch, [_response(200, body = _stream_body())], timeouts)
+ supervisor = _make_supervisor(_noop_check_active)
+
+ assert _run_stream(supervisor, timeout_seconds = 0) == ("report", "", "stop", None)
+ assert timeouts[0].read == 300 * 3 + research_runs._STREAM_READ_TIMEOUT_MARGIN_SECONDS
+
+
+def test_an_unlimited_run_survives_a_gap_past_the_default_queue_bound(monkeypatch):
+ """A healthy queue on a slow heartbeat must not be failed as a first-output stall."""
+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setattr(research_runs, "_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setenv("UNSLOTH_LLAMA_ADMISSION_KEEPALIVE_INTERVAL", "0.1")
+ _install_fake_client(monkeypatch, [_slow_admission_stream(0.15)])
+ supervisor = _make_supervisor(_noop_check_active)
+
+ assert _run_stream(supervisor, timeout_seconds = 0) == ("report", "", "stop", None)
diff --git a/studio/backend/tests/test_research_runs_storage.py b/studio/backend/tests/test_research_runs_storage.py
index 05adee4d844..8b16039be76 100644
--- a/studio/backend/tests/test_research_runs_storage.py
+++ b/studio/backend/tests/test_research_runs_storage.py
@@ -1459,7 +1459,7 @@ def test_research_budget_defaults_support_long_runs():
)
-def test_research_budget_ceilings_allow_depth_but_remain_bounded():
+def test_research_budget_limits_allow_unlimited_model_requests():
from fastapi import HTTPException
from routes.research_runs import CreateResearchRun, _sanitize_config
@@ -1470,13 +1470,26 @@ def test_research_budget_ceilings_allow_depth_but_remain_bounded():
budgets = {
"maxSteps": 30,
"maxSources": 100,
- "modelTimeoutSeconds": 3600,
+ "modelTimeoutSeconds": 7200,
"toolTimeoutSeconds": 600,
"firstOutputTimeoutSeconds": 3600,
},
)
assert _sanitize_config(payload, {"modelId": "local-model"})["budgets"] == payload.budgets
+ payload.budgets["modelTimeoutSeconds"] = 0
+ assert _sanitize_config(payload, {"modelId": "local-model"})["budgets"] == payload.budgets
+
+ # The ceiling reads back in the 400, and the sentinel is the only sub-floor value allowed.
+ for rejected in (10**310, 9, -1):
+ payload.budgets["modelTimeoutSeconds"] = rejected
+ with pytest.raises(
+ HTTPException,
+ match = "modelTimeoutSeconds must be 0 \\(unlimited\\) or between 10 and 31536000",
+ ):
+ _sanitize_config(payload, {"modelId": "local-model"})
+
+ payload.budgets["modelTimeoutSeconds"] = 7200
payload.budgets["maxSteps"] = 31
with pytest.raises(HTTPException, match = "maxSteps must be between 1 and 30"):
_sanitize_config(payload, {"modelId": "local-model"})
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index ee52a8db051..e0b16c4f0f0 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -3914,6 +3914,9 @@ export function createOpenAIStreamAdapter(
inferenceRequest,
...(researchInstructions ? { instructions: researchInstructions } : {}),
...(ragScope ? { ragScope } : {}),
+ budgets: {
+ modelTimeoutSeconds: runtime.researchModelTimeoutSeconds,
+ },
websitePolicy: {
allowedDomains: [...runtime.researchWebsitePolicy.allowedDomains],
blockedDomains: [...runtime.researchWebsitePolicy.blockedDomains],
diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.ts
index 45ad8d363e6..4a22946a670 100644
--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts
@@ -52,6 +52,7 @@ export interface PersistedChatSettings {
webFetchToolsEnabled?: boolean;
deepResearchEnabled?: boolean;
researchWebsitePolicy?: ResearchWebsitePolicy;
+ researchModelTimeoutSeconds?: number;
artifactsEnabled?: boolean;
showCanvasMenuItem?: boolean;
mcpEnabledForChat?: boolean;
diff --git a/studio/frontend/src/features/chat/components/deep-research-composer-button.tsx b/studio/frontend/src/features/chat/components/deep-research-composer-button.tsx
index e4857d1603b..10c695b2dca 100644
--- a/studio/frontend/src/features/chat/components/deep-research-composer-button.tsx
+++ b/studio/frontend/src/features/chat/components/deep-research-composer-button.tsx
@@ -17,9 +17,18 @@ import { cn } from "@/lib/utils";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { XIcon } from "lucide-react";
import { type KeyboardEvent, useState } from "react";
-import { useChatRuntimeStore } from "../stores/chat-runtime-store";
+import {
+ DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ useChatRuntimeStore,
+} from "../stores/chat-runtime-store";
+import { MAX_RESEARCH_MODEL_TIMEOUT_SECONDS } from "../utils/mirrored-chat-settings";
import type { ResearchWebsitePolicy } from "../types/research";
+// The field is in minutes; its ceiling is the seconds cap the backend enforces.
+const MAX_RESEARCH_MODEL_TIMEOUT_MINUTES = Math.floor(
+ MAX_RESEARCH_MODEL_TIMEOUT_SECONDS / 60,
+);
+
function normalizeDomain(raw: string): string | null {
const value = raw.trim();
if (!value || /[\\\s]/.test(value)) return null;
@@ -189,6 +198,12 @@ export function DeepResearchWebsiteAccessDialog({
const setPolicy = useChatRuntimeStore(
(state) => state.setResearchWebsitePolicy,
);
+ const modelTimeoutSeconds = useChatRuntimeStore(
+ (state) => state.researchModelTimeoutSeconds,
+ );
+ const setModelTimeoutSeconds = useChatRuntimeStore(
+ (state) => state.setResearchModelTimeoutSeconds,
+ );
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -196,6 +211,8 @@ export function DeepResearchWebsiteAccessDialog({
<DeepResearchWebsiteAccessContent
policy={policy}
setPolicy={setPolicy}
+ modelTimeoutSeconds={modelTimeoutSeconds}
+ setModelTimeoutSeconds={setModelTimeoutSeconds}
onClose={() => onOpenChange(false)}
/>
) : null}
@@ -206,24 +223,80 @@ export function DeepResearchWebsiteAccessDialog({
function DeepResearchWebsiteAccessContent({
policy,
setPolicy,
+ modelTimeoutSeconds,
+ setModelTimeoutSeconds,
onClose,
}: {
policy: ResearchWebsitePolicy;
setPolicy: (policy: ResearchWebsitePolicy) => void;
+ modelTimeoutSeconds: number;
+ setModelTimeoutSeconds: (seconds: number) => void;
onClose: () => void;
}) {
const [draft, setDraft] = useState<ResearchWebsitePolicy>(policy);
+ const [unlimited, setUnlimited] = useState(modelTimeoutSeconds === 0);
+ // Unlimited has no minutes of its own, so turning the limit back on offers the default.
+ const [timeoutMinutes, setTimeoutMinutes] = useState(
+ String(
+ Math.ceil(
+ (modelTimeoutSeconds || DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS) / 60,
+ ),
+ ),
+ );
+ // The API accepts second-level values the minutes field cannot spell, so saving an
+ // untouched control must replay the stored seconds rather than the rounded minutes.
+ const [timeoutEdited, setTimeoutEdited] = useState(false);
return (
<DialogContent className="sm:max-w-lg">
<DialogHeader>
- <DialogTitle>Website access</DialogTitle>
+ <DialogTitle>Deep research</DialogTitle>
<DialogDescription>
- Control which websites the next Deep Research run can search and read.
- Limits are enforced by the server and shared with the research model.
+ Control website access and model request time for the next Deep
+ Research run.
</DialogDescription>
</DialogHeader>
<div className="space-y-6">
+ <div className="space-y-2">
+ <div>
+ {/* A run makes many model requests, so this bounds each one, not the run. */}
+ <div className="text-sm font-medium">Time per model request</div>
+ <p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">
+ {unlimited
+ ? "No limit on a single model request. Slow models can continue while they keep producing output."
+ : "Maximum time for each model request, so a run of many requests can take longer. Output stall safeguards stay active."}
+ </p>
+ </div>
+ <div className="flex gap-2">
+ <Input
+ type="number"
+ min="1"
+ max={MAX_RESEARCH_MODEL_TIMEOUT_MINUTES}
+ step="1"
+ value={timeoutMinutes}
+ disabled={unlimited}
+ onChange={(event) => {
+ setTimeoutEdited(true);
+ setTimeoutMinutes(event.target.value);
+ }}
+ aria-label="Deep Research time per model request in minutes"
+ className="w-28"
+ />
+ <span className="self-center text-sm text-muted-foreground">
+ minutes
+ </span>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => {
+ setTimeoutEdited(true);
+ setUnlimited((value) => !value);
+ }}
+ >
+ {unlimited ? "Use a limit" : "No limit"}
+ </Button>
+ </div>
+ </div>
<DomainList
label="Allow only"
description="When set, research can access only these domains and their subdomains."
@@ -244,6 +317,18 @@ function DeepResearchWebsiteAccessContent({
<Button
onClick={() => {
setPolicy(draft);
+ const minutes = Number(timeoutMinutes);
+ // The max attribute does not stop a typed value reaching here, and falling
+ // through to the default would hand someone asking for a long run a short one.
+ setModelTimeoutSeconds(
+ unlimited
+ ? 0
+ : !timeoutEdited
+ ? modelTimeoutSeconds
+ : Number.isSafeInteger(minutes) && minutes >= 1
+ ? Math.min(minutes, MAX_RESEARCH_MODEL_TIMEOUT_MINUTES) * 60
+ : DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
onClose();
}}
>
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 72ce9dd92ce..aa883e3c347 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -57,6 +57,8 @@ import {
} from "../utils/chat-settings-storage";
import {
loadShadowOwnsMirroredSetting,
+ MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS,
normalizeStoredPermissionMode,
normalizeStoredRagAutoInject,
} from "../utils/mirrored-chat-settings";
@@ -87,6 +89,8 @@ export const CHAT_DEEP_RESEARCH_ENABLED_KEY =
"unsloth_chat_deep_research_enabled";
export const CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY =
"unsloth_chat_deep_research_website_policy";
+export const CHAT_DEEP_RESEARCH_MODEL_TIMEOUT_KEY =
+ "unsloth_chat_deep_research_model_timeout";
export const CHAT_ARTIFACTS_ENABLED_KEY = "unsloth_chat_artifacts_enabled";
export const CHAT_SHOW_CANVAS_MENU_ITEM_KEY =
"unsloth_chat_show_canvas_menu_item";
@@ -169,6 +173,29 @@ export const DEFAULT_RESEARCH_WEBSITE_POLICY: ResearchWebsitePolicy = {
allowedDomains: [],
blockedDomains: [],
};
+export const DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS = 900;
+
+/** 0 (unlimited) or a finite budget the settings patch and the run route both accept.
+ * Anything else would be dropped from the patch and 400 the run, so the default stands in. */
+function isSupportedResearchModelTimeout(value: number): boolean {
+ if (!Number.isSafeInteger(value) || value < 0) return false;
+ if (value > MAX_RESEARCH_MODEL_TIMEOUT_SECONDS) return false;
+ return value === 0 || value >= MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS;
+}
+
+function loadResearchModelTimeoutSeconds(): number {
+ if (typeof window === "undefined") return DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS;
+ try {
+ const raw = window.localStorage.getItem(CHAT_DEEP_RESEARCH_MODEL_TIMEOUT_KEY);
+ if (raw === null) return DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS;
+ const value = Number(raw);
+ return isSupportedResearchModelTimeout(value)
+ ? value
+ : DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS;
+ } catch {
+ return DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS;
+ }
+}
function loadResearchWebsitePolicy(): ResearchWebsitePolicy {
if (typeof window === "undefined") return DEFAULT_RESEARCH_WEBSITE_POLICY;
@@ -593,6 +620,10 @@ const MIRRORED_SETTINGS = {
storageKey: CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY,
...JSON_SETTING,
},
+ researchModelTimeoutSeconds: {
+ storageKey: CHAT_DEEP_RESEARCH_MODEL_TIMEOUT_KEY,
+ ...NUMBER_SETTING,
+ },
artifactsEnabled: {
storageKey: CHAT_ARTIFACTS_ENABLED_KEY,
...BOOLEAN_SETTING,
@@ -2202,6 +2233,7 @@ type ChatRuntimeStore = {
imageToolsEnabled: boolean;
deepResearchEnabled: boolean;
researchWebsitePolicy: ResearchWebsitePolicy;
+ researchModelTimeoutSeconds: number;
artifactsEnabled: boolean;
// Whether the Canvas toggle is offered in the composer + menu (hidden by default).
showCanvasMenuItem: boolean;
@@ -2527,6 +2559,7 @@ type ChatRuntimeStore = {
setImageToolsEnabled: (enabled: boolean) => void;
setDeepResearchEnabled: (enabled: boolean) => void;
setResearchWebsitePolicy: (policy: ResearchWebsitePolicy) => void;
+ setResearchModelTimeoutSeconds: (seconds: number) => void;
setArtifactsEnabled: (
enabled: boolean,
options?: { persist?: boolean },
@@ -2646,6 +2679,7 @@ type ScalarSettingKey =
| "webFetchToolsEnabled"
| "deepResearchEnabled"
| "researchWebsitePolicy"
+ | "researchModelTimeoutSeconds"
| "artifactsEnabled"
| "showCanvasMenuItem"
| "mcpEnabledForChat"
@@ -2694,6 +2728,7 @@ const SCALAR_SETTING_KEYS = [
"webFetchToolsEnabled",
"deepResearchEnabled",
"researchWebsitePolicy",
+ "researchModelTimeoutSeconds",
"artifactsEnabled",
"showCanvasMenuItem",
"mcpEnabledForChat",
@@ -3340,6 +3375,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
imageToolsEnabled: loadBool(CHAT_IMAGE_TOOLS_ENABLED_KEY, false),
deepResearchEnabled: loadBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false),
researchWebsitePolicy: loadResearchWebsitePolicy(),
+ researchModelTimeoutSeconds: loadResearchModelTimeoutSeconds(),
artifactsEnabled: loadBool(CHAT_ARTIFACTS_ENABLED_KEY, false),
showCanvasMenuItem: loadShowCanvasMenuItem(),
collapseHtmlArtifacts: loadBool(CHAT_COLLAPSE_HTML_ARTIFACTS_KEY, false),
@@ -4269,6 +4305,19 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
};
}),
+ setResearchModelTimeoutSeconds: (researchModelTimeoutSeconds) =>
+ set((state) => {
+ const seconds = isSupportedResearchModelTimeout(
+ researchModelTimeoutSeconds,
+ )
+ ? researchModelTimeoutSeconds
+ : DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS;
+ persistSetting(CHAT_DEEP_RESEARCH_MODEL_TIMEOUT_KEY, String(seconds));
+ return {
+ researchModelTimeoutSeconds: seconds,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
+ }),
setArtifactsEnabled: (artifactsEnabled, options) =>
set((state) => {
if (options?.persist !== false) {
diff --git a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
index 0a10a8e2bf5..c9e9a36fca5 100644
--- a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
+++ b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
@@ -38,14 +38,27 @@ const MIRRORED_ENUM_VALUES = {
Record<keyof PersistedChatSettings, readonly string[]>
>;
+// One year, the ceiling ChatSettingsPayload and the run route both enforce. A larger value
+// would be dropped from the patch and then 400 the run, so it is bounded where it is set.
+export const MAX_RESEARCH_MODEL_TIMEOUT_SECONDS = 365 * 24 * 3600;
+// 0 is the unlimited sentinel, not a very short budget, so it sits below the run route's
+// finite floor. A stored 1..9 would 400 every run.
+export const MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS = 10;
+
// Bounds match the ge/le the backend payload enforces on the same fields.
const MIRRORED_NUMBER_BOUNDS = {
ragTopK: { min: 1, max: 50, integer: true },
ragAutoInjectMinScore: { min: 0, max: 1, integer: false },
+ researchModelTimeoutSeconds: {
+ min: 0,
+ minPositive: MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ max: MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ integer: true,
+ },
} as const satisfies Partial<
Record<
keyof PersistedChatSettings,
- { min: number; max: number; integer: boolean }
+ { min: number; minPositive?: number; max: number; integer: boolean }
>
>;
@@ -108,10 +121,19 @@ export function sanitizeRagSource(
export function sanitizeBoundedNumber(
value: unknown,
- { min, max, integer }: { min: number; max: number; integer: boolean },
+ {
+ min,
+ minPositive,
+ max,
+ integer,
+ }: { min: number; minPositive?: number; max: number; integer: boolean },
): number | undefined {
if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
if (integer && !Number.isInteger(value)) return undefined;
+ // A sentinel below the floor stays legal; anything between the two is not.
+ if (minPositive !== undefined && value > min && value < minPositive) {
+ return undefined;
+ }
return value >= min && value <= max ? value : undefined;
}
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.ts
index 1423ceadf07..06b02e54ad5 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
@@ -25,6 +25,7 @@ const QUEUED_SETTING_KEYS = [
"webFetchToolsEnabled",
"deepResearchEnabled",
"researchWebsitePolicy",
+ "researchModelTimeoutSeconds",
"ragEnabled",
"ragSource",
"ragMode",
diff --git a/studio/frontend/tests/mirrored-chat-settings.test.ts b/studio/frontend/tests/mirrored-chat-settings.test.ts
index 313322806bd..adf0c3236c3 100644
--- a/studio/frontend/tests/mirrored-chat-settings.test.ts
+++ b/studio/frontend/tests/mirrored-chat-settings.test.ts
@@ -38,6 +38,7 @@ test("a full set of mirrored settings survives the round trip", () => {
allowedDomains: ["unsloth.ai"],
blockedDomains: [],
},
+ researchModelTimeoutSeconds: 0,
speculativeType: "ngram",
gpuMemoryMode: "manual",
fitOnDeviceOnly: true,
@@ -56,6 +57,7 @@ test("a full set of mirrored settings survives the round trip", () => {
allowedDomains: ["unsloth.ai"],
blockedDomains: [],
},
+ researchModelTimeoutSeconds: 0,
speculativeType: "ngram",
gpuMemoryMode: "manual",
fitOnDeviceOnly: true,
diff --git a/studio/frontend/tests/mirrored-settings-write-authority.test.ts b/studio/frontend/tests/mirrored-settings-write-authority.test.ts
index 86eee4d50e9..525ddb620a3 100644
--- a/studio/frontend/tests/mirrored-settings-write-authority.test.ts
+++ b/studio/frontend/tests/mirrored-settings-write-authority.test.ts
@@ -99,6 +99,26 @@ test("hydration backfills only from an authoritative read", () => {
assert.doesNotMatch(hydrate, /\n\s*backfillMirroredSettings\(settings\);/);
});
+test("a missing Deep Research timeout keeps the finite default", () => {
+ const loadTimeout = slice(
+ store,
+ "function loadResearchModelTimeoutSeconds(): number {",
+ "\n}\n\nfunction loadResearchWebsitePolicy",
+ );
+ assert.match(
+ loadTimeout,
+ /const raw = window\.localStorage\.getItem\(CHAT_DEEP_RESEARCH_MODEL_TIMEOUT_KEY\);/,
+ );
+ assert.match(
+ loadTimeout,
+ /if \(raw === null\) return DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS;/,
+ );
+ assert.match(
+ loadTimeout,
+ /catch \{\s*return DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS;\s*\}/,
+ );
+});
+
test("only the legacy-storage fallback is non-authoritative", () => {
const loader = slice(
storage,
diff --git a/studio/frontend/tests/research-model-timeout-bounds.test.ts b/studio/frontend/tests/research-model-timeout-bounds.test.ts
new file mode 100644
index 00000000000..3a47afa9309
--- /dev/null
+++ b/studio/frontend/tests/research-model-timeout-bounds.test.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The Deep Research total-time minutes field had no ceiling, while ChatSettingsPayload and
+// the run route cap the seconds it turns into at one year: an over-cap value was dropped
+// from the settings patch and then 400d every run. These pin the ceiling on every path.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import type { PersistedChatSettings } from "../src/features/chat/api/chat-settings-api.ts";
+import {
+ assignSanitizedMirroredSettings,
+ MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ sanitizeBoundedNumber,
+} from "../src/features/chat/utils/mirrored-chat-settings.ts";
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const { store: localStorageFake } = installLocalStorageFake();
+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");
+register("./store-settings-resolver.mjs", import.meta.url);
+
+const { useChatRuntimeStore, DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS } =
+ await import("../src/features/chat/stores/chat-runtime-store.ts");
+
+test("the cap matches the ceiling the backend payload enforces", () => {
+ assert.equal(MAX_RESEARCH_MODEL_TIMEOUT_SECONDS, 365 * 24 * 3600);
+});
+
+test("the mirrored patch keeps the cap and drops one second past it", () => {
+ const atCap: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings(
+ { researchModelTimeoutSeconds: MAX_RESEARCH_MODEL_TIMEOUT_SECONDS },
+ atCap,
+ );
+ assert.equal(
+ atCap.researchModelTimeoutSeconds,
+ MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
+
+ const overCap: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings(
+ { researchModelTimeoutSeconds: MAX_RESEARCH_MODEL_TIMEOUT_SECONDS + 1 },
+ overCap,
+ );
+ assert.equal(overCap.researchModelTimeoutSeconds, undefined);
+});
+
+test("an over-cap budget never reaches the store or storage", () => {
+ const store = useChatRuntimeStore.getState();
+
+ // 1000000 minutes, which the composer's unbounded minutes field accepted.
+ store.setResearchModelTimeoutSeconds(1000000 * 60);
+ assert.equal(
+ useChatRuntimeStore.getState().researchModelTimeoutSeconds,
+ DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
+
+ // One out-of-contract field rejects the whole patch, so what the store holds
+ // has to survive sanitisation rather than be dropped from it.
+ const mirrored: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings(
+ {
+ researchModelTimeoutSeconds:
+ useChatRuntimeStore.getState().researchModelTimeoutSeconds,
+ },
+ mirrored,
+ );
+ assert.equal(
+ mirrored.researchModelTimeoutSeconds,
+ DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
+
+ // The cap itself and the unlimited sentinel still round trip.
+ store.setResearchModelTimeoutSeconds(MAX_RESEARCH_MODEL_TIMEOUT_SECONDS);
+ assert.equal(
+ useChatRuntimeStore.getState().researchModelTimeoutSeconds,
+ MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
+ store.setResearchModelTimeoutSeconds(0);
+ assert.equal(useChatRuntimeStore.getState().researchModelTimeoutSeconds, 0);
+});
+
+// 0 is the unlimited sentinel, so it is legal below the run route's finite floor of 10.
+// Anything between the two would hydrate, be sent unchanged, and 400 every run.
+test("a sub-floor finite timeout is refused on every frontend path", () => {
+ const store = useChatRuntimeStore.getState();
+
+ for (const rejected of [1, 5, 9]) {
+ const mirrored: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings(
+ { researchModelTimeoutSeconds: rejected },
+ mirrored,
+ );
+ assert.equal(mirrored.researchModelTimeoutSeconds, undefined);
+
+ store.setResearchModelTimeoutSeconds(rejected);
+ assert.equal(
+ useChatRuntimeStore.getState().researchModelTimeoutSeconds,
+ DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
+ }
+
+ // The sentinel and the floor itself stay legal.
+ for (const accepted of [0, MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS]) {
+ const mirrored: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings(
+ { researchModelTimeoutSeconds: accepted },
+ mirrored,
+ );
+ assert.equal(mirrored.researchModelTimeoutSeconds, accepted);
+ }
+
+ // The shared sanitizer keeps the rule for any caller, not just this field.
+ const bounds = { min: 0, minPositive: 10, max: 100, integer: true };
+ assert.equal(sanitizeBoundedNumber(0, bounds), 0);
+ assert.equal(sanitizeBoundedNumber(5, bounds), undefined);
+ assert.equal(sanitizeBoundedNumber(10, bounds), 10);
+});
+
+// The max attribute does not stop a typed value reaching the save handler, so it clamps:
+// falling through to the default would hand someone asking for a long run a short one.
+test("an over-cap typed value saves as the cap, not as the default", () => {
+ const store = useChatRuntimeStore.getState();
+ const maxMinutes = Math.floor(MAX_RESEARCH_MODEL_TIMEOUT_SECONDS / 60);
+
+ // What the dialog's save handler computes for a typed 1000000 minutes.
+ const saved = Math.min(1000000, maxMinutes) * 60;
+ assert.equal(saved, MAX_RESEARCH_MODEL_TIMEOUT_SECONDS);
+
+ store.setResearchModelTimeoutSeconds(saved);
+ assert.equal(
+ useChatRuntimeStore.getState().researchModelTimeoutSeconds,
+ MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
+ assert.notEqual(
+ useChatRuntimeStore.getState().researchModelTimeoutSeconds,
+ DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS,
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-settings.test.ts b/studio/frontend/tests/thread-scoped-settings.test.ts
index 2f2d8a292a4..3425177f6b1 100644
--- a/studio/frontend/tests/thread-scoped-settings.test.ts
+++ b/studio/frontend/tests/thread-scoped-settings.test.ts
@@ -86,6 +86,7 @@ test("settings that describe the installation stay out of the snapshot", () => {
"ragOcrScanned",
"ragCaptionFigures",
"researchWebsitePolicy",
+ "researchModelTimeoutSeconds",
"speculativeType",
"gpuMemoryMode",
"expandQuantizations",
diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.py
index 2259e28f1f0..3b87f2dad6a 100644
--- a/tests/studio/test_deep_research_frontend_contract.py
+++ b/tests/studio/test_deep_research_frontend_contract.py
@@ -269,7 +269,7 @@ def test_research_website_limits_are_configurable_and_sent_with_each_run() -> No
assert 'label="Allow only"' in component
assert 'label="Always block"' in component
assert "their subdomains" in component
- assert "<DialogTitle>Website access</DialogTitle>" in component
+ assert "<DialogTitle>Deep research</DialogTitle>" in component
assert "DeepResearchWebsiteAccessDialog" in thread
assert "researchWebsitePolicy" in store
assert "CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY" in store