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
add a setting that tells the model the current date (#8879)
Maheswar Kumar450299909bf7
diff --git a/studio/backend/core/research/prompts.py b/studio/backend/core/research/prompts.pyindex 7542e9f4988..f7a16cf9eb2 100644--- a/studio/backend/core/research/prompts.py+++ b/studio/backend/core/research/prompts.py@@ -6,6 +6,7 @@from __future__ import annotationsfrom core.inference.web_access_policy import website_policy_prompt+from utils.current_date_prompt_settings import strip_current_date_prompt_lines_REPORT_BOUNDARY_MARKER = "<!-- UNSLOTH_FINAL_REPORT -->"@@ -100,6 +101,9 @@ Return only strict JSON with this shape:Use 1 to {max_steps} focused, non-overlapping steps. Each step must have a concrete search query.Prioritize primary and authoritative sources, account for relevant dates and geography, and includeverification or counterevidence where the question involves disputed or consequential claims.+When a step depends on recency and a current date is stated above, anchor the step to that date+rather than to a year your training data makes feel current. An earlier year is right whenever the+period under study reaches into it, such as the most recent annual figures early in a new year.For empirical or technical steps, include a source-type term such as `research paper`, `standard`,or `official documentation` in the query. Do not use generic topic-only queries.Treat prior conversation context and chat instructions as private reference material. Never put@@ -110,12 +114,19 @@ Do not assume the user's premise is correct. Do not answer the question or calldef _system_prompt_with_instructions(base: str, config: dict) -> str:+ prompt = base+ # runs created before this field existed have no stamped date and keep their original prompts.+ current_date = str(config.get("currentDate") or "").strip()+ if current_date:+ prompt = f"{current_date}\n\n{prompt}"instructions = str(config.get("instructions") or "").strip()+ if current_date:+ instructions = strip_current_date_prompt_lines(instructions)if not instructions:- return base+ return promptreturn ("Chat-specific instructions follow. Apply them only when compatible with the ""non-overridable research, citation, output-format, and security rules that follow.\n"f"<chat_instructions>\n{instructions}\n</chat_instructions>\n\n"- f"Non-overridable rules:\n{base}"+ f"Non-overridable rules:\n{prompt}")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 9d610dc1650..284e2085eed 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -2909,7 +2909,12 @@ from utils.utils import is_hf_authentication_error, safe_error_detail, log_and_himport ioimport base64-from datetime import date as _date++from utils.current_date_prompt_settings import (+ contains_current_date_prompt_line,+ current_date_prompt_line,+ replace_current_date_prompt_lines,+)if TYPE_CHECKING:import numpy as np@@ -4175,10 +4180,9 @@ def _build_tool_action_nudge(return ""if full_access_only:return _full_access_tip(code_tools) if (full_access and has_code) else ""- date_line = f"The current date is {_date.today().isoformat()}. "if not (has_web or has_code or has_artifact):# Research alone: the base nudge's "otherwise answer normally" would undo the tip.- return date_line + _TOOL_RESEARCH_TIP+ return _TOOL_RESEARCH_TIPmodel_size_b = _extract_model_size_b(model_name)compact_web_tip = model_size_b is not None and model_size_b < 9@@ -4195,7 +4199,8 @@ def _build_tool_action_nudge(tool_tip_parts.append(_TOOL_ARTIFACT_TIP)if has_research:tool_tip_parts.append(_TOOL_RESEARCH_TIP)- return date_line + _TOOL_BASE_NUDGE + " " + " ".join(tool_tip_parts)+ # the date rides on the system prompt instead, so a tool-less chat is not left date-blind.+ return _TOOL_BASE_NUDGE + " " + " ".join(tool_tip_parts)# Nudge appended when the RAG knowledge-base tool is active: ground answers in@@ -4733,19 +4738,125 @@ def _apply_compaction_nudge(async def _apply_rag_nudge(nudge: str, tools: list[dict], *, rag_scope) -> str:"""Append the RAG grounding nudge to ``nudge`` when the knowledge-base tool- is active (search_knowledge_base present and a retrieval scope is set). The- date is prefixed when the tool nudge is empty (RAG-only tool set). Returns- ``nudge`` unchanged when RAG isn't active."""+ is active (search_knowledge_base present and a retrieval scope is set).+ Returns ``nudge`` unchanged when RAG isn't active."""tool_names = {(t.get("function") or {}).get("name") for t in (tools or [])}if "search_knowledge_base" not in tool_names or not rag_scope:return nudgegrounding = _RAG_GROUNDING_NUDGE + await _rag_roster_sentence(rag_scope)if not nudge:- date_line = f"The current date is {_date.today().isoformat()}."- return date_line + " " + grounding+ return groundingreturn nudge + " " + grounding+def _refresh_stated_date(content: Any, date_line: str) -> tuple[Any, bool, bool]:+ if isinstance(content, str):+ stated = contains_current_date_prompt_line(content)+ refreshed = replace_current_date_prompt_lines(content, date_line)+ return refreshed, stated, refreshed != content+ if not isinstance(content, list):+ return content, False, False+ refreshed_parts = list(content)+ stated = False+ changed = False+ for index, part in enumerate(content):+ if not isinstance(part, dict) or not isinstance(part.get("text"), str):+ continue+ stated = stated or contains_current_date_prompt_line(part["text"])+ refreshed_text = replace_current_date_prompt_lines(part["text"], date_line)+ if refreshed_text == part["text"]:+ continue+ refreshed_parts[index] = {**part, "text": refreshed_text}+ changed = True+ return refreshed_parts, stated, changed+++def _wants_current_date(request: Any) -> bool:+ """Whether this caller's prompt is Studio's to compose: an interactive session, nothing else.++ The router is also mounted at /v1, so a third party's sk-unsloth key reaches the same+ handlers, and their request is theirs verbatim. Studio's own workflow keys are excluded too:+ a data recipe generates a dataset, and Deep Research decides once at run creation and stamps+ the answer into its config, so injecting here would override the state the run started in.+ """+ return not _request_has_api_key(request)+++def _apply_current_date_prompt(+ system_prompt: str,+ request: Any = None,+ *,+ include_api_key: bool = False,+) -> str:+ """Prefix the user's system prompt with today's date when the setting is on.++ Kept ahead of the user's own text so a system prompt that ends in an instruction still reads+ as the last word to the model.+ """+ if request is not None and not _wants_current_date(request):+ if not include_api_key or _request_is_internal_workflow(request):+ return system_prompt+ date_line = current_date_prompt_line(request = request)+ if not date_line:+ return system_prompt+ refreshed_prompt, stated, _ = _refresh_stated_date(system_prompt, date_line)+ if stated:+ return refreshed_prompt+ return f"{date_line}\n\n{system_prompt.lstrip()}" if system_prompt else date_line+++def _prepend_current_date_to_messages(+ messages: list[dict],+ request: Any = None,+ *,+ include_api_key: bool = False,+) -> list[dict]:+ """Apply the date to an already-built message list for a provider Studio proxies to.++ The local path prefixes ``system_prompt`` before the messages exist; an external payload is+ assembled first, so the date goes onto its leading system turn instead.+ """+ if request is not None and not _wants_current_date(request):+ if not include_api_key or _request_is_internal_workflow(request):+ return messages+ date_line = current_date_prompt_line(request = request)+ if not date_line:+ return messages+ copied = [dict(msg) for msg in messages]+ stated = False+ refreshed = False+ for msg in copied:+ if msg.get("role") not in ("system", "developer"):+ continue+ content, content_stated, changed = _refresh_stated_date(msg.get("content"), date_line)+ stated = stated or content_stated+ if changed:+ msg["content"] = content+ refreshed = True+ if stated:+ if not refreshed:+ return messages+ return copied+ for msg in copied:+ if msg.get("role") not in ("system", "developer"):+ continue+ content = msg.get("content", "")+ if isinstance(content, str):+ msg["content"] = date_line + "\n\n" + content.lstrip()+ return copied+ if isinstance(content, list):+ copied_parts = [dict(part) if isinstance(part, dict) else part for part in content]+ for part in copied_parts:+ if not isinstance(part, dict) or not isinstance(part.get("text"), str):+ continue+ part["text"] = date_line + "\n\n" + part["text"].lstrip()+ msg["content"] = copied_parts+ return copied+ msg["content"] = [{"type": "text", "text": date_line}, *copied_parts]+ return copied+ return [{"role": "system", "content": date_line}, *copied]++# Strip leaked tool-call markup: every shared-parser format plus the leak shapes# llama_cpp.py's speculative buffer splits across the visible/DRAIN boundary:# 1. well-formed `<tool_call>...</tool_call>` / `<function=...>...</function>`@@ -17793,6 +17904,11 @@ async def _proxy_to_external_provider(chat_messages = _append_to_codex_instructions(chat_messages, _codex_full_access_nudge)+ chat_messages = _prepend_current_date_to_messages(+ chat_messages,+ request,+ include_api_key = bool(studio_tool_payloads),+ )cancel_event = threading.Event()cancel_keys = tuple(key for key in (payload.cancel_id, payload.session_id) if key)@@ -18086,6 +18202,11 @@ async def _proxy_to_external_provider(mcp_allowed = bool(payload.mcp_enabled),)run_studio_tool_loop = bool(external_studio_tools)+ chat_messages = _prepend_current_date_to_messages(+ chat_messages,+ request,+ include_api_key = run_studio_tool_loop,+ )if run_studio_tool_loop and payload.bypass_permissions:# Full access disables the sandbox at execution time, so the schemas must# say so too rather than describing a sandbox the model will not get.@@ -19049,6 +19170,7 @@ async def produce_openai_chat_completions(else _decode_audio_base64(payload.audio_base64))system_prompt, chat_messages, _ = _extract_content_parts(payload.messages)+ system_prompt = _apply_current_date_prompt(system_prompt, request)except Exception as e:api_monitor.fail(monitor_id, _friendly_error(e))raise@@ -19464,6 +19586,8 @@ async def produce_openai_chat_completions(system_prompt, chat_messages, extracted_image_b64 = _pre_parsedelse:system_prompt, chat_messages, extracted_image_b64 = _extract_content_parts(payload.messages)+ # applied once so both backends inherit it, with or without tools, and never state it twice.+ system_prompt = _apply_current_date_prompt(system_prompt, request)if not chat_messages:raise _reject(400, "At least one non-system message is required.")@@ -19654,6 +19778,12 @@ async def produce_openai_chat_completions()if _wants_multiple_choices(payload):raise _reject_unsupported_n("GGUF tool chat completions")+ system_prompt = _apply_current_date_prompt(+ system_prompt,+ request,+ include_api_key = True,+ )+ gguf_messages = _set_or_prepend_system_message(gguf_messages, system_prompt)# ── Tool-use system prompt nudge ──────────────────────_nudge = _build_tool_action_nudge(tools = tools_to_use,@@ -21344,7 +21474,11 @@ async def produce_openai_chat_completions(# is no reset and no carried_forward block to describe._sf_nudge = _apply_compaction_nudge(_sf_nudge, _sf_tools_to_use)- _sf_system_prompt = system_prompt+ _sf_system_prompt = _apply_current_date_prompt(+ system_prompt,+ request,+ include_api_key = True,+ )if _sf_nudge:if _sf_system_prompt:_sf_system_prompt = _sf_system_prompt.rstrip() + "\n\n" + _sf_nudge@@ -25651,7 +25785,9 @@ def _append_to_system_message(messages: list[dict], addition: str) -> list[dict]@router.post("/chat/count_tokens")async def chat_count_tokens(- payload: ChatCountTokensRequest, current_subject: str = Depends(get_current_subject)+ payload: ChatCountTokensRequest,+ current_subject: str = Depends(get_current_subject),+ request: Request = None,):"""Count prompt tokens for OpenAI-form chat messages using the loaded tokenizer.@@ -25707,6 +25843,9 @@ async def chat_count_tokens(if not _takes_passthrough:openai_messages = _coalesce_consecutive_user_turns(openai_messages)_system_prompt, _, _ = _extract_content_parts(payload.messages)+ # the verbatim passthrough carries no date line, so counting one here would overcount it.+ if not _takes_passthrough:+ _system_prompt = _apply_current_date_prompt(_system_prompt, request)openai_messages = _set_or_prepend_system_message(openai_messages, _system_prompt)# A PENDING turn (unanswered user message or tool result) is the one shape the tool loop@@ -25767,6 +25906,11 @@ async def chat_count_tokens(tools_to_use = tools_to_use + _mcp_toolsif tools_to_use:openai_tools = tools_to_use+ openai_messages = _prepend_current_date_to_messages(+ openai_messages,+ request,+ include_api_key = True,+ )_count_nudge = await _apply_rag_nudge(_build_tool_action_nudge(tools = tools_to_use,@@ -25913,6 +26057,34 @@ async def anthropic_count_tokens(_strip_provider_synthetic_tool_history(_drop_empty_assistant_sentinels(openai_messages)))openai_tools = anthropic_tools_to_openai(payload.tools or []) or None+ # Only the client-tool passthrough is forwarded verbatim, so reproduce /messages' own+ # routing rather than "any tools": a Studio server-tool alias, or a template without+ # passthrough support, falls through to plain generation there and does carry the date.+ _count_studio_tools = _anthropic_requested_studio_tools(payload.tools)+ _count_has_client_tool = any(+ (t if isinstance(t, dict) else t.model_dump()).get("input_schema") is not None+ or anthropic_schema_client_tool_kind(t) is not None+ for t in payload.tools or []+ )+ _count_server_tools = (+ _anthropic_selects_server_tools(payload, _count_studio_tools, _count_has_client_tool)+ and llama_backend.supports_tools+ and not _anthropic_request_has_image(payload)+ )+ _count_client_tools = (+ not _count_server_tools+ and any(+ tool.get("function", {}).get("name") not in _count_studio_tools+ for tool in anthropic_tools_to_openai(payload.tools or [])+ )+ and getattr(llama_backend, "supports_tool_passthrough", llama_backend.supports_tools)+ )+ if not _count_client_tools:+ openai_messages = _prepend_current_date_to_messages(+ openai_messages,+ request,+ include_api_key = _count_server_tools,+ )# Render with the same reasoning controls generation will use: on switchable# templates thinking / reasoning_effort / preserve_thinking change the@@ -26208,6 +26380,15 @@ async def anthropic_messages(and getattr(llama_backend, "supports_tool_passthrough", llama_backend.supports_tools))+ # Studio composes the prompt on every branch but the client-tool passthrough, which forwards+ # the caller's own request verbatim (mirrors the GGUF passthrough gate in /chat/completions).+ if not client_tools:+ openai_messages = _prepend_current_date_to_messages(+ openai_messages,+ request,+ include_api_key = server_tools,+ )+# Anthropic tool_choice.disable_parallel_tool_use caps the response to a# single tool_use block. Computed here so BOTH the client-tool passthrough# and the server-tool path honor it.diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex ca8e2fb5029..61470127463 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -24,6 +24,7 @@ from storage import research_runs_db as dbfrom core.inference.providers import provider_runs_local_toolsfrom storage import providers_dbfrom storage.studio_db import get_chat_message, get_chat_thread, upsert_chat_message+from utils.current_date_prompt_settings import current_date_prompt_linerouter = APIRouter()_SENSITIVE_KEY_EXACT = {@@ -193,7 +194,11 @@ def _contains_sensitive_key(value: object) -> bool:return False-def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:+def _sanitize_config(+ payload: CreateResearchRun,+ thread: dict,+ http_request: Request = None,+) -> dict:request = dict(payload.inferenceRequest)if _contains_sensitive_key(request):raise HTTPException(status_code = 400, detail = "Inference credentials cannot be persisted")@@ -366,6 +371,8 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:"budgets": budgets,"websitePolicy": website_policy,"instructions": (payload.instructions or "").strip(),+ # 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(),}@@ -393,7 +400,7 @@ def create_research_run(status_code = 400,detail = "Deep research requires a user message with non-empty text",)- config = _sanitize_config(payload, thread)+ config = _sanitize_config(payload, thread, request)try:if db.has_thread_claim(payload.threadId):# The thread's one run was stopped, so it is re-pointed at this question ratherdiff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex bb7dfbfcd81..932270705f0 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -120,6 +120,11 @@ from utils.preview_sharing_settings import (get_preview_sharing_enabled,set_preview_sharing_enabled,)+from utils.current_date_prompt_settings import (+ DEFAULT_CURRENT_DATE_PROMPT_ENABLED,+ get_current_date_prompt_enabled,+ set_current_date_prompt_enabled,+)from utils.lan_access_settings import (lan_access_status,set_lan_access_auto_start,@@ -2886,6 +2891,15 @@ class PreviewSharingResponse(BaseModel):default_enabled: bool = DEFAULT_PREVIEW_SHARING_ENABLED+class CurrentDatePromptPayload(BaseModel):+ enabled: StrictBool+++class CurrentDatePromptResponse(BaseModel):+ enabled: bool+ default_enabled: bool = DEFAULT_CURRENT_DATE_PROMPT_ENABLED++class RemoteAccessAutoStartPayload(BaseModel):enabled: StrictBool@@ -3083,6 +3097,34 @@ def update_preview_sharing(return PreviewSharingResponse(enabled = enabled)[email protected]("/current-date-prompt", response_model = CurrentDatePromptResponse)+def get_current_date_prompt(+ current_subject: str = Depends(get_current_subject),+) -> CurrentDatePromptResponse:+ return CurrentDatePromptResponse(enabled = get_current_date_prompt_enabled())++[email protected]("/current-date-prompt", response_model = CurrentDatePromptResponse)+def update_current_date_prompt(+ payload: CurrentDatePromptPayload, current_subject: str = Depends(get_current_subject)+) -> CurrentDatePromptResponse:+ """Enable/disable telling the model today's date in chat and Deep Research prompts."""+ try:+ enabled = set_current_date_prompt_enabled(payload.enabled)+ except ValueError as exc:+ raise log_and_http_error(+ exc,+ 400,+ safe_error_detail(exc, fallback = "Invalid current date prompt setting."),+ event = "settings.update_current_date_prompt_failed",+ log = logger,+ ) from exc+ logger.info(+ "settings.current_date_prompt_updated subject=%s enabled=%s", current_subject, enabled+ )+ return CurrentDatePromptResponse(enabled = enabled)++def _require_ui_session_for_keyless(via_api_key: bool = Depends(authenticated_via_api_key)) -> None:"""Only a signed-in UI session may change who needs a key.diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex e2ca7d6cb2f..93e7a199cd1 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -467,8 +467,9 @@ class TestToolActionNudge:model_name = "Llama-3.1-70B-Instruct",)- assert nudge.startswith("The current date is ")- assert "Tools are available when they materially improve" in nudge+ # the date rides on the system prompt now, not the nudge.+ assert "The current date is " not in nudge+ assert nudge.startswith("Tools are available when they materially improve")assert "prefer using tools rather than answering from memory" not in nudgeassert "fetch its full content by calling web_search with the url parameter" in nudgeassert "Use code execution for math" in nudge@@ -2206,6 +2207,10 @@ def _mock_backend(monkeypatch, **overrides):"""import routes.inference as inf_mod+ # Pinned off by default so prompt assertions do not depend on the host's stored setting;+ # the date's own behaviour on this route is covered in test_current_date_prompt_settings.+ monkeypatch.setattr(inf_mod, "current_date_prompt_line", lambda **_kwargs: "")+calls = []def _gen_plain(**kwargs):@@ -2282,6 +2287,25 @@ class TestAnthropicMessagesToolRouting:return _drive(_consume())+ def test_plain_non_streaming_states_the_current_date(self, monkeypatch):+ # /v1/messages used to get the date from the tool nudge; it now rides the system turn,+ # so this route needs its own coverage or the date silently disappears from it.+ import routes.inference as inf_mod++ backend = _mock_backend(monkeypatch, context_length = 2048)+ monkeypatch.setattr(+ inf_mod,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )+ _drive(anthropic_messages(_basic_payload(), request = self._Request(), current_subject = "t"))++ [(_path, kwargs)] = backend.calls+ assert kwargs["messages"][0] == {+ "role": "system",+ "content": "The current date is 2026-08-15.",+ }+def test_plain_non_streaming_records_api_monitor_entry(self, monkeypatch):import routes.inference as inf_mod@@ -2722,6 +2746,30 @@ class TestAnthropicMessagesToolRouting:_drive(anthropic_messages(payload, request = None, current_subject = "t"))assert backend.calls[0][0] == "tools"+ def test_api_server_tool_request_keeps_the_current_date(self, monkeypatch):+ import routes.inference as inf_mod++ backend = _mock_backend(monkeypatch)+ monkeypatch.setattr(+ inf_mod,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )+ monkeypatch.setattr(inf_mod, "_request_is_internal_workflow", lambda _request: False)++ class ApiRequest(self._Request):+ headers = {"authorization": "Bearer sk-unsloth-test"}+ state = SimpleNamespace(skip_api_monitor = True)++ payload = _basic_payload(+ tools = [{"type": "web_search_20250305", "name": "web_search"}],+ )+ _drive(anthropic_messages(payload, request = ApiRequest(), current_subject = "t"))++ call_kind, kwargs = backend.calls[0]+ assert call_kind == "tools"+ assert kwargs["messages"][0]["content"].startswith("The current date is 2026-08-15.\n\n")+def test_server_tool_choice_alias_uses_the_selected_studio_name(self, monkeypatch):backend = _mock_backend(monkeypatch)payload = _basic_payload(diff --git a/studio/backend/tests/test_current_date_prompt_settings.py b/studio/backend/tests/test_current_date_prompt_settings.pynew file mode 100644index 00000000000..bdb18e4b2be--- /dev/null+++ b/studio/backend/tests/test_current_date_prompt_settings.py@@ -0,0 +1,375 @@+# 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 current-date preference: its endpoints, and the prompts it feeds."""++from datetime import date, datetime, timezone+from pathlib import Path+import sys+import types as _types+++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.settings as settings+import utils.current_date_prompt_settings as current_date_settings+from core.research.prompts import _system_prompt_with_instructions+++def client(monkeypatch):+ calls: dict = {"enabled": True}++ def _set(value):+ calls["set"] = bool(value)+ calls["enabled"] = bool(value)+ return bool(value)++ monkeypatch.setattr(settings, "get_current_date_prompt_enabled", lambda: calls["enabled"])+ monkeypatch.setattr(settings, "set_current_date_prompt_enabled", _set)++ app = FastAPI()+ app.include_router(settings.router)+ app.dependency_overrides[settings.get_current_subject] = lambda: "admin"+ return TestClient(app, raise_server_exceptions = False), calls+++def test_get_current_date_prompt(client):+ c, _ = client+ r = c.get("/current-date-prompt")+ assert r.status_code == 200+ body = r.json()+ assert body["enabled"] is True+ assert body["default_enabled"] is True+++def test_put_current_date_prompt_disables(client):+ c, calls = client+ r = c.put("/current-date-prompt", json = {"enabled": False})+ assert r.status_code == 200+ assert r.json()["enabled"] is False+ assert calls["set"] is False+++def test_put_current_date_prompt_rejects_non_bool(client):+ c, _ = client+ r = c.put("/current-date-prompt", json = {"enabled": "maybe"})+ assert r.status_code == 422+++class TestCurrentDatePromptLine:+ def test_line_states_the_iso_date_when_enabled(self, monkeypatch):+ monkeypatch.setattr(current_date_settings, "get_current_date_prompt_enabled", lambda: True)+ assert (+ current_date_settings.current_date_prompt_line(date(2026, 8, 15))+ == "The current date is 2026-08-15."+ )++ def test_system_prompt_helper_refreshes_a_stale_date(self, monkeypatch):+ import routes.inference as inference++ monkeypatch.setattr(+ inference,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )+ already = "The current date is 2026-08-14.\n\nBASE"+ assert (+ inference._apply_current_date_prompt(already)+ == "The current date is 2026-08-15.\n\nBASE"+ )++ def test_system_prompt_helper_does_not_duplicate_the_current_date(self, monkeypatch):+ import routes.inference as inference++ monkeypatch.setattr(+ inference,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )+ prompt = "The current date is 2026-08-15.\n\nBASE"+ assert inference._apply_current_date_prompt(prompt) == prompt++ def test_discussing_the_date_phrase_does_not_suppress_injection(self, monkeypatch):+ import routes.inference as inference++ monkeypatch.setattr(+ inference,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )+ prompt = "The current date is a phrase this prompt discusses, not a date stamp."+ assert (+ inference._apply_current_date_prompt(prompt)+ == f"The current date is 2026-08-15.\n\n{prompt}"+ )++ def test_line_is_empty_when_disabled(self, monkeypatch):+ monkeypatch.setattr(current_date_settings, "get_current_date_prompt_enabled", lambda: False)+ assert current_date_settings.current_date_prompt_line(date(2026, 8, 15)) == ""++ def test_request_timezone_decides_the_calendar_date(self):+ request = _types.SimpleNamespace(+ headers = {+ current_date_settings.CURRENT_DATE_TIMEZONE_HEADER: "Pacific/Auckland",+ }+ )+ instant = datetime(2026, 8, 28, 12, 30, tzinfo = timezone.utc)+ assert current_date_settings._request_local_date(request, instant) == date(2026, 8, 29)++ def test_request_offset_is_used_when_timezone_is_unknown(self):+ request = _types.SimpleNamespace(+ headers = {+ current_date_settings.CURRENT_DATE_TIMEZONE_HEADER: "Invalid/Zone",+ current_date_settings.CURRENT_DATE_TIMEZONE_OFFSET_HEADER: "-720",+ }+ )+ instant = datetime(2026, 8, 28, 12, 30, tzinfo = timezone.utc)+ assert current_date_settings._request_local_date(request, instant) == date(2026, 8, 29)++ def test_research_run_stamp_receives_the_http_request(self, monkeypatch):+ import routes.research_runs as research_routes++ request = _types.SimpleNamespace(headers = {"x-unsloth-timezone": "Pacific/Auckland"})+ monkeypatch.setattr(+ research_routes,+ "current_date_prompt_line",+ lambda **kwargs: kwargs["request"].headers["x-unsloth-timezone"],+ )+ payload = research_routes.CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "message-1",+ inferenceRequest = {"model": "local-model"},+ )++ config = research_routes._sanitize_config(payload, {"modelId": "local-model"}, request)++ assert config["currentDate"] == "Pacific/Auckland"++ def test_unreadable_settings_still_default_to_enabled(self, monkeypatch):+ def _explode(*_args, **_kwargs):+ raise RuntimeError("settings db unavailable")++ monkeypatch.setitem(+ sys.modules,+ "storage.studio_db",+ _types.SimpleNamespace(get_app_setting = _explode),+ )+ assert current_date_settings.get_current_date_prompt_enabled() is True+++class TestExternalProviderMessages:+ """vLLM, Ollama, OpenAI and custom connections are proxied, so the date goes on the payload."""++ @staticmethod+ def _prepend(messages):+ import routes.inference as inference+ return inference._prepend_current_date_to_messages(messages)++ @pytest.fixture(autouse = True)+ def _enabled(self, monkeypatch):+ import routes.inference as inference+ monkeypatch.setattr(+ inference,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )++ def test_date_prefixes_an_existing_system_turn(self):+ out = self._prepend(+ [{"role": "system", "content": "Be terse."}, {"role": "user", "content": "hi"}]+ )+ assert out[0]["content"] == "The current date is 2026-08-15.\n\nBe terse."+ assert out[1] == {"role": "user", "content": "hi"}++ def test_system_turn_is_created_when_absent(self):+ out = self._prepend([{"role": "user", "content": "hi"}])+ assert out[0] == {"role": "system", "content": "The current date is 2026-08-15."}+ assert out[1] == {"role": "user", "content": "hi"}++ def test_date_prefixes_text_inside_structured_system_content(self):+ messages = [{"role": "system", "content": [{"type": "text", "text": "Be terse."}]}]+ out = self._prepend(messages)+ assert len(out) == 1+ assert out[0]["content"] == [+ {"type": "text", "text": "The current date is 2026-08-15.\n\nBe terse."}+ ]+ assert messages[0]["content"] == [{"type": "text", "text": "Be terse."}]++ def test_date_becomes_a_text_part_when_structured_content_has_none(self):+ messages = [+ {+ "role": "system",+ "content": [{"type": "image_url", "image_url": {"url": "data:image/png,x"}}],+ }+ ]+ out = self._prepend(messages)+ assert len(out) == 1+ assert out[0]["content"][0] == {+ "type": "text",+ "text": "The current date is 2026-08-15.",+ }+ assert out[0]["content"][1] == messages[0]["content"][0]++ def test_developer_turn_is_used_when_there_is_no_system_turn(self):+ out = self._prepend([{"role": "developer", "content": "Be terse."}])+ assert out[0]["content"] == "The current date is 2026-08-15.\n\nBe terse."++ def test_messages_are_untouched_when_disabled(self, monkeypatch):+ import routes.inference as inference++ monkeypatch.setattr(inference, "current_date_prompt_line", lambda **_kwargs: "")+ messages = [{"role": "user", "content": "hi"}]+ assert self._prepend(messages) is messages++ def test_a_stale_date_is_refreshed_for_an_interactive_request(self):+ stamped = [+ {"role": "system", "content": "The current date is 2026-08-14.\n\nBe terse."},+ {"role": "user", "content": "hi"},+ ]+ refreshed = self._prepend(stamped)+ assert refreshed[0]["content"] == "The current date is 2026-08-15.\n\nBe terse."+ assert stamped[0]["content"] == "The current date is 2026-08-14.\n\nBe terse."++ def test_a_stale_date_buried_under_instructions_is_refreshed(self):+ buried = [+ {+ "role": "system",+ "content": (+ "Chat-specific instructions follow.\n"+ "<chat_instructions>\nBe terse.\n</chat_instructions>\n\n"+ "Non-overridable rules:\nThe current date is 2026-08-14.\n\nBASE"+ ),+ }+ ]+ refreshed = self._prepend(buried)+ assert "The current date is 2026-08-15." in refreshed[0]["content"]+ assert "The current date is 2026-08-14." not in refreshed[0]["content"]++ def test_a_stale_date_on_a_later_system_turn_is_refreshed(self):+ messages = [+ {"role": "system", "content": "Be terse."},+ {"role": "developer", "content": "The current date is 2026-08-14."},+ {"role": "user", "content": "hi"},+ ]+ refreshed = self._prepend(messages)+ assert refreshed[0]["content"] == "Be terse."+ assert refreshed[1]["content"] == "The current date is 2026-08-15."++ def test_any_api_key_request_is_left_verbatim(self, monkeypatch):+ # studio's own workflow keys are excluded too, not just third-party sk-unsloth callers.+ import routes.inference as inference++ monkeypatch.setattr(inference, "_request_has_api_key", lambda _request: True)+ messages = [{"role": "user", "content": "hi"}]+ assert inference._prepend_current_date_to_messages(messages, object()) is messages+ assert inference._apply_current_date_prompt("Be terse.", object()) == "Be terse."++ def test_server_tool_loop_can_date_an_api_key_request(self, monkeypatch):+ import routes.inference as inference++ monkeypatch.setattr(inference, "_request_has_api_key", lambda _request: True)+ messages = [{"role": "user", "content": "hi"}]+ out = inference._prepend_current_date_to_messages(+ messages,+ object(),+ include_api_key = True,+ )+ assert out[0] == {"role": "system", "content": "The current date is 2026-08-15."}++ def test_server_tool_loop_keeps_an_internal_workflow_stamp(self, monkeypatch):+ import routes.inference as inference++ monkeypatch.setattr(inference, "_request_has_api_key", lambda _request: True)+ monkeypatch.setattr(inference, "_request_is_internal_workflow", lambda _request: True)+ messages = [{"role": "system", "content": "The current date is 2026-08-14."}]+ out = inference._prepend_current_date_to_messages(+ messages,+ object(),+ include_api_key = True,+ )+ assert out is messages++ def test_a_studio_session_request_is_dated(self, monkeypatch):+ import routes.inference as inference++ monkeypatch.setattr(inference, "_request_has_api_key", lambda _request: False)+ out = inference._prepend_current_date_to_messages(+ [{"role": "user", "content": "hi"}], object()+ )+ assert out[0] == {"role": "system", "content": "The current date is 2026-08-15."}++ def test_a_stale_date_inside_a_text_part_is_refreshed(self):+ messages = [+ {+ "role": "system",+ "content": [{"type": "text", "text": "The current date is 2026-08-14."}],+ },+ {"role": "user", "content": "hi"},+ ]+ refreshed = self._prepend(messages)+ assert refreshed[0]["content"][0]["text"] == "The current date is 2026-08-15."+ assert messages[0]["content"][0]["text"] == "The current date is 2026-08-14."++ def test_a_phrase_discussion_inside_a_text_part_does_not_suppress(self):+ messages = [+ {+ "role": "system",+ "content": [+ {+ "type": "text",+ "text": "The current date is merely a phrase under discussion.",+ },+ ],+ },+ {"role": "user", "content": "hi"},+ ]+ out = self._prepend(messages)+ assert len(out) == len(messages)+ assert out[0]["content"][0]["text"].startswith("The current date is 2026-08-15.\n\n")+ assert out[1:] == messages[1:]+++class TestResearchSystemPrompt:+ """Every Deep Research call (planner, agent, audit, report) goes through this helper."""++ def test_stamped_date_is_prefixed(self):+ prompt = _system_prompt_with_instructions(+ "BASE", {"currentDate": "The current date is 2026-08-15."}+ )+ assert prompt == "The current date is 2026-08-15.\n\nBASE"++ def test_date_precedes_the_non_overridable_rules_with_instructions(self):+ prompt = _system_prompt_with_instructions(+ "BASE",+ {"currentDate": "The current date is 2026-08-15.", "instructions": "Be terse."},+ )+ assert "<chat_instructions>\nBe terse.\n</chat_instructions>" in prompt+ assert prompt.endswith("Non-overridable rules:\nThe current date is 2026-08-15.\n\nBASE")++ def test_stale_manual_date_is_removed_from_instructions(self):+ prompt = _system_prompt_with_instructions(+ "BASE",+ {+ "currentDate": "The current date is 2026-08-15.",+ "instructions": "The current date is 2025-03-01.\nBe terse.",+ },+ )+ assert "The current date is 2025-03-01." not in prompt+ assert prompt.count("The current date is 2026-08-15.") == 1+ assert "<chat_instructions>\nBe terse.\n</chat_instructions>" in prompt++ def test_run_without_a_stamped_date_is_unchanged(self):+ # runs created before the field existed, and runs started with the setting off.+ assert _system_prompt_with_instructions("BASE", {}) == "BASE"+ assert _system_prompt_with_instructions("BASE", {"currentDate": ""}) == "BASE"diff --git a/studio/backend/tests/test_external_hosted_tool_passthrough.py b/studio/backend/tests/test_external_hosted_tool_passthrough.pyindex b3bf4938545..4a05b79e7d4 100644--- a/studio/backend/tests/test_external_hosted_tool_passthrough.py+++ b/studio/backend/tests/test_external_hosted_tool_passthrough.py@@ -178,6 +178,46 @@ def test_a_hosted_tool_request_still_reaches_the_provider(monkeypatch, provider_assert any("hi" in chunk for chunk in chunks)[email protected]("provider_type", HOSTED_PROVIDERS)+def test_a_studio_hosted_provider_receives_the_current_date(monkeypatch, provider_type):+ inf = _install(monkeypatch, provider_type)+ monkeypatch.setattr(+ inf,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )++ _run(inf, _payload())++ messages = FakeExternalClient.last["passthrough"]["messages"]+ assert messages[0] == {"role": "system", "content": "The current date is 2026-08-15."}+ assert messages[1] == {"role": "user", "content": "what is 2+2?"}+++def test_an_api_request_without_resolved_server_tools_stays_undated(monkeypatch):+ inf = _install(monkeypatch, "openai")+ monkeypatch.setattr(inf, "_request_has_api_key", lambda _request: True)+ monkeypatch.setattr(inf, "_request_is_internal_workflow", lambda _request: False)+ monkeypatch.setattr(+ inf,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )++ _run(+ inf,+ _payload(+ enable_tools = True,+ enabled_tools = ["unknown_tool"],+ run_tools_locally = True,+ ),+ )++ assert FakeExternalClient.last["passthrough"]["messages"] == [+ {"role": "user", "content": "what is 2+2?"}+ ]++def test_a_hosted_code_execution_is_not_dropped(monkeypatch):"""The regression in one line: `code_execution` has no local implementation,so a loop that captures this request executes web_search itself and silentlydiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 98d5d698f7e..76f24d0f097 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -3912,6 +3912,9 @@ def _count_tokens_backend(backend.count_chat_tokens = _countmonkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _switch)+ # Pinned off so message-shape assertions do not depend on the host's stored setting;+ # test_chat_count_tokens_prices_the_current_date covers the date's own effect on the count.+ monkeypatch.setattr(inference_route, "current_date_prompt_line", lambda **_kwargs: "")return switched, counted@@ -4151,6 +4154,63 @@ def test_chat_count_tokens_keeps_adjacent_user_turns_on_the_passthrough(monkeypa]+def test_chat_count_tokens_prices_the_current_date(monkeypatch):+ """The bar has to price what generation sends, and only the passthrough is sent undated."""+ _switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)+ monkeypatch.setattr(+ inference_route,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )+ thread = [{"role": "user", "content": "hi"}]++ _counted_body(_count_request(thread))+ assert counted["messages"][0] == {+ "role": "system",+ "content": "The current date is 2026-08-15.",+ }++ # The passthrough forwards the caller's request verbatim, so counting a date it never sends+ # would overcount exactly those prompts.+ _counted_body(_count_request(thread, tools = _PASSTHROUGH_CATALOG))+ assert all(message.get("role") != "system" for message in counted["messages"])+++def test_chat_count_tokens_dates_only_api_server_tool_prompts(monkeypatch):+ _switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)+ monkeypatch.setattr(+ inference_route,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )++ async def _select(_payload, *, tools_on, mcp_allowed):+ return [{"type": "function", "function": {"name": "web_search"}}]++ monkeypatch.setattr(inference_route, "_select_request_tools", _select)+ monkeypatch.setattr(+ inference_route,+ "_request_is_internal_workflow",+ lambda _request: False,+ )+ request = types.SimpleNamespace(+ headers = {"authorization": "Bearer sk-unsloth-test"},+ )+ thread = [{"role": "user", "content": "hi"}]++ asyncio.run(+ inference_route.chat_count_tokens(+ _count_request(thread, enable_tools = True, enabled_tools = ["web_search"]),+ "tester",+ request,+ )+ )+ assert counted["messages"][0]["content"].startswith("The current date is 2026-08-15.\n\n")++ asyncio.run(inference_route.chat_count_tokens(_count_request(thread), "tester", request))+ assert all(message.get("role") != "system" for message in counted["messages"])++def _in_flight_generation():"""One registered generation, as the completion path registers it."""from state import active_generationsdiff --git a/studio/backend/tests/test_openai_codex_subscription.py b/studio/backend/tests/test_openai_codex_subscription.pyindex fdba51e6996..1629f326e40 100644--- a/studio/backend/tests/test_openai_codex_subscription.py+++ b/studio/backend/tests/test_openai_codex_subscription.py@@ -1539,6 +1539,85 @@ def _codex_chat_gate(return excinfo.value+def test_codex_chat_receives_the_current_date(monkeypatch):+ from models.inference import ChatCompletionRequest+ from routes import inference as inf++ model = get_provider_info("openai_codex")["default_models"][0]+ monkeypatch.setattr(+ inf.providers_db,+ "get_provider",+ lambda _pid: {+ "id": _pid,+ "provider_type": "openai_codex",+ "base_url": OPENAI_CODEX_API_BASE,+ "display_name": "ChatGPT subscription",+ "is_enabled": True,+ "models": [model],+ },+ )+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-1"})+ monkeypatch.setattr(codex_client, "subscription_catalog_matches_account", lambda *_args: True)+ monkeypatch.setattr(codex_client, "subscription_catalog_known", lambda _pid: False)+ monkeypatch.setattr(codex_client, "subscription_catalog_stale", lambda _pid: False)+ monkeypatch.setattr(codex_client, "saved_models_proven_for", lambda *_args: True)++ async def _resolve_access(_provider_id, **_kwargs):+ return "token", "acct-1"++ monkeypatch.setattr(codex_auth, "resolve_access", _resolve_access)+ captured = {}++ class FakeCodexClient:+ def __init__(self, *_args, **_kwargs):+ pass++ def stream(self, **kwargs):+ captured.update(kwargs)++ async def _stream():+ yield 'data: {"type":"response.completed"}'++ return _stream()++ async def close(self):+ pass++ monkeypatch.setattr(codex_client, "OpenAICodexClient", FakeCodexClient)+ monkeypatch.setattr(+ inf,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )++ async def _is_disconnected():+ return False++ request = SimpleNamespace(+ headers = {},+ state = SimpleNamespace(skip_api_monitor = True),+ is_disconnected = _is_disconnected,+ )+ payload = ChatCompletionRequest(+ messages = [{"role": "user", "content": "hello"}],+ provider_id = "codex-1",+ external_model = model,+ stream = True,+ )++ async def _run():+ response = await inf._proxy_to_external_provider(payload, request, current_subject = "t")+ return [chunk async for chunk in response.body_iterator]++ asyncio.run(_run())++ assert captured["messages"][0] == {+ "role": "system",+ "content": "The current date is 2026-08-15.",+ }+ assert captured["messages"][1] == {"role": "user", "content": "hello"}++def test_chat_accepts_a_plan_listed_slug_the_seed_does_not_carry(monkeypatch):"""A slug the picker offered and the provider routes saved must be chattable.diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex fcae77f27fd..c96d4b1ca80 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -3600,6 +3600,7 @@ class TestGgufVisionToolRouting:tool_generate = None,payload_kwargs = None,backend_kwargs = None,+ request = None,):import routes.inference as inf_mod@@ -3637,7 +3638,11 @@ class TestGgufVisionToolRouting:request_data.update(payload_kwargs)payload = ChatCompletionRequest(**request_data)response = self._drive(- openai_chat_completions(payload, request = self._Request(), current_subject = "test")+ openai_chat_completions(+ payload,+ request = request or self._Request(),+ current_subject = "test",+ ))result = SimpleNamespace(response = response, monitor = monitor, backend = backend)if request_data.get("stream"):@@ -3809,6 +3814,43 @@ class TestGgufVisionToolRouting:}assert captured["kwargs"]["permission_mode"] == "off"+ def test_api_server_tool_loop_keeps_the_current_date(self, monkeypatch):+ import routes.inference as inf_mod++ captured = {}++ def _tools(**kwargs):+ captured.update(kwargs)+ yield {"type": "content", "text": "done"}++ class ApiRequest(self._Request):+ headers = {"authorization": "Bearer sk-unsloth-test"}+ state = SimpleNamespace(skip_api_monitor = True)++ monkeypatch.setattr(+ inf_mod,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )+ monkeypatch.setattr(inf_mod, "_request_is_internal_workflow", lambda _request: False)+ self._run_gguf_case(+ monkeypatch,+ tool_generate = _tools,+ payload_kwargs = {+ "enable_tools": True,+ "enabled_tools": ["web_search"],+ "permission_mode": "off",+ "stream": True,+ },+ request = ApiRequest(),+ )++ system_messages = [+ message for message in captured["messages"] if message["role"] == "system"+ ]+ assert len(system_messages) == 1+ assert system_messages[0]["content"].startswith("The current date is 2026-08-15.\n\n")+def test_forced_tool_choice_must_be_in_the_selected_gguf_catalog(self, monkeypatch):import routes.inference as inf_mod@@ -5238,7 +5280,8 @@ class TestGgufVisionToolRouting:asyncio.run(_run())- def test_standard_gguf_merges_system_and_developer_messages(self, monkeypatch):+ def _drive_standard_gguf(self, monkeypatch, date_line: str) -> list[dict]:+ """Run one non-tool GGUF completion with the current-date setting pinned."""import routes.inference as inf_modcaptured = {}@@ -5261,6 +5304,8 @@ class TestGgufVisionToolRouting:generate_chat_completion = _generate,)monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)+ # Pinned, not left to the host's stored setting, so the assertion is the same everywhere.+ monkeypatch.setattr(inf_mod, "current_date_prompt_line", lambda **_kwargs: date_line)payload = ChatCompletionRequest(model = "default",@@ -5274,12 +5319,24 @@ class TestGgufVisionToolRouting:self._drive(openai_chat_completions(payload, request = self._Request(), current_subject = "test"))+ return captured["messages"]- assert captured["messages"] == [+ def test_standard_gguf_merges_system_and_developer_messages(self, monkeypatch):+ assert self._drive_standard_gguf(monkeypatch, "") == [{"role": "system", "content": "original system\n\ndeveloper rules"},{"role": "user", "content": "hi"},]+ def test_standard_gguf_prefixes_the_current_date(self, monkeypatch):+ # Covers the wiring, not just the helper: a tool-less GGUF chat must carry the date.+ assert self._drive_standard_gguf(monkeypatch, "The current date is 2026-08-15.") == [+ {+ "role": "system",+ "content": "The current date is 2026-08-15.\n\noriginal system\n\ndeveloper rules",+ },+ {"role": "user", "content": "hi"},+ ]+@pytest.mark.parametrize(("seed", "expected"),[diff --git a/studio/backend/utils/current_date_prompt_settings.py b/studio/backend/utils/current_date_prompt_settings.pynew file mode 100644index 00000000000..eb6a3bf41c5--- /dev/null+++ b/studio/backend/utils/current_date_prompt_settings.py@@ -0,0 +1,108 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Persisted preference for telling the model today's date."""++from __future__ import annotations++from datetime import date, datetime, timedelta, timezone+import re+from typing import Any+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++CURRENT_DATE_PROMPT_SETTING_KEY = "include_current_date_in_prompt"+# Lets callers recognise a prompt that already states a date, whoever put it there.+CURRENT_DATE_PROMPT_PREFIX = "The current date is "+CURRENT_DATE_PROMPT_LINE_RE = re.compile(+ rf"(?m)^{re.escape(CURRENT_DATE_PROMPT_PREFIX)}[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}\.(?=\r?$)"+)+# default on: date-blind models answer from their training cutoff and search for stale material.+DEFAULT_CURRENT_DATE_PROMPT_ENABLED = True+CURRENT_DATE_TIMEZONE_HEADER = "x-unsloth-timezone"+CURRENT_DATE_TIMEZONE_OFFSET_HEADER = "x-unsloth-timezone-offset-minutes"+MAX_TIMEZONE_OFFSET_MINUTES = 14 * 60+++def contains_current_date_prompt_line(text: str) -> bool:+ return CURRENT_DATE_PROMPT_LINE_RE.search(text) is not None+++def replace_current_date_prompt_lines(text: str, date_line: str) -> str:+ return CURRENT_DATE_PROMPT_LINE_RE.sub(date_line, text)+++def strip_current_date_prompt_lines(text: str) -> str:+ if not contains_current_date_prompt_line(text):+ return text+ return "".join(+ line+ for line in text.splitlines(keepends = True)+ if not CURRENT_DATE_PROMPT_LINE_RE.fullmatch(line.rstrip("\r\n"))+ ).strip()+++def _coerce_bool(value: Any) -> bool | None:+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ normalized = value.strip().lower()+ if normalized in {"1", "true", "yes", "on"}:+ return True+ if normalized in {"0", "false", "no", "off", ""}:+ return False+ return None+++def get_current_date_prompt_enabled() -> bool:+ """Read the persisted preference, defaulting to enabled when it is missing or unreadable."""+ try:+ from storage.studio_db import get_app_setting+ stored = get_app_setting(CURRENT_DATE_PROMPT_SETTING_KEY, None)+ except Exception:+ stored = None+ parsed = _coerce_bool(stored)+ return parsed if parsed is not None else DEFAULT_CURRENT_DATE_PROMPT_ENABLED+++def set_current_date_prompt_enabled(value: Any) -> bool:+ """Persist whether prompts should state the current date."""+ parsed = _coerce_bool(value)+ if parsed is None:+ raise ValueError("Include current date in prompt must be true or false.")++ from storage.studio_db import upsert_app_settings++ upsert_app_settings({CURRENT_DATE_PROMPT_SETTING_KEY: parsed})+ return parsed+++def _request_local_date(request: Any, now: datetime | None = None) -> date:+ instant = now or datetime.now(timezone.utc)+ try:+ headers = request.headers+ except Exception:+ return instant.astimezone().date()++ timezone_name = str(headers.get(CURRENT_DATE_TIMEZONE_HEADER) or "").strip()+ if timezone_name and len(timezone_name) <= 64:+ try:+ return instant.astimezone(ZoneInfo(timezone_name)).date()+ except (ValueError, ZoneInfoNotFoundError, OSError):+ pass++ try:+ offset_minutes = int(headers.get(CURRENT_DATE_TIMEZONE_OFFSET_HEADER, ""))+ except (TypeError, ValueError):+ return instant.astimezone().date()+ if abs(offset_minutes) > MAX_TIMEZONE_OFFSET_MINUTES:+ return instant.astimezone().date()+ browser_zone = timezone(timedelta(minutes = -offset_minutes))+ return instant.astimezone(browser_zone).date()+++def current_date_prompt_line(today: date | None = None, request: Any = None) -> str:+ """Return the shared date sentence, or an empty string when the preference is off."""+ if not get_current_date_prompt_enabled():+ return ""+ resolved_date = today or _request_local_date(request)+ return f"{CURRENT_DATE_PROMPT_PREFIX}{resolved_date.isoformat()}."diff --git a/studio/frontend/src/features/auth/api.ts b/studio/frontend/src/features/auth/api.tsindex 64eae3de36b..cc7a40a8c51 100644--- a/studio/frontend/src/features/auth/api.ts+++ b/studio/frontend/src/features/auth/api.ts@@ -29,6 +29,22 @@ let refreshInflightToken: string | null = null;let logoutGeneration = 0;const TAURI_FETCH_RETRY_DELAYS_MS = [250, 750, 1500] as const;+const BROWSER_TIMEZONE_HEADER = "X-Unsloth-Timezone";+const BROWSER_TIMEZONE_OFFSET_HEADER =+ "X-Unsloth-Timezone-Offset-Minutes";++function addBrowserTimezoneHeaders(headers: Headers): void {+ try {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ if (timezone) headers.set(BROWSER_TIMEZONE_HEADER, timezone);+ headers.set(+ BROWSER_TIMEZONE_OFFSET_HEADER,+ String(new Date().getTimezoneOffset()),+ );+ } catch {+ // runtimes without Intl keep the backend-local fallback.+ }+}function wait(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));@@ -131,6 +147,7 @@ async function retryWithCurrentToken(): Promise<Response> {beforeRetry?.();const retryHeaders = new Headers(init?.headers);+ addBrowserTimezoneHeaders(retryHeaders);const token = getAuthToken();if (token) retryHeaders.set("Authorization", `Bearer ${token}`);// Retries are tagged like the first attempt; an untagged TypeError reads as a rejection.@@ -211,6 +228,7 @@ export async function authFetch(): Promise<Response> {const resolvedInput = typeof input === "string" ? apiUrl(input) : input;const headers = new Headers(init?.headers);+ addBrowserTimezoneHeaders(headers);const accessToken = getAuthToken();if (accessToken) {headers.set("Authorization", `Bearer ${accessToken}`);diff --git a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts b/studio/frontend/src/features/chat/utils/refresh-context-usage.tsindex e90a8fa6406..bbc634778dc 100644--- a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts+++ b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts@@ -180,6 +180,7 @@ type RefreshOptions =threadId?: string;/** When true, skip the modelLoading guard (post-load recount). */afterModelLoad?: boolean;+ invalidate?: boolean;}| undefined;@@ -207,6 +208,8 @@ export async function refreshContextUsage();if (activeModel?.isAudio && !activeModel?.hasAudioInput) return;+ if (options?.invalidate) store.setContextUsage(null);+// Never count while anything is generating: the endpoint refuses, and the recount effect depends// on this, so the last run finishing re-fires it. runningByThreadId, not the narrower// localRunByThreadId: the endpoint refuses during an external-provider run too, so gating on lessdiff --git a/studio/frontend/src/features/settings/api/current-date-prompt.ts b/studio/frontend/src/features/settings/api/current-date-prompt.tsnew file mode 100644index 00000000000..82ba1415fc6--- /dev/null+++ b/studio/frontend/src/features/settings/api/current-date-prompt.ts@@ -0,0 +1,54 @@+// 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 { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++export type CurrentDatePromptSettings = {+ enabled: boolean;+ defaultEnabled: boolean;+};++type ApiCurrentDatePromptSettings = {+ enabled: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ default_enabled: boolean;+};++function fromApi(+ settings: ApiCurrentDatePromptSettings,+): CurrentDatePromptSettings {+ return {+ enabled: settings.enabled,+ defaultEnabled: settings.default_enabled,+ };+}++export async function loadCurrentDatePrompt(+ fallbackMessage: string,+): Promise<CurrentDatePromptSettings> {+ const res = await authFetch("/api/settings/current-date-prompt");+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, fallbackMessage),+ );+ }+ return fromApi(await res.json());+}++export async function updateCurrentDatePrompt(+ enabled: boolean,+ fallbackMessage: string,+): Promise<CurrentDatePromptSettings> {+ const res = await authFetch("/api/settings/current-date-prompt", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled }),+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, fallbackMessage),+ );+ }+ return fromApi(await res.json());+}diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 627450357bf..2a21a4c8ac6 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -95,6 +95,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {],chat: ["settings.general.chatDefaults",+ "settings.chat.currentDate.label","settings.general.autoTitleNewChats","settings.chat.projectAttachments","settings.chat.rememberParamsPerModel",diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsxindex f172d812600..ffc34e84c5e 100644--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx@@ -23,6 +23,7 @@ import {parseCompactionStyle,} from "@/features/chat/utils/auto-compaction";import { PASTED_TEXT_THRESHOLD_CHOICES } from "@/features/chat/utils/pasted-text";+import { refreshContextUsage } from "@/features/chat/utils/refresh-context-usage";import { formatBindingLabel, isMacPlatform } from "../lib/keyboard-shortcuts";import { useUserProfileStore } from "@/features/profile";import { type TranslationKey, useT } from "@/i18n";@@ -38,8 +39,13 @@ import {} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { Columns2Icon } from "lucide-react";-import { useEffect, useRef } from "react";+import { useEffect, useRef, useState } from "react";import type { ReactNode } from "react";+import {+ type CurrentDatePromptSettings,+ loadCurrentDatePrompt,+ updateCurrentDatePrompt,+} from "../api/current-date-prompt";import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";import { useSettingsDialogStore } from "../stores/settings-dialog-store";@@ -248,6 +254,13 @@ export function ChatTab() {const setCollapseThinkingByDefault = useChatPreferencesStore((state) => state.setCollapseThinkingByDefault,);+ const [currentDatePrompt, setCurrentDatePrompt] =+ useState<CurrentDatePromptSettings | null>(null);+ const [currentDatePromptError, setCurrentDatePromptError] = useState<+ string | null+ >(null);+ const [isSavingCurrentDatePrompt, setIsSavingCurrentDatePrompt] =+ useState(false);const collapseToolActivityByDefault = useChatPreferencesStore((state) => state.collapseToolActivityByDefault,);@@ -274,6 +287,48 @@ export function ChatTab() {refreshModelDisclaimerPreference().catch(() => undefined);}, [hydratePersistedSettings]);+ useEffect(() => {+ let cancelled = false;+ void loadCurrentDatePrompt(t("settings.chat.currentDate.loadError"))+ .then((settings) => {+ if (cancelled) return;+ setCurrentDatePrompt(settings);+ setCurrentDatePromptError(null);+ })+ .catch((error) => {+ if (cancelled) return;+ setCurrentDatePromptError(+ error instanceof Error+ ? error.message+ : t("settings.chat.currentDate.loadError"),+ );+ });+ return () => {+ cancelled = true;+ };+ }, [t]);++ const saveCurrentDatePrompt = async (enabled: boolean) => {+ setIsSavingCurrentDatePrompt(true);+ setCurrentDatePromptError(null);+ try {+ const settings = await updateCurrentDatePrompt(+ enabled,+ t("settings.chat.currentDate.saveError"),+ );+ setCurrentDatePrompt(settings);+ void refreshContextUsage({ invalidate: true });+ } catch (error) {+ setCurrentDatePromptError(+ error instanceof Error+ ? error.message+ : t("settings.chat.currentDate.saveError"),+ );+ } finally {+ setIsSavingCurrentDatePrompt(false);+ }+ };+return (<div className="flex flex-col gap-6"><header className="flex flex-col gap-1">@@ -340,6 +395,27 @@ export function ChatTab() {</SettingsSection><SettingsSection title={t("settings.general.chatDefaults")}>+ <SettingsRow+ label={t("settings.chat.currentDate.label")}+ description={t("settings.chat.currentDate.description")}+ >+ <div className="flex flex-col items-end gap-1">+ <Switch+ aria-label={t("settings.chat.currentDate.label")}+ checked={currentDatePrompt?.enabled ?? false}+ disabled={!currentDatePrompt || isSavingCurrentDatePrompt}+ onCheckedChange={(enabled) => void saveCurrentDatePrompt(enabled)}+ />+ {currentDatePromptError ? (+ <span+ role="alert"+ className="max-w-[260px] text-right text-xs text-destructive"+ >+ {currentDatePromptError}+ </span>+ ) : null}+ </div>+ </SettingsRow><SettingsRowlabel={t("settings.chat.projectsSection")}description={t("settings.chat.projectsSectionDescription")}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 775d1eb166f..bb593fe4a4f 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1379,6 +1379,13 @@ export const ar = {collapseByDefaultDescription:"إبقاء التفكير مطويًا أثناء تفكير النموذج بدلًا من فتحه تلقائيًا. وسّع أي كتلة لقراءتها.",},+ currentDate: {+ label: "إخبار النموذج بتاريخ اليوم",+ description:+ "أضف التاريخ الحالي إلى المطالبة حتى يبحث البحث على الويب و Deep Research عن مصادر حديثة بدلًا من افتراض تاريخ انتهاء تدريب النموذج.",+ loadError: "تعذّر تحميل إعدادات التاريخ الحالي",+ saveError: "تعذّر تحديث إعدادات التاريخ الحالي",+ },tools: {collapseByDefault: "طيّ نشاط الأدوات افتراضيًا",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex d5b30116b58..198393dba88 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1419,6 +1419,13 @@ export const de = {collapseByDefaultDescription:"Das Denken bleibt eingeklappt, während das Modell denkt, statt automatisch aufzuklappen. Zum Lesen einen Block ausklappen.",},+ currentDate: {+ label: "Dem Modell das heutige Datum mitteilen",+ description:+ "Fügt das aktuelle Datum zum Prompt hinzu, damit Websuche und Deep Research nach aktuellen Quellen suchen, statt vom Trainingsstand des Modells auszugehen.",+ loadError: "Einstellungen zum aktuellen Datum konnten nicht geladen werden",+ saveError: "Einstellungen zum aktuellen Datum konnten nicht aktualisiert werden",+ },tools: {collapseByDefault: "Tool-Aktivität standardmäßig einklappen",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 7e66d6cf199..e66c6c42682 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1372,6 +1372,13 @@ export const en = {collapseByDefaultDescription:"Keep reasoning collapsed while the model thinks instead of streaming it open. Expand any block to read it.",},+ currentDate: {+ label: "Tell the model today's date",+ description:+ "Add the current date to the prompt so web search and Deep Research look for recent sources instead of assuming the model's training cutoff.",+ loadError: "Failed to load current date settings",+ saveError: "Failed to update current date settings",+ },tools: {collapseByDefault: "Collapse tool activity by default",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 61f25bf0c90..8a803ba8a29 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1410,6 +1410,13 @@ export const es = {collapseByDefaultDescription:"Mantén el razonamiento contraído mientras el modelo piensa, en lugar de abrirlo automáticamente. Expande cualquier bloque para leerlo.",},+ currentDate: {+ label: "Indicar al modelo la fecha de hoy",+ description:+ "Añade la fecha actual al prompt para que la búsqueda web y Deep Research busquen fuentes recientes en lugar de asumir la fecha de corte del entrenamiento del modelo.",+ loadError: "No se pudieron cargar los ajustes de fecha actual",+ saveError: "No se pudieron actualizar los ajustes de fecha actual",+ },tools: {collapseByDefault: "Contraer la actividad de herramientas por defecto",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 812a47a8c5b..9f2159c1b23 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1416,6 +1416,13 @@ export const fr = {collapseByDefaultDescription:"Garde la réflexion repliée pendant que le modèle réfléchit, au lieu de l’ouvrir automatiquement. Dépliez un bloc pour le lire.",},+ currentDate: {+ label: "Indiquer la date du jour au modèle",+ description:+ "Ajoute la date actuelle au prompt pour que la recherche web et Deep Research cherchent des sources récentes au lieu de se fier à la date de fin d’entraînement du modèle.",+ loadError: "Impossible de charger les paramètres de date actuelle",+ saveError: "Impossible de mettre à jour les paramètres de date actuelle",+ },tools: {collapseByDefault: "Replier l’activité des outils par défaut",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 4e0694cc279..f30799ea1e6 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1385,6 +1385,13 @@ export const hi = {collapseByDefaultDescription:"मॉडल के सोचते समय रीज़निंग अपने आप खुलने के बजाय संक्षिप्त रहती है। पढ़ने के लिए किसी भी ब्लॉक को विस्तृत करें।",},+ currentDate: {+ label: "मॉडल को आज की तारीख बताएँ",+ description:+ "प्रॉम्प्ट में मौजूदा तारीख जोड़ें ताकि वेब सर्च और Deep Research मॉडल की ट्रेनिंग कटऑफ मान लेने के बजाय हाल के स्रोत खोजें।",+ loadError: "मौजूदा तारीख की सेटिंग्स लोड नहीं हो सकीं",+ saveError: "मौजूदा तारीख की सेटिंग्स अपडेट नहीं हो सकीं",+ },tools: {collapseByDefault: "टूल गतिविधि को डिफ़ॉल्ट रूप से संक्षिप्त रखें",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex f5b9fec3ac9..612de7889f1 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1384,6 +1384,13 @@ export const it = {collapseByDefaultDescription:"Mantieni il ragionamento compresso mentre il modello pensa, invece di aprirlo automaticamente. Espandi un blocco per leggerlo.",},+ currentDate: {+ label: "Comunica al modello la data di oggi",+ description:+ "Aggiunge la data corrente al prompt in modo che la ricerca web e Deep Research cerchino fonti recenti invece di basarsi sulla data di fine addestramento del modello.",+ loadError: "Impossibile caricare le impostazioni della data corrente",+ saveError: "Impossibile aggiornare le impostazioni della data corrente",+ },tools: {collapseByDefault: "Comprimi l’attività degli strumenti per impostazione predefinita",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 3f1077686c6..ac944073c4b 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1366,6 +1366,13 @@ export const ja = {collapseByDefaultDescription:"モデルの思考中も自動で展開せず、折りたたんだままにします。読みたいときはブロックを展開してください。",},+ currentDate: {+ label: "今日の日付をモデルに伝える",+ description:+ "現在の日付をプロンプトに追加し、ウェブ検索や Deep Research がモデルの学習データの締め切りを前提とせず、最新の情報源を探すようにします。",+ loadError: "現在の日付の設定を読み込めませんでした",+ saveError: "現在の日付の設定を更新できませんでした",+ },tools: {collapseByDefault: "ツールの動作をデフォルトで折りたたむ",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex f79c74fd56e..32eedbefebf 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1376,6 +1376,13 @@ export const ko = {collapseByDefaultDescription:"모델이 생각하는 동안 사고 과정을 자동으로 펼치지 않고 접어 둡니다. 읽으려면 블록을 펼치세요.",},+ currentDate: {+ label: "모델에 오늘 날짜 알려주기",+ description:+ "프롬프트에 현재 날짜를 추가해 웹 검색과 Deep Research가 모델의 학습 데이터 기준 시점을 가정하지 않고 최신 출처를 찾도록 합니다.",+ loadError: "현재 날짜 설정을 불러오지 못했습니다",+ saveError: "현재 날짜 설정을 업데이트하지 못했습니다",+ },tools: {collapseByDefault: "기본적으로 도구 활동 접기",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 52b3821a3c0..a84bb69a1b3 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1398,6 +1398,13 @@ export const ptBR = {collapseByDefaultDescription:"Mantém o raciocínio recolhido enquanto o modelo pensa, em vez de abri-lo automaticamente. Expanda um bloco para lê-lo.",},+ currentDate: {+ label: "Informar a data de hoje ao modelo",+ description:+ "Adiciona a data atual ao prompt para que a busca na web e o Deep Research procurem fontes recentes em vez de assumir a data de corte do treinamento do modelo.",+ loadError: "Não foi possível carregar as configurações de data atual",+ saveError: "Não foi possível atualizar as configurações de data atual",+ },tools: {collapseByDefault: "Recolher atividade de ferramentas por padrão",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 6abe5cafe52..ad13b49a597 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1395,6 +1395,13 @@ export const ru = {collapseByDefaultDescription:"Размышления остаются свёрнутыми, пока модель думает, вместо автоматического раскрытия. Разверните блок, чтобы прочитать его.",},+ currentDate: {+ label: "Сообщать модели сегодняшнюю дату",+ description:+ "Добавляет текущую дату в запрос, чтобы веб-поиск и Deep Research искали свежие источники, а не исходили из даты окончания обучения модели.",+ loadError: "Не удалось загрузить настройки текущей даты",+ saveError: "Не удалось обновить настройки текущей даты",+ },tools: {collapseByDefault: "Сворачивать действия инструментов по умолчанию",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 909e7be963e..3057a12211f 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1350,6 +1350,13 @@ export const zhCN = {collapseByDefaultDescription:"模型思考时保持折叠,而不是自动展开。需要阅读时展开对应区块。",},+ currentDate: {+ label: "告诉模型今天的日期",+ description:+ "在提示词中加入当前日期,让联网搜索和 Deep Research 查找最新来源,而不是按模型训练数据的截止时间推断。",+ loadError: "无法加载当前日期设置",+ saveError: "无法更新当前日期设置",+ },tools: {collapseByDefault: "默认折叠工具活动",collapseByDefaultDescription:diff --git a/studio/frontend/tests/auth-fetch-timezone.test.ts b/studio/frontend/tests/auth-fetch-timezone.test.tsnew file mode 100644index 00000000000..de0739fb8e1--- /dev/null+++ b/studio/frontend/tests/auth-fetch-timezone.test.ts@@ -0,0 +1,50 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";++type AuthApi = {+ authFetch: (input: string, init?: RequestInit) => Promise<Response>;+};++test("authFetch sends the browser timezone", async () => {+ const originalFetch = globalThis.fetch;+ let receivedHeaders = new Headers();+ globalThis.fetch = async (_input, init) => {+ receivedHeaders = new Headers(init?.headers);+ return new Response(null, { status: 200 });+ };++ try {+ const authApi = loadWithStubs<AuthApi>(+ new URL("../src/features/auth/api.ts", import.meta.url),+ {+ "@/lib/api-base": { apiUrl: (path: string) => path, isTauri: false },+ "./session": {+ clearAuthTokens: () => {},+ getAuthToken: () => "access-token",+ getRefreshToken: () => null,+ mustChangePassword: () => false,+ setMustChangePassword: () => {},+ storeAuthTokens: () => {},+ },+ },+ );++ await authApi.authFetch("/api/inference/chat/completions");++ assert.equal(+ receivedHeaders.get("X-Unsloth-Timezone"),+ Intl.DateTimeFormat().resolvedOptions().timeZone,+ );+ assert.equal(+ receivedHeaders.get("X-Unsloth-Timezone-Offset-Minutes"),+ String(new Date().getTimezoneOffset()),+ );+ } finally {+ globalThis.fetch = originalFetch;+ }+});diff --git a/studio/frontend/tests/current-date-context-usage.test.ts b/studio/frontend/tests/current-date-context-usage.test.tsnew file mode 100644index 00000000000..fdc46e2d36b--- /dev/null+++ b/studio/frontend/tests/current-date-context-usage.test.ts@@ -0,0 +1,81 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";++type RefreshModule = {+ refreshContextUsage: (options?: { invalidate?: boolean }) => Promise<void>;+};++test("a prompt setting change clears local usage even during a run", async () => {+ const cleared: unknown[] = [];+ const state = {+ activeThreadId: "thread-1",+ contextUsage: { totalTokens: 42 },+ ggufContextLength: 4096,+ modelLoading: false,+ models: [],+ params: { checkpoint: "local-model" },+ runningByThreadId: { "thread-1": true },+ setContextUsage: (usage: unknown) => cleared.push(usage),+ };+ const refreshModule = loadWithStubs<RefreshModule>(+ new URL(+ "../src/features/chat/utils/refresh-context-usage.ts",+ import.meta.url,+ ),+ {+ "../api/chat-adapter": {},+ "../api/chat-api": {},+ "../external-providers": {+ isExternalModelId: () => false,+ },+ "../stores/chat-runtime-store": {+ useChatRuntimeStore: { getState: () => state },+ },+ "./chat-history-storage": {},+ },+ );++ await refreshModule.refreshContextUsage({ invalidate: true });++ assert.deepEqual(cleared, [null]);+});++test("a prompt setting change leaves external usage intact", async () => {+ const cleared: unknown[] = [];+ const state = {+ activeThreadId: "thread-1",+ contextUsage: { totalTokens: 42 },+ ggufContextLength: 4096,+ modelLoading: false,+ models: [],+ params: { checkpoint: "external:model" },+ runningByThreadId: {},+ setContextUsage: (usage: unknown) => cleared.push(usage),+ };+ const refreshModule = loadWithStubs<RefreshModule>(+ new URL(+ "../src/features/chat/utils/refresh-context-usage.ts",+ import.meta.url,+ ),+ {+ "../api/chat-adapter": {},+ "../api/chat-api": {},+ "../external-providers": {+ isExternalModelId: () => true,+ },+ "../stores/chat-runtime-store": {+ useChatRuntimeStore: { getState: () => state },+ },+ "./chat-history-storage": {},+ },+ );++ await refreshModule.refreshContextUsage({ invalidate: true });++ assert.deepEqual(cleared, []);+});diff --git a/studio/frontend/tests/current-date-settings-accessibility.test.ts b/studio/frontend/tests/current-date-settings-accessibility.test.tsnew file mode 100644index 00000000000..b480745ec53--- /dev/null+++ b/studio/frontend/tests/current-date-settings-accessibility.test.ts@@ -0,0 +1,22 @@+// 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 { readFile } from "node:fs/promises";+import test from "node:test";++const chatTab = await readFile(+ new URL("../src/features/settings/tabs/chat-tab.tsx", import.meta.url),+ "utf8",+);++test("the current date switch has an accessible name", () => {+ assert.match(+ chatTab,+ /aria-label=\{t\("settings\.chat\.currentDate\.label"\)\}/,+ );+});++test("current date setting errors are announced", () => {+ assert.match(chatTab, /role="alert"/);+});diff --git a/studio/frontend/tests/current-date-settings-errors.test.ts b/studio/frontend/tests/current-date-settings-errors.test.tsnew file mode 100644index 00000000000..da248061a76--- /dev/null+++ b/studio/frontend/tests/current-date-settings-errors.test.ts@@ -0,0 +1,51 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";++type CurrentDateApi = {+ loadCurrentDatePrompt: (fallbackMessage: string) => Promise<unknown>;+ updateCurrentDatePrompt: (+ enabled: boolean,+ fallbackMessage: string,+ ) => Promise<unknown>;+};++function loadApi(): CurrentDateApi {+ return loadWithStubs<CurrentDateApi>(+ new URL(+ "../src/features/settings/api/current-date-prompt.ts",+ import.meta.url,+ ),+ {+ "@/features/auth": {+ authFetch: async () => new Response(null, { status: 500 }),+ },+ "@/lib/format-fastapi-error": {+ readFastApiError: async (_response: Response, fallback: string) =>+ fallback,+ },+ },+ );+}++test("the load helper uses its translated fallback", async () => {+ const api = loadApi();++ await assert.rejects(+ api.loadCurrentDatePrompt("Échec du chargement"),+ /Échec du chargement/,+ );+});++test("the save helper uses its translated fallback", async () => {+ const api = loadApi();++ await assert.rejects(+ api.updateCurrentDatePrompt(true, "Échec de l’enregistrement"),+ /Échec de l’enregistrement/,+ );+});diff --git a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts b/studio/frontend/tests/on-device-dot-and-header-alignment.test.tsindex f74084be97a..31e67acfcdb 100644--- a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts+++ b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts@@ -66,7 +66,7 @@ test("every select-model surface shares that one badge", () => {test("list header actions end where a hovered row's action does", () => {// A row action is `right-0 pr-1.5` inside a pill the list inset by- // scrollRowPadding: 12px in normally, 11px under the desktop titlebar.+ // unrailedRowPadding: 12px in normally, 11px under the desktop titlebar.assert.match(CSS,/\.sidebar-row-action \{\n\t\t@apply absolute top-0 bottom-0 right-0[^;]*pr-1\.5/,diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.tsindex d433cd06b6f..a754486613b 100644--- a/studio/frontend/tests/settings-search.test.ts+++ b/studio/frontend/tests/settings-search.test.ts@@ -58,6 +58,13 @@ const DESKTOP_STARTUP_ENTRIES = ["settings.general.startup.launchAtLogin",] as const;const CLOSE_TO_TRAY_ENTRY = "settings.general.startup.closeToTray";+const CURRENT_DATE_ENTRY = "settings.chat.currentDate.label";++test("the current date prompt setting is searchable under Chat", () => {+ const index = createSettingsSearchIndex({ desktop: false, closeToTray: false });++ assert.ok(index.chat.includes(CURRENT_DATE_ENTRY));+});test("desktop startup entries are absent from browser search", () => {const desktop = createSettingsSearchIndex({ desktop: true, closeToTray: true });