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.

Studio: keep a chat's start date in the system prompt, note a new date on the latest user turn (#12096)

Daniel Han7e80a43ae404
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 8fcf84f4f6f..2e63e783cbe 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -74,6 +74,7 @@ from core.inference.mcp_client import (
)
from storage import mcp_servers_db
from utils.account_context import account_thread, current_account_id, is_owner_context
+from utils.current_date_prompt_settings import strip_current_date_update_note
from core.inference.tool_confinement import ToolConfinementUnavailable, account_confinement
from pathlib import Path
from utils.paths.storage_roots import RetiredAccountError, ensure_dir
@@ -13646,14 +13647,14 @@ def _last_user_text(conversation: list[dict]) -> str:
continue
content = msg.get("content")
if isinstance(content, str):
- return content.strip()
+ return strip_current_date_update_note(content).strip()
if isinstance(content, list):
parts = [
p.get("text", "")
for p in content
if isinstance(p, dict) and p.get("type") in ("text", "input_text")
]
- return " ".join(t for t in parts if t).strip()
+ return strip_current_date_update_note(" ".join(t for t in parts if t)).strip()
return ""
return ""
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 095091e7a60..1e9a9053c2e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3778,7 +3778,11 @@ import base64
import zlib
from utils.current_date_prompt_settings import (
+ CURRENT_DATE_PROMPT_LINE_RE,
+ CURRENT_DATE_PROMPT_PREFIX,
+ CURRENT_DATE_UPDATE_PREFIX,
contains_current_date_prompt_line,
+ conversation_start_date,
current_date_prompt_line,
replace_current_date_prompt_lines,
)
@@ -6031,21 +6035,128 @@ def _wants_current_date(request: Any) -> bool:
return not _request_has_api_key(request)
+def _current_date_parts(request: Any, thread_id: Any) -> tuple[str, str]:
+ """(system line, user-turn note); a thread keeps its start date so its cached prefix survives."""
+ date_line = current_date_prompt_line(request = request)
+ if not date_line or not thread_id or request is None or not _wants_current_date(request):
+ return date_line, ""
+ today = CURRENT_DATE_PROMPT_LINE_RE.fullmatch(date_line)
+ started = conversation_start_date(thread_id, request) if today else None
+ if started is None:
+ return date_line, ""
+ today_iso = date_line[len(CURRENT_DATE_PROMPT_PREFIX) : -1]
+ # a browser clock running ahead can stamp a future creation day; never state a later "start".
+ if started.isoformat() >= today_iso:
+ return date_line, ""
+ return (
+ f"{CURRENT_DATE_PROMPT_PREFIX}{started.isoformat()}.",
+ f"{CURRENT_DATE_UPDATE_PREFIX}{today_iso}]",
+ )
+
+
+def _date_gate_blocks(request: Any, include_api_key: bool) -> bool:
+ if request is not None and not _wants_current_date(request):
+ return not include_api_key or _request_is_internal_workflow(request)
+ return False
+
+
+def _is_folded_tool_json(text: Any) -> bool:
+ if not isinstance(text, str) or not text.lstrip().startswith("{"):
+ return False
+ try:
+ parsed = json.loads(text)
+ except ValueError:
+ return False
+ return isinstance(parsed, dict) and "tool_response" in parsed
+
+
+def _is_folded_tool_result(content: Any) -> bool:
+ # only a turn that is ALL folded result: a follow-up coalesced onto one is the user's text.
+ if isinstance(content, list):
+ texts = [
+ p.get("text")
+ for p in content
+ if isinstance(p, dict) and isinstance(p.get("text"), str) and p["text"].strip()
+ ]
+ return bool(texts) and all(_is_folded_tool_json(t) for t in texts)
+ return _is_folded_tool_json(content)
+
+
+def _append_current_date_note(
+ messages: list[dict],
+ request: Any = None,
+ *,
+ include_api_key: bool = False,
+ thread_id: Any = None,
+ note: str | None = None,
+) -> list[dict]:
+ """Lead the newest user turn with the date-change note; earlier turns keep their own bytes."""
+ if note is None:
+ if _date_gate_blocks(request, include_api_key):
+ return messages
+ note = _current_date_parts(request, thread_id)[1]
+ if not note:
+ return messages
+ for index in range(len(messages) - 1, -1, -1):
+ msg = messages[index]
+ if not isinstance(msg, dict) or msg.get("role") != "user":
+ continue
+ content = msg.get("content")
+ if _is_folded_tool_result(content):
+ continue
+ if isinstance(content, str):
+ if content.startswith(note):
+ return messages
+ new_content: Any = f"{note}\n\n{content}"
+ has_text = bool(content.strip())
+ elif isinstance(content, list):
+ if content and all(
+ isinstance(p, dict) and p.get("type") == "tool_result" for p in content
+ ):
+ continue
+ first = next(
+ (
+ i
+ for i, p in enumerate(content)
+ if isinstance(p, dict) and isinstance(p.get("text"), str) and p["text"].strip()
+ ),
+ None,
+ )
+ has_text = first is not None
+ if has_text and content[first]["text"].startswith(note):
+ return messages
+ new_content = list(content)
+ if has_text:
+ new_content[first] = {
+ **content[first],
+ "text": f"{note}\n\n{content[first]['text']}",
+ }
+ else:
+ continue
+ # a media-only turn falls back to "transcribe" / "describe" defaults the note would replace.
+ if not has_text:
+ return messages
+ copied = list(messages)
+ copied[index] = {**msg, "content": new_content}
+ return copied
+ return messages
+
+
def _apply_current_date_prompt(
system_prompt: str,
request: Any = None,
*,
include_api_key: bool = False,
+ thread_id: Any = None,
) -> str:
- """Prefix the user's system prompt with today's date when the setting is on.
+ """Prefix the user's system prompt with the 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 _date_gate_blocks(request, include_api_key):
+ return system_prompt
+ date_line = _current_date_parts(request, thread_id)[0]
if not date_line:
return system_prompt
refreshed_prompt, stated, _ = _refresh_stated_date(system_prompt, date_line)
@@ -6066,6 +6177,7 @@ def _prepend_current_date_to_messages(
*,
include_api_key: bool = False,
provider_type: str | None = None,
+ thread_id: Any = None,
) -> list[dict]:
"""Apply the date to an already-built message list for a provider Studio proxies to.
@@ -6074,12 +6186,12 @@ def _prepend_current_date_to_messages(
such turn one is synthesized, except for ``_MODELFILE_SYSTEM_PROVIDERS``, where it is
dropped: the caller's silence is what lets the server's own prompt apply.
"""
- 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 _date_gate_blocks(request, include_api_key):
+ return messages
+ date_line, note = _current_date_parts(request, thread_id)
if not date_line:
return messages
+ messages = _append_current_date_note(messages, note = note)
copied = [dict(msg) for msg in messages]
stated = False
refreshed = False
@@ -23881,6 +23993,7 @@ async def _proxy_to_external_provider(
chat_messages,
request,
include_api_key = bool(studio_tool_payloads),
+ thread_id = getattr(payload, "thread_id", None),
)
cancel_event = threading.Event()
cancel_keys = tuple(
@@ -24248,6 +24361,7 @@ async def _proxy_to_external_provider(
request,
include_api_key = run_studio_tool_loop,
provider_type = None if _external_nudge else provider_type,
+ thread_id = getattr(payload, "thread_id", None),
)
if _external_nudge:
chat_messages = _append_to_system_message(chat_messages, _external_nudge)
@@ -25924,7 +26038,12 @@ async def produce_openai_chat_completions(
system_prompt, chat_messages, _ = await _extract_content_parts_async(
payload.messages
)
- system_prompt = _apply_current_date_prompt(system_prompt, request)
+ system_prompt = _apply_current_date_prompt(
+ system_prompt, request, thread_id = getattr(payload, "thread_id", None)
+ )
+ chat_messages = _append_current_date_note(
+ chat_messages, request, thread_id = getattr(payload, "thread_id", None)
+ )
except _DecodedAudioTooLongError as e:
# A limit the caller can act on, not a server fault.
api_monitor.fail(monitor_id, str(e))
@@ -26363,7 +26482,12 @@ async def produce_openai_chat_completions(
payload.messages, keep_tool_images = True
)
# 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)
+ system_prompt = _apply_current_date_prompt(
+ system_prompt, request, thread_id = getattr(payload, "thread_id", None)
+ )
+ chat_messages = _append_current_date_note(
+ chat_messages, request, thread_id = getattr(payload, "thread_id", None)
+ )
if not chat_messages:
raise _reject(400, "At least one non-system message is required.")
@@ -26430,6 +26554,9 @@ async def produce_openai_chat_completions(
_gguf_replayed_image_parts,
)
gguf_messages = _set_or_prepend_system_message(gguf_messages, system_prompt)
+ gguf_messages = _append_current_date_note(
+ gguf_messages, request, thread_id = getattr(payload, "thread_id", None)
+ )
image_b64 = None
if audio_b64:
_inject_audio_part(gguf_messages, audio_b64, audio_format)
@@ -26576,6 +26703,7 @@ async def produce_openai_chat_completions(
system_prompt,
request,
include_api_key = True,
+ thread_id = getattr(payload, "thread_id", None),
)
gguf_messages = _set_or_prepend_system_message(gguf_messages, system_prompt)
# ── Tool-use system prompt nudge ──────────────────────
@@ -28213,6 +28341,9 @@ async def produce_openai_chat_completions(
payload.messages, _legacy_distinct
):
chat_messages, served_images = _msgs, _payloads
+ chat_messages = _append_current_date_note(
+ chat_messages, request, thread_id = getattr(payload, "thread_id", None)
+ )
# Decode image (from content parts OR legacy field)
image_b64 = extracted_image_b64 or payload.image_base64
@@ -28581,6 +28712,7 @@ async def produce_openai_chat_completions(
system_prompt,
request,
include_api_key = True,
+ thread_id = getattr(payload, "thread_id", None),
)
if _sf_nudge:
if _sf_system_prompt:
@@ -29207,8 +29339,12 @@ async def produce_openai_chat_completions(
gen_kwargs["images"] = await _decode_request_images(
backend, _sf_rebuilt_images, dict(zip(served_images, images)), reject = _reject
)
- gen_kwargs["messages"] = _set_or_prepend_system_message(
- _structured_tool_history_for_local_template(_sf_rebuilt), system_prompt
+ gen_kwargs["messages"] = _append_current_date_note(
+ _set_or_prepend_system_message(
+ _structured_tool_history_for_local_template(_sf_rebuilt), system_prompt
+ ),
+ request,
+ thread_id = getattr(payload, "thread_id", None),
)
else:
#
@@ -29232,7 +29368,11 @@ async def produce_openai_chat_completions(
trim_mcp_image_turns(
_sf_rebuilt, _sf_rebuilt_images, limit = _MCP_MAX_TOTAL_MODEL_IMAGES - 1
)
- gen_kwargs["messages"] = _set_or_prepend_system_message(_sf_rebuilt, system_prompt)
+ gen_kwargs["messages"] = _append_current_date_note(
+ _set_or_prepend_system_message(_sf_rebuilt, system_prompt),
+ request,
+ thread_id = getattr(payload, "thread_id", None),
+ )
gen_kwargs["images"] = _sf_rebuilt_images or None
# Mark the turn that owns the image so the newest-user-turn scan does not move an
# older picture onto a later question. Gated on _sf_renders_image, not on an image:
@@ -34872,7 +35012,12 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
# The completion applies this once for both non-GGUF backends before it branches.
# Only with a request: the helper's requestless mode injects the date unconditionally.
if request is not None:
- system_prompt = _apply_current_date_prompt(system_prompt, request)
+ system_prompt = _apply_current_date_prompt(
+ system_prompt, request, thread_id = getattr(payload, "thread_id", None)
+ )
+ messages = _append_current_date_note(
+ messages, request, thread_id = getattr(payload, "thread_id", None)
+ )
from state.tool_policy import get_tool_policy as _get_tool_policy_mlx
@@ -34980,7 +35125,11 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
),
vision = False,
)
- messages = _set_or_prepend_system_message(messages, system_prompt)
+ messages = _append_current_date_note(
+ _set_or_prepend_system_message(messages, system_prompt),
+ request,
+ thread_id = getattr(payload, "thread_id", None),
+ )
system_prompt = ""
elif _tools_to_use:
# A PENDING turn is the shape this loop answers from exactly these messages, splicing
@@ -35037,6 +35186,7 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
system_prompt,
request,
include_api_key = True,
+ thread_id = getattr(payload, "thread_id", None),
)
if _nudge:
system_prompt = (system_prompt.rstrip() + "\n\n" + _nudge) if system_prompt else _nudge
@@ -35241,8 +35391,14 @@ async def chat_count_tokens(
_system_prompt, _, _ = await _extract_content_parts_async(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)
+ _system_prompt = _apply_current_date_prompt(
+ _system_prompt, request, thread_id = getattr(payload, "thread_id", None)
+ )
openai_messages = _set_or_prepend_system_message(openai_messages, _system_prompt)
+ if not _takes_passthrough:
+ openai_messages = _append_current_date_note(
+ openai_messages, request, thread_id = getattr(payload, "thread_id", None)
+ )
# A PENDING turn (unanswered user message or tool result) is the one shape the tool loop
# answers from exactly these messages, splicing in whatever build_rag_autoinject retrieves --
@@ -35306,6 +35462,7 @@ async def chat_count_tokens(
openai_messages,
request,
include_api_key = True,
+ thread_id = getattr(payload, "thread_id", None),
)
_count_nudge = await _apply_rag_nudge(
_build_tool_action_nudge(
@@ -35552,6 +35709,7 @@ async def anthropic_count_tokens(
openai_messages,
request,
include_api_key = _count_server_tools,
+ thread_id = getattr(payload, "thread_id", None),
)
if _count_server_tools:
openai_tools = _count_selected_server_tools
@@ -35935,6 +36093,7 @@ async def anthropic_messages(
openai_messages,
request,
include_api_key = server_tools,
+ thread_id = getattr(payload, "thread_id", None),
)
# Anthropic tool_choice.disable_parallel_tool_use caps the response to a
diff --git a/studio/backend/tests/test_current_date_prompt_settings.py b/studio/backend/tests/test_current_date_prompt_settings.py
index 5bd868e60d4..598137dbf63 100644
--- a/studio/backend/tests/test_current_date_prompt_settings.py
+++ b/studio/backend/tests/test_current_date_prompt_settings.py
@@ -398,3 +398,259 @@ class TestResearchSystemPrompt:
# 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"
+
+
+class TestConversationStartDate:
+ @staticmethod
+ def _threads(monkeypatch, threads):
+ import storage.studio_db as studio_db
+ monkeypatch.setattr(studio_db, "get_chat_thread", lambda thread_id: threads.get(thread_id))
+
+ def test_start_date_is_the_creation_day_in_the_browser_zone(self, monkeypatch):
+ # 2026-08-15T02:00Z is still the 14th in New York.
+ created = int(datetime(2026, 8, 15, 2, tzinfo = timezone.utc).timestamp() * 1000)
+ self._threads(monkeypatch, {"t": {"createdAt": created}})
+ request = _types.SimpleNamespace(headers = {"x-unsloth-timezone": "America/New_York"})
+ assert current_date_settings.conversation_start_date("t", request) == date(2026, 8, 14)
+
+ def test_a_fork_keeps_its_root_threads_start_date(self, monkeypatch):
+ day = lambda d: int(datetime(2026, 8, d, 12, tzinfo = timezone.utc).timestamp() * 1000)
+ self._threads(
+ monkeypatch,
+ {
+ "root": {"createdAt": day(1)},
+ "mid": {"createdAt": day(5), "forkedFromThreadId": "root"},
+ "leaf": {"createdAt": day(9), "forkedFromThreadId": "mid"},
+ "orphan": {"createdAt": day(9), "forkedFromThreadId": "gone"},
+ "loop": {"createdAt": day(9), "forkedFromThreadId": "loop"},
+ },
+ )
+ request = _types.SimpleNamespace(headers = {"x-unsloth-timezone": "UTC"})
+ start = current_date_settings.conversation_start_date
+ assert start("leaf", request) == date(2026, 8, 1)
+ assert start("orphan", request) == date(2026, 8, 9)
+ assert start("loop", request) == date(2026, 8, 9)
+
+ def test_a_deep_fork_chain_still_reaches_the_root(self, monkeypatch):
+ root = int(datetime(2026, 8, 1, 12, tzinfo = timezone.utc).timestamp() * 1000)
+ later = int(datetime(2026, 8, 9, 12, tzinfo = timezone.utc).timestamp() * 1000)
+ threads = {"t0": {"createdAt": root}}
+ for i in range(1, 40):
+ threads[f"t{i}"] = {"createdAt": later, "forkedFromThreadId": f"t{i - 1}"}
+ self._threads(monkeypatch, threads)
+ request = _types.SimpleNamespace(headers = {"x-unsloth-timezone": "UTC"})
+ assert current_date_settings.conversation_start_date("t39", request) == date(2026, 8, 1)
+
+ @pytest.mark.parametrize("thread_id", [None, "", 7, "missing"])
+ def test_unknown_threads_have_no_start_date(self, monkeypatch, thread_id):
+ self._threads(monkeypatch, {})
+ assert current_date_settings.conversation_start_date(thread_id) is None
+
+ def test_a_lookup_failure_has_no_start_date(self, monkeypatch):
+ import storage.studio_db as studio_db
+
+ def _boom(_thread_id):
+ raise RuntimeError("db locked")
+
+ monkeypatch.setattr(studio_db, "get_chat_thread", _boom)
+ assert current_date_settings.conversation_start_date("t") is None
+
+
+class TestDateChangeNote:
+ @pytest.fixture(autouse = True)
+ def _clock(self, monkeypatch):
+ import routes.inference as inference
+
+ self.today = "2026-08-15"
+ self.started = date(2026, 8, 15)
+ monkeypatch.setattr(
+ inference,
+ "current_date_prompt_line",
+ lambda **_kwargs: f"The current date is {self.today}.",
+ )
+ monkeypatch.setattr(
+ inference,
+ "conversation_start_date",
+ lambda thread_id, _request = None: self.started if thread_id == "t" else None,
+ )
+ monkeypatch.setattr(inference, "_request_has_api_key", lambda _request: False)
+ self.inference = inference
+
+ def _proxy(
+ self,
+ messages,
+ thread_id = "t",
+ **kwargs,
+ ):
+ return self.inference._prepend_current_date_to_messages(
+ messages, object(), thread_id = thread_id, **kwargs
+ )
+
+ def test_same_day_is_byte_identical_to_a_threadless_request(self):
+ messages = [{"role": "system", "content": "Be terse."}, {"role": "user", "content": "hi"}]
+ assert self._proxy(messages) == self._proxy(messages, thread_id = None)
+ assert self.inference._apply_current_date_prompt("Be terse.", object(), thread_id = "t") == (
+ "The current date is 2026-08-15.\n\nBe terse."
+ )
+
+ def test_midnight_keeps_the_system_turn_and_notes_the_newest_user_turn(self):
+ history = [
+ {"role": "system", "content": "Be terse."},
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "second"},
+ ]
+ before = self._proxy(history)
+ self.today = "2026-08-16"
+ after = self._proxy(history)
+ assert after[0] == before[0]
+ assert after[0]["content"] == "The current date is 2026-08-15.\n\nBe terse."
+ assert after[1:3] == history[1:3]
+ assert after[3]["content"] == "[Current date: 2026-08-16]\n\nsecond"
+ assert history[3]["content"] == "second"
+
+ def test_next_request_after_midnight_restores_the_earlier_turn_to_its_own_text(self):
+ self.today = "2026-08-16"
+ turn1 = [{"role": "user", "content": "first"}]
+ sent1 = self._proxy(turn1)
+ turn2 = turn1 + [
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "second"},
+ ]
+ sent2 = self._proxy(turn2)
+ assert sent2[0] == sent1[0]
+ assert sent1[1]["content"] == "[Current date: 2026-08-16]\n\nfirst"
+ assert sent2[1]["content"] == "first"
+ assert sent2[3]["content"] == "[Current date: 2026-08-16]\n\nsecond"
+
+ def test_threadless_requests_still_refresh_to_today(self):
+ self.today = "2026-08-16"
+ out = self._proxy([{"role": "user", "content": "hi"}], thread_id = None)
+ assert out == [
+ {"role": "system", "content": "The current date is 2026-08-16."},
+ {"role": "user", "content": "hi"},
+ ]
+
+ def test_a_stated_system_date_is_refreshed_to_the_start_date(self):
+ self.today = "2026-08-16"
+ out = self._proxy(
+ [
+ {"role": "system", "content": "The current date is 2026-08-16."},
+ {"role": "user", "content": "hi"},
+ ]
+ )
+ assert out[0]["content"] == "The current date is 2026-08-15."
+ assert out[1]["content"] == "[Current date: 2026-08-16]\n\nhi"
+
+ def test_note_leads_the_text_part_and_skips_tool_results(self):
+ self.today = "2026-08-16"
+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA"}}
+ messages = [
+ {"role": "user", "content": [image, {"type": "text", "text": "what is this"}]},
+ {"role": "assistant", "content": "a cat"},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "x"}]},
+ ]
+ out = self.inference._append_current_date_note(messages, object(), thread_id = "t")
+ assert out[2] is messages[2]
+ assert out[0]["content"] == [
+ image,
+ {"type": "text", "text": "[Current date: 2026-08-16]\n\nwhat is this"},
+ ]
+
+ def test_note_skips_a_tool_result_folded_into_a_user_turn(self):
+ from core.inference.anthropic_compat import fold_tool_results_into_user
+
+ self.today = "2026-08-16"
+ messages = fold_tool_results_into_user(
+ [
+ {"role": "user", "content": "list files"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{"id": "c1", "function": {"name": "ls", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "a.txt"},
+ ]
+ )
+ out = self.inference._append_current_date_note(messages, object(), thread_id = "t")
+ assert out[2] is messages[2]
+ assert out[0]["content"] == "[Current date: 2026-08-16]\n\nlist files"
+
+ @pytest.mark.parametrize(
+ "content",
+ ["", " ", [{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA"}}]],
+ )
+ def test_a_media_only_turn_keeps_its_transcribe_or_describe_default(self, content):
+ from core.inference.chat_template_helpers import last_user_text
+
+ self.today = "2026-08-16"
+ messages = [{"role": "user", "content": content}]
+ out = self.inference._append_current_date_note(messages, object(), thread_id = "t")
+ assert out is messages
+ assert last_user_text(out) == ""
+
+ def test_retrieval_queries_ignore_the_note(self):
+ from core.inference.tools import _last_user_text
+ self.today = "2026-08-16"
+ for content in ("refund policy", [{"type": "text", "text": "refund policy"}]):
+ noted = self.inference._append_current_date_note(
+ [{"role": "user", "content": content}], object(), thread_id = "t"
+ )
+ assert noted[0]["content"] != content
+ assert _last_user_text(noted) == "refund policy"
+
+ def test_a_follow_up_coalesced_onto_a_folded_tool_result_gets_the_note(self):
+ from core.inference.anthropic_compat import fold_tool_results_into_user
+
+ self.today = "2026-08-16"
+ messages = self.inference._coalesce_consecutive_user_turns(
+ fold_tool_results_into_user(
+ [
+ {"role": "user", "content": "list files"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{"id": "c1", "function": {"name": "ls", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "a.txt"},
+ {"role": "user", "content": "now read it"},
+ ]
+ )
+ )
+ out = self.inference._append_current_date_note(messages, object(), thread_id = "t")
+ assert out[0] is messages[0]
+ assert out[-1]["content"].startswith("[Current date: 2026-08-16]\n\n")
+ assert out[-1]["content"].endswith("now read it")
+
+ def test_a_future_creation_day_never_becomes_the_stated_start(self):
+ self.today = "2026-08-15"
+ self.started = date(2026, 8, 20)
+ out = self._proxy([{"role": "user", "content": "hi"}])
+ assert out == [
+ {"role": "system", "content": "The current date is 2026-08-15."},
+ {"role": "user", "content": "hi"},
+ ]
+
+ def test_note_is_not_added_twice(self):
+ self.today = "2026-08-16"
+ once = self.inference._append_current_date_note(
+ [{"role": "user", "content": "hi"}], object(), thread_id = "t"
+ )
+ assert self.inference._append_current_date_note(once, object(), thread_id = "t") is once
+
+ def test_api_key_callers_never_use_a_thread_start_date(self, monkeypatch):
+ monkeypatch.setattr(self.inference, "_request_has_api_key", lambda _request: True)
+ monkeypatch.setattr(self.inference, "_request_is_internal_workflow", lambda _r: False)
+ self.today = "2026-08-16"
+ out = self._proxy([{"role": "user", "content": "hi"}], include_api_key = True)
+ assert out == [
+ {"role": "system", "content": "The current date is 2026-08-16."},
+ {"role": "user", "content": "hi"},
+ ]
+
+ def test_disabled_setting_adds_no_note(self, monkeypatch):
+ monkeypatch.setattr(self.inference, "current_date_prompt_line", lambda **_kwargs: "")
+ messages = [{"role": "user", "content": "hi"}]
+ assert (
+ self.inference._append_current_date_note(messages, object(), thread_id = "t") is messages
+ )
diff --git a/studio/backend/utils/current_date_prompt_settings.py b/studio/backend/utils/current_date_prompt_settings.py
index eb6a3bf41c5..7633ac833a2 100644
--- a/studio/backend/utils/current_date_prompt_settings.py
+++ b/studio/backend/utils/current_date_prompt_settings.py
@@ -13,6 +13,11 @@ 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 "
+# Leads the turn: a trailing sentence made small models answer about the date instead (PR #12096).
+CURRENT_DATE_UPDATE_PREFIX = "[Current date: "
+CURRENT_DATE_UPDATE_NOTE_RE = re.compile(
+ rf"^\s*{re.escape(CURRENT_DATE_UPDATE_PREFIX)}[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}\]\s*"
+)
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?$)"
)
@@ -106,3 +111,35 @@ def current_date_prompt_line(today: date | None = None, request: Any = None) ->
return ""
resolved_date = today or _request_local_date(request)
return f"{CURRENT_DATE_PROMPT_PREFIX}{resolved_date.isoformat()}."
+
+
+def conversation_start_date(thread_id: Any, request: Any = None) -> date | None:
+ """Local date the thread (or the root of its fork chain) was created, None when unknown."""
+ if not isinstance(thread_id, str) or not thread_id:
+ return None
+ try:
+ from storage.studio_db import get_chat_thread
+
+ thread = get_chat_thread(thread_id)
+ seen = {thread_id}
+ # a fork keeps its parent's history, so it keeps the parent's prompt prefix too.
+ while thread:
+ parent_id = thread.get("forkedFromThreadId")
+ if not parent_id or parent_id in seen:
+ break
+ seen.add(parent_id)
+ parent = get_chat_thread(parent_id)
+ if not parent:
+ break
+ thread = parent
+ created_ms = thread.get("createdAt") if thread else None
+ if isinstance(created_ms, bool) or not isinstance(created_ms, (int, float)):
+ return None
+ created = datetime.fromtimestamp(created_ms / 1000, timezone.utc)
+ except Exception:
+ return None
+ return _request_local_date(request, now = created)
+
+
+def strip_current_date_update_note(text: str) -> str:
+ return CURRENT_DATE_UPDATE_NOTE_RE.sub("", text)
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 443811467b9..d6568ceeaa9 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1983,8 +1983,14 @@ export async function buildLocalTokenCountExtras(
// tools-on default answer and the server renders a catalog the completion does not.
// No budget, because the completion sends none either, so a policy that injects tools
// past this false gets the server default on both sides.
+ // The completion always sends thread_id; the server dates a thread's prompt from it.
+ const threadField = threadId ? { thread_id: threadId } : {};
if (!supportsTools) {
- return { enable_tools: false, bypass_permissions: bypassPermissions };
+ return {
+ enable_tools: false,
+ bypass_permissions: bypassPermissions,
+ ...threadField,
+ };
}
const ragProjectId = await resolveProjectId(threadId);
@@ -2008,7 +2014,11 @@ export async function buildLocalTokenCountExtras(
) {
// Explicit false, not omission: the server defaults tools on. The permission level rides
// along because `--enable-tools` still outranks that false in _effective_enable_tools.
- return { enable_tools: false, bypass_permissions: bypassPermissions };
+ return {
+ enable_tools: false,
+ bypass_permissions: bypassPermissions,
+ ...threadField,
+ };
}
return {
@@ -2034,7 +2044,7 @@ export async function buildLocalTokenCountExtras(
mcp_enabled: mcpEnabledForChat,
// Top level, not inside rag_scope: an archived thread puts search_conversation and its
// compaction nudge in the prompt whether or not RAG is on, and the completion sends it here.
- ...(threadId ? { thread_id: threadId } : {}),
+ ...threadField,
// Armed research puts the deep_research schema in the prompt, so the count carries it.
...(deepResearchEnabled ? { deep_research_armed: true } : {}),
// Keeps search_knowledge_base and its grounding nudge in the prompt. No retrieval runs for