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: let the model decide when a message needs Deep Research (#9726)

Nilay07c49e91f11d
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index e095a2e9761..f22423605ef 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -4560,8 +4560,12 @@ def _render_html_reaches_network(arguments: dict) -> bool:
# to pause them and their safety needs no argument scan. render_html is handled
# separately above because a networked canvas does need approval.
# search_conversation only reads this chat's own past turns, so auto mode would otherwise
-# prompt for approval on every call.
-_ALWAYS_SAFE_TOOLS = frozenset({"web_search", "search_knowledge_base", "search_conversation"})
+# prompt for approval on every call. deep_research runs no code and reaches nothing either: it
+# only reports that the user's own armed research is starting, and without it here
+# is_high_risk_tool_call's unknown-name default would prompt on every handoff.
+_ALWAYS_SAFE_TOOLS = frozenset(
+ {"web_search", "search_knowledge_base", "search_conversation", "deep_research"}
+)
def is_always_safe_tool(name: str) -> bool:
@@ -9960,6 +9964,58 @@ ALL_TOOLS = [
SEARCH_CONVERSATION_TOOL,
]
+# Deliberately an ordinary tool with an ordinary result. Studio runs three tool loops -- one for
+# llama.cpp, one for safetensors, one for external providers -- and only a plain result behaves
+# the same in all three. The client starts the run off the tool events every loop already
+# publishes, so nothing here needs to know a research run exists.
+#
+# Never in ALL_TOOLS: it is offered only when the composer armed research.
+#
+# The client keys the handoff on this opening rather than on tool_end alone: a denied, skipped,
+# truncated or budget-exhausted call is closed by the same event, and only the result says the
+# call actually ran.
+DEEP_RESEARCH_STARTED_MARKER = "Deep Research has started"
+DEEP_RESEARCH_STARTED = (
+ f"{DEEP_RESEARCH_STARTED_MARKER} on that question. Reply with one short sentence saying you "
+ "are looking into it. Do not answer the question yourself and do not call this tool again; "
+ "the researched report arrives separately."
+)
+
+DEEP_RESEARCH_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "deep_research",
+ "description": (
+ "Start Deep Research on the user's question: a multi-step web investigation that "
+ "gathers current sources and writes a cited report, replacing your reply. The user "
+ "turned this on because they want researched answers, so call it for any question "
+ "about the world -- facts, events, laws, products, papers, prices, comparisons, "
+ "anything that may have changed since your training -- even when you think you know "
+ "the answer. Do not answer such questions from memory.\n"
+ "Do not call it for a message with no question in it, such as a hello or a thanks, or "
+ "for a request to write or transform text the user supplied.\n"
+ "If the topic is too vague to research well, do not call this yet: ask one short "
+ "clarifying question, then call it once the user has narrowed it down.\n"
+ "The question you pass is what gets researched, so make it specific and "
+ "self-contained: fold in what the conversation established rather than repeating "
+ "the user's words."
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "question": {
+ "type": "string",
+ "description": (
+ "The specific, self-contained question to research. Not the user's raw "
+ "message unless it already reads as one."
+ ),
+ },
+ },
+ "required": ["question"],
+ },
+ },
+}
+
# OpenAI's function.name regex; MCP names that violate it would 400 the whole
# request, so validate up front and skip with a warning.
@@ -10268,6 +10324,10 @@ def execute_tool(
),
name,
)
+ if name == "deep_research":
+ if not str(arguments.get("question") or "").strip():
+ return "Error: deep_research needs a question to investigate."
+ return DEEP_RESEARCH_STARTED
if name == "web_search":
return _fit_result_to_room(
_web_search(
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index c1946913b7b..13f264d223c 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -254,11 +254,21 @@ def _extract_text(message: dict) -> str:
return message_text_with_pastes(message).strip()
-def _research_question_context(thread_id: str, user_message_id: str) -> tuple[str, str]:
+def _research_question_context(
+ thread_id: str,
+ user_message_id: str,
+ override: str = "",
+) -> tuple[str, str]:
+ """The question to research plus the conversation that led to it.
+
+ ``override`` is the question the model handed off, which folds in what the conversation
+ established and is what the user actually wants researched. The raw message stands in for
+ runs created without one.
+ """
messages = list_chat_messages(thread_id)
by_id = {str(message["id"]): message for message in messages}
user = by_id.get(user_message_id)
- question = _extract_text(user or {})
+ question = override.strip() or _extract_text(user or {})
if not user:
return question, "[]"
@@ -818,6 +828,22 @@ def _research_step_failed(web_result: str, rag_sources: list[dict]) -> bool:
return is_tool_error(web_result) or web_result.strip() in EMPTY_SEARCH_RESULTS
+def _run_moved_on(fresh: dict | None, attempt: int) -> bool:
+ """Whether the run this worker was running has since been re-pointed at a newer question.
+
+ A thread reuses its one run row for its lifetime, so between committing a terminal status
+ and writing the terminal reply the user can stop the run and ask something else: the row
+ is reset, its assistant binding moves, and the reply below -- resolved by run id -- would
+ stamp "Research cancelled." and researchStatus cancelled onto the NEW question's
+ placeholder, where it stays until that question reaches its own terminal write.
+
+ retryCount is the attempt epoch, which rebind_cancelled advances for exactly this reason.
+ """
+ if not fresh:
+ return True
+ return int(fresh.get("retryCount") or 0) != attempt
+
+
def _update_assistant(
run: dict,
text: str,
@@ -836,7 +862,10 @@ def _update_assistant(
status = status,
sources = sources,
completion_worker_id = completion_worker_id,
+ expected_attempt = int(run.get("retryCount") or 0),
)
+ if not message_id:
+ return
existing = get_chat_message(run["threadId"], message_id) or {}
content = existing.get("content") if isinstance(existing.get("content"), list) else []
# Only replace this worker's text/source parts; retain artifacts, reasoning, and other extensions.
@@ -886,6 +915,8 @@ def _update_assistant(
"createdAt": existing.get("createdAt") or db.now_ms(),
},
allow_research_update = True,
+ expected_research_run_id = run["id"],
+ expected_research_attempt = int(run.get("retryCount") or 0),
)
@@ -1720,6 +1751,9 @@ class ResearchSupervisor:
logger.debug("research.phase_event_failed run_id=%s", run_id, exc_info = True)
async def _process(self, run: dict) -> None:
+ # The attempt this worker claimed. Everything it writes after a terminal status is
+ # only its to write while the run is still on that attempt.
+ attempt = int(run.get("retryCount") or 0)
cancel_event = self._cancel_event(run["id"])
if await asyncio.to_thread(db.is_cancel_requested, run["id"]):
cancel_event.set()
@@ -1735,7 +1769,7 @@ class ResearchSupervisor:
db.finish, run["id"], self.worker_id, "cancelled"
)
fresh = await asyncio.to_thread(db.get_run, run["id"])
- if actual_status == "cancelled" and fresh:
+ if actual_status == "cancelled" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant, fresh, "Research cancelled.", "cancelled"
)
@@ -1743,14 +1777,14 @@ class ResearchSupervisor:
logger.warning("research.lease_lost run_id=%s", run["id"])
actual_status = await self._finish_after_lease_loss(run["id"])
fresh = await asyncio.to_thread(db.get_run, run["id"])
- if actual_status == "cancelled" and fresh:
+ if actual_status == "cancelled" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant,
fresh,
"Research cancelled.",
"cancelled",
)
- elif actual_status == "failed" and fresh:
+ elif actual_status == "failed" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant,
fresh,
@@ -1769,11 +1803,11 @@ class ResearchSupervisor:
if actual_status is None:
actual_status = await self._finish_after_lease_loss(run["id"])
fresh = await asyncio.to_thread(db.get_run, run["id"])
- if actual_status == "cancelled" and fresh:
+ if actual_status == "cancelled" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant, fresh, "Research cancelled.", "cancelled"
)
- elif actual_status == "failed" and fresh:
+ elif actual_status == "failed" and not _run_moved_on(fresh, attempt):
await asyncio.to_thread(
_update_assistant, fresh, f"Research failed: {error}", "failed"
)
@@ -1813,7 +1847,10 @@ class ResearchSupervisor:
async def _plan(self, run: dict) -> None:
question, conversation_context = await asyncio.to_thread(
- _research_question_context, run["threadId"], run["userMessageId"]
+ _research_question_context,
+ run["threadId"],
+ run["userMessageId"],
+ str(run["config"].get("question") or ""),
)
if not question:
raise ValueError("User message has no text to research")
@@ -1864,6 +1901,8 @@ class ResearchSupervisor:
preview_labels = True,
)
plan = _parse_and_validate_plan(response, planning_reasoning, max_steps)
+ # Arming research in the composer is the approval, so the plan is queued as it is
+ # stored rather than parked for a second confirmation.
try:
result = await asyncio.to_thread(
db.set_plan,
@@ -1871,6 +1910,7 @@ class ResearchSupervisor:
plan,
None,
self.worker_id,
+ auto_approve = True,
)
except db.ResearchConflictError:
if await asyncio.to_thread(db.is_cancel_requested, run["id"]):
@@ -1886,6 +1926,8 @@ class ResearchSupervisor:
if not fresh or not fresh.get("plan"):
raise ValueError("Approved plan is missing")
run = fresh
+ # The attempt this pass belongs to, kept because ``run`` is re-read below.
+ research_attempt = int(run.get("retryCount") or 0)
budgets = run["config"]["budgets"]
max_steps = int(budgets["maxSteps"])
max_sources = int(budgets["maxSources"])
@@ -1913,7 +1955,10 @@ class ResearchSupervisor:
used_queries: set[str] = set()
fetched_urls: set[str] = set()
question, conversation_context = await asyncio.to_thread(
- _research_question_context, run["threadId"], run["userMessageId"]
+ _research_question_context,
+ run["threadId"],
+ run["userMessageId"],
+ str(run["config"].get("question") or ""),
)
reset = db.prepare_execution_resume if resuming else db.reset_execution_steps
written = await asyncio.to_thread(reset, run["id"], self.worker_id)
@@ -2586,5 +2631,5 @@ class ResearchSupervisor:
if actual_status is None:
raise LeaseLost()
run = await asyncio.to_thread(db.get_run, run["id"])
- if actual_status == "cancelled" and run:
+ if actual_status == "cancelled" and not _run_moved_on(run, research_attempt):
await asyncio.to_thread(_update_assistant, run, "Research cancelled.", "cancelled")
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index d47a3b89243..2e87db0d6e5 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1747,6 +1747,13 @@ class ChatCompletionRequest(BaseModel):
None,
description = "[x-unsloth] When true, append tools from every enabled MCP server to this request's tool list.",
)
+ deep_research_armed: Optional[bool] = Field(
+ None,
+ description = (
+ "[x-unsloth] Offer the deep_research handoff tool for this turn. Set when the "
+ "composer has Deep Research armed; the model decides whether to use it."
+ ),
+ )
confirm_tool_calls: Optional[bool] = Field(
None,
description = "[x-unsloth] When true, pause before each tool call and wait for the user to allow/deny it via POST /api/inference/tool-confirm.",
@@ -2191,6 +2198,13 @@ class ChatCountTokensRequest(BaseModel):
None,
description = "[x-unsloth] Append tools from every enabled MCP server",
)
+ deep_research_armed: Optional[bool] = Field(
+ None,
+ description = (
+ "[x-unsloth] Offer the deep_research handoff tool. Its schema is in the prompt "
+ "whenever the composer armed research, so the count carries it too."
+ ),
+ )
rag_scope: Optional[dict] = Field(
None,
description = "[x-unsloth] Hidden RAG retrieval scope for search_knowledge_base",
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 721398a2de3..b93950acb71 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3225,6 +3225,11 @@ def _selects_only_provider_hosted_tools(payload, provider_type: str | None) -> b
"""
if getattr(payload, "mcp_enabled", False):
return False
+ # Armed research appends Studio's own deep_research past every filter below, and no
+ # provider can run it, so such a selection is never purely hosted. Without this the
+ # request proxies through, the tool is never offered and arming research does nothing.
+ if getattr(payload, "deep_research_armed", False):
+ return False
enabled = getattr(payload, "enabled_tools", None)
# None means "every local tool"; an empty list selects nothing and never
# reaches the loop anyway. Neither is a hosted-tool request.
@@ -3918,6 +3923,22 @@ def _full_access_tip(code_tools: list[str]) -> str:
)
+# Armed Deep Research. Stated outright because the schema alone does not move a small model
+# off its prior: asked about 2026 it answers from 2024 training data with no sign it is
+# stale, and the base nudge's "otherwise answer normally" reads as permission to do so.
+# The exception is worded without "greetings" on purpose: with that word in the prompt a
+# 1.7B model opens a fresh chat by greeting the user instead of researching the question
+# (0/4 first-turn calls, against 4/4 with this wording).
+_TOOL_RESEARCH_TIP = (
+ "Deep Research is turned on for this conversation. For any question about the world "
+ "-- facts, events, laws, products, papers, prices, comparisons, anything that may have "
+ "changed since your training -- call deep_research instead of answering from memory, "
+ "even when you think you know the answer: the user asked for a researched, cited "
+ "report and your knowledge has a cutoff. If a message has no question in it, such as a "
+ "hello, a thanks, or a remark about you, reply normally. If a topic is too vague to "
+ "research well, ask one short clarifying question first."
+)
+
_TOOL_ARTIFACT_TIP = (
"For HTML, CSS, or JavaScript canvas requests, call render_html once when "
"it is available with one complete self-contained HTML document in the code "
@@ -3952,10 +3973,15 @@ def _build_tool_action_nudge(
code_tools = [name for name in _LOCAL_CODE_TOOLS if name in tool_names]
has_code = bool(code_tools)
has_artifact = "render_html" in tool_names
- if not (has_web or has_code or has_artifact):
+ has_research = "deep_research" in tool_names
+ if not (has_web or has_code or has_artifact or has_research):
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
model_size_b = _extract_model_size_b(model_name)
compact_web_tip = model_size_b is not None and model_size_b < 9
@@ -3970,12 +3996,9 @@ def _build_tool_action_nudge(
tool_tip_parts.append(_full_access_tip(code_tools))
if has_artifact:
tool_tip_parts.append(_TOOL_ARTIFACT_TIP)
- return (
- f"The current date is {_date.today().isoformat()}. "
- + _TOOL_BASE_NUDGE
- + " "
- + " ".join(tool_tip_parts)
- )
+ if has_research:
+ tool_tip_parts.append(_TOOL_RESEARCH_TIP)
+ return date_line + _TOOL_BASE_NUDGE + " " + " ".join(tool_tip_parts)
# Nudge appended when the RAG knowledge-base tool is active: ground answers in
@@ -4397,6 +4420,13 @@ async def _select_request_tools(
tools = apply_full_access_tool_descriptions(tools)
if mcp_allowed:
tools = tools + await get_enabled_mcp_tools()
+ # getattr: callers hand in lighter payload objects than the request models, not all of
+ # which know this field.
+ if getattr(payload, "deep_research_armed", None):
+ # Appended past every filter above, including the tools_on gate: arming research in the
+ # composer is what offers this tool, and it is the only way the model can start a run.
+ from core.inference.tools import DEEP_RESEARCH_TOOL
+ tools = tools + [DEEP_RESEARCH_TOOL]
return tools
diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.py
index 3618870ed5c..ca8e2fb5029 100644
--- a/studio/backend/routes/research_runs.py
+++ b/studio/backend/routes/research_runs.py
@@ -75,6 +75,7 @@ class CreateResearchRun(BaseModel):
budgets: dict[str, int] | None = None
websitePolicy: dict[str, list[str]] | None = None
instructions: str | None = Field(default = None, max_length = 32_000)
+ question: str | None = Field(default = None, max_length = 2000)
@field_validator("budgets", mode = "before")
@classmethod
@@ -136,9 +137,12 @@ def _sync_assistant(run: dict, text: str | None = None) -> None:
run["id"],
text = fallback_text,
status = run["status"],
+ expected_attempt = int(run.get("retryCount") or 0),
)
if created:
return
+ if not message_id:
+ return
message = get_chat_message(run["threadId"], message_id)
if message is None:
return
@@ -166,6 +170,8 @@ def _sync_assistant(run: dict, text: str | None = None) -> None:
"metadata": metadata,
},
allow_research_update = True,
+ expected_research_run_id = run["id"],
+ expected_research_attempt = int(run.get("retryCount") or 0),
)
@@ -360,6 +366,7 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:
"budgets": budgets,
"websitePolicy": website_policy,
"instructions": (payload.instructions or "").strip(),
+ "question": (payload.question or "").strip(),
}
@@ -377,28 +384,40 @@ def create_research_run(
raise HTTPException(
status_code = 400, detail = "userMessageId must identify a user message in the thread"
)
- if not message_text_with_pastes(user_message).strip():
+ # A handed-off question counts as the text. An image-, audio- or video-only send is a
+ # normal composer turn, and a multimodal model that reads one and calls deep_research
+ # passes the question it wrote; the worker researches config.question, so refusing here
+ # on the message's own (empty) text ends an otherwise complete handoff in a toast.
+ if not message_text_with_pastes(user_message).strip() and not (payload.question or "").strip():
raise HTTPException(
status_code = 400,
detail = "Deep research requires a user message with non-empty text",
)
- if db.has_thread_claim(payload.threadId):
- raise HTTPException(
- status_code = 409,
- detail = "This thread already has a Deep Research run",
- )
config = _sanitize_config(payload, thread)
- run_id = uuid.uuid4().hex
- assistant_id = payload.assistantMessageId
try:
- run = db.create_run(
- run_id = run_id,
- owner_subject = current_subject,
- thread_id = payload.threadId,
- user_message_id = payload.userMessageId,
- assistant_message_id = assistant_id,
- config = config,
- )
+ if db.has_thread_claim(payload.threadId):
+ # The thread's one run was stopped, so it is re-pointed at this question rather
+ # than refusing every later one in the chat.
+ run = db.rebind_cancelled(
+ thread_id = payload.threadId,
+ user_message_id = payload.userMessageId,
+ assistant_message_id = payload.assistantMessageId,
+ config = config,
+ )
+ if run is None:
+ raise HTTPException(
+ status_code = 409,
+ detail = "This thread already has a Deep Research run",
+ )
+ else:
+ run = db.create_run(
+ run_id = uuid.uuid4().hex,
+ owner_subject = current_subject,
+ thread_id = payload.threadId,
+ user_message_id = payload.userMessageId,
+ assistant_message_id = payload.assistantMessageId,
+ config = config,
+ )
except db.ResearchConflictError as exc:
raise HTTPException(status_code = 409, detail = str(exc)) from exc
except sqlite3.IntegrityError as exc:
@@ -420,7 +439,7 @@ def active_research_runs(
):
return {
"runs": db.list_active(thread_id),
- "hasRun": db.has_thread_claim(thread_id),
+ "hasRun": db.research_spent(thread_id),
}
diff --git a/studio/backend/storage/research_runs_db.py b/studio/backend/storage/research_runs_db.py
index 5c5905017a8..24a7a74e83b 100644
--- a/studio/backend/storage/research_runs_db.py
+++ b/studio/backend/storage/research_runs_db.py
@@ -129,6 +129,77 @@ def append_worker_event(
conn.close()
+def _bind_assistant_locked(
+ conn: sqlite3.Connection,
+ *,
+ run_id: str,
+ thread_id: str,
+ user_message_id: str,
+ assistant_message_id: str | None,
+ plan_revision: int,
+ created: int,
+) -> None:
+ if not assistant_message_id:
+ return
+ message = conn.execute(
+ "SELECT * FROM chat_messages WHERE id=?", (assistant_message_id,)
+ ).fetchone()
+ metadata = {
+ "researchRunId": run_id,
+ "researchStatus": "planning",
+ "researchPlanRevision": plan_revision,
+ "serverManaged": True,
+ }
+ if message is None:
+ conn.execute(
+ """INSERT INTO chat_messages
+ (id, thread_id, parent_id, role, content_json, metadata_json, created_at)
+ VALUES (?, ?, ?, 'assistant', '[]', ?, ?)""",
+ (
+ assistant_message_id,
+ thread_id,
+ user_message_id,
+ json.dumps(metadata, ensure_ascii = False),
+ created,
+ ),
+ )
+ conn.execute(
+ "UPDATE chat_threads SET updated_at=MAX(COALESCE(updated_at, created_at), ?) WHERE id=?",
+ (created, thread_id),
+ )
+ return
+ existing_metadata = _loads(message["metadata_json"], {})
+ existing_run_id = (
+ existing_metadata.get("researchRunId") if isinstance(existing_metadata, dict) else None
+ )
+ # Only bind to an empty placeholder or this run's own message: an untagged
+ # reply carries text/source parts that _update_assistant drops on completion,
+ # so binding one silently overwrites an existing answer.
+ existing_answer = any(
+ isinstance(part, dict)
+ and (
+ (part.get("type") == "text" and (part.get("text") or "").strip())
+ or part.get("type") == "source"
+ )
+ and part.get("researchRunId") is None
+ for part in _loads(message["content_json"], [])
+ )
+ if (
+ message["thread_id"] != thread_id
+ or message["role"] != "assistant"
+ or message["parent_id"] != user_message_id
+ or existing_run_id not in (None, run_id)
+ or (existing_run_id is None and existing_answer)
+ ):
+ raise ResearchConflictError("Assistant message does not match this research run")
+ merged_metadata = dict(existing_metadata) if isinstance(existing_metadata, dict) else {}
+ merged_metadata.update(metadata)
+ conn.execute(
+ "UPDATE chat_messages SET metadata_json=? WHERE id=?",
+ (json.dumps(merged_metadata, ensure_ascii = False), assistant_message_id),
+ )
+
+
def create_run(
*,
run_id: str,
@@ -157,71 +228,15 @@ def create_run(
if claim is not None:
raise ResearchConflictError("This thread already has a Deep Research run") from exc
raise
- if assistant_message_id:
- message = conn.execute(
- "SELECT * FROM chat_messages WHERE id=?", (assistant_message_id,)
- ).fetchone()
- metadata = {
- "researchRunId": run_id,
- "researchStatus": "planning",
- "researchPlanRevision": 0,
- "serverManaged": True,
- }
- if message is None:
- conn.execute(
- """INSERT INTO chat_messages
- (id, thread_id, parent_id, role, content_json, metadata_json, created_at)
- VALUES (?, ?, ?, 'assistant', '[]', ?, ?)""",
- (
- assistant_message_id,
- thread_id,
- user_message_id,
- json.dumps(metadata, ensure_ascii = False),
- created,
- ),
- )
- conn.execute(
- "UPDATE chat_threads SET updated_at=MAX(COALESCE(updated_at, created_at), ?) "
- "WHERE id=?",
- (created, thread_id),
- )
- else:
- existing_metadata = _loads(message["metadata_json"], {})
- existing_run_id = (
- existing_metadata.get("researchRunId")
- if isinstance(existing_metadata, dict)
- else None
- )
- # Only bind to an empty placeholder or this run's own message: an untagged
- # reply carries text/source parts that _update_assistant drops on completion,
- # so binding one silently overwrites an existing answer.
- existing_answer = any(
- isinstance(part, dict)
- and (
- (part.get("type") == "text" and (part.get("text") or "").strip())
- or part.get("type") == "source"
- )
- and part.get("researchRunId") is None
- for part in _loads(message["content_json"], [])
- )
- if (
- message["thread_id"] != thread_id
- or message["role"] != "assistant"
- or message["parent_id"] != user_message_id
- or existing_run_id not in (None, run_id)
- or (existing_run_id is None and existing_answer)
- ):
- raise ResearchConflictError(
- "Assistant message does not match this research run"
- )
- merged_metadata = (
- dict(existing_metadata) if isinstance(existing_metadata, dict) else {}
- )
- merged_metadata.update(metadata)
- conn.execute(
- "UPDATE chat_messages SET metadata_json=? WHERE id=?",
- (json.dumps(merged_metadata, ensure_ascii = False), assistant_message_id),
- )
+ _bind_assistant_locked(
+ conn,
+ run_id = run_id,
+ thread_id = thread_id,
+ user_message_id = user_message_id,
+ assistant_message_id = assistant_message_id,
+ plan_revision = 0,
+ created = created,
+ )
conn.execute(
"""
INSERT INTO research_runs
@@ -250,6 +265,145 @@ def create_run(
return get_run(run_id, owner_subject)
+def _unbind_assistant_locked(
+ conn: sqlite3.Connection, previous_id: str | None, next_id: str | None
+) -> None:
+ """Drop the research binding from the reply the run is leaving behind.
+
+ Both replies would otherwise carry the same run id, and each renders whatever that run is
+ doing now -- so the new question's live card would appear twice.
+ """
+ if not previous_id or previous_id == next_id:
+ return
+ row = conn.execute(
+ "SELECT metadata_json FROM chat_messages WHERE id=?", (previous_id,)
+ ).fetchone()
+ if row is None:
+ return
+ metadata = _loads(row["metadata_json"], {})
+ if not isinstance(metadata, dict):
+ return
+ for key in ("researchRunId", "researchStatus", "researchPlanRevision", "serverManaged"):
+ metadata.pop(key, None)
+ conn.execute(
+ "UPDATE chat_messages SET metadata_json=? WHERE id=?",
+ (json.dumps(metadata, ensure_ascii = False), previous_id),
+ )
+
+
+def _stopped_run_locked(conn: sqlite3.Connection, thread_id: str) -> sqlite3.Row | None:
+ """The claim owner's latest run, when stopped and available for a new question."""
+ run = conn.execute(
+ """SELECT r.id, r.status, r.owner_subject, r.plan_revision, r.assistant_message_id
+ FROM research_thread_claims AS c
+ JOIN research_runs AS r
+ ON r.thread_id=c.thread_id AND r.owner_subject=c.owner_subject
+ WHERE c.thread_id=?
+ ORDER BY r.created_at DESC, r.id DESC
+ LIMIT 1""",
+ (thread_id,),
+ ).fetchone()
+ if run is None or run["status"] != "cancelled":
+ return None
+ return run
+
+
+def research_spent(thread_id: str) -> bool:
+ """Whether the thread's research is used up, which is what the composer greys out on.
+
+ The claim itself outlives a stopped run so the same run can be re-pointed, so a held
+ claim alone must not read as spent: after a Stop, research is still on offer.
+ """
+ conn = get_connection()
+ try:
+ claim = conn.execute(
+ "SELECT 1 FROM research_thread_claims WHERE thread_id=?", (thread_id,)
+ ).fetchone()
+ return claim is not None and _stopped_run_locked(conn, thread_id) is None
+ finally:
+ conn.close()
+
+
+def rebind_cancelled(
+ *,
+ thread_id: str,
+ user_message_id: str,
+ assistant_message_id: str | None,
+ config: dict[str, Any],
+) -> dict | None:
+ """Re-point the thread's stopped run at a newer message, or return None.
+
+ A thread holds one Deep Research run for its lifetime, so a run the user stopped would
+ otherwise refuse every later question in that chat. Stopping kept nothing, so the same
+ run is reset and pointed at the new message instead of a second one being created.
+ """
+ conn = get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ run = _stopped_run_locked(conn, thread_id)
+ if run is None:
+ conn.commit()
+ return None
+ message = conn.execute(
+ "SELECT role, thread_id FROM chat_messages WHERE id=?", (user_message_id,)
+ ).fetchone()
+ if message is None or message["role"] != "user" or message["thread_id"] != thread_id:
+ conn.commit()
+ return None
+ run_id = run["id"]
+ revision = int(run["plan_revision"]) + 1
+ now = now_ms()
+ _unbind_assistant_locked(conn, run["assistant_message_id"], assistant_message_id)
+ _bind_assistant_locked(
+ conn,
+ run_id = run_id,
+ thread_id = thread_id,
+ user_message_id = user_message_id,
+ assistant_message_id = assistant_message_id,
+ plan_revision = revision,
+ created = now,
+ )
+ # retry_count is the attempt epoch every event is stamped with, and the new question
+ # is a new attempt: without the bump its report would carry the stopped question's
+ # reasoning (get_reasoning_text joins every event at the run's current attempt) and its
+ # activity panel would fold the two questions together. The retry BUDGET is counted per
+ # question in retry(), so spending an epoch here does not spend a retry.
+ conn.execute(
+ "UPDATE research_runs SET user_message_id=?, assistant_message_id=?, "
+ "status='planning', cancel_requested=0, plan_json=NULL, plan_hash=NULL, "
+ "plan_revision=?, retry_count=retry_count + 1, error_message=NULL, "
+ "report_text=NULL, created_at=?, heartbeat_at=?, started_at=NULL, "
+ "completed_at=NULL, lease_owner=NULL, lease_expires_at=NULL, config_json=?, "
+ "updated_at=? WHERE id=?",
+ (
+ user_message_id,
+ assistant_message_id,
+ revision,
+ now,
+ now,
+ json.dumps(config, ensure_ascii = False),
+ now,
+ run_id,
+ ),
+ )
+ conn.execute("DELETE FROM research_plan_steps WHERE run_id=?", (run_id,))
+ conn.execute("DELETE FROM research_sources WHERE run_id=?", (run_id,))
+ conn.execute("DELETE FROM research_document_sources WHERE run_id=?", (run_id,))
+ # Events replay into the activity panel, so a kept approval would show "Plan approved"
+ # for a question this run no longer researches.
+ conn.execute(
+ "DELETE FROM research_events WHERE run_id=? AND event_type='run.approved'", (run_id,)
+ )
+ _event_locked(conn, run_id, "run.rebound", {"status": "planning"})
+ _commit_event(conn)
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ return get_run(run_id)
+
+
def _row_to_run(row: sqlite3.Row) -> dict[str, Any]:
data = dict(row)
return {
@@ -402,7 +556,8 @@ def create_and_bind_terminal_fallback(
status: str,
sources: list[dict] | None = None,
completion_worker_id: str | None = None,
-) -> tuple[str, bool]:
+ expected_attempt: int | None = None,
+) -> tuple[str | None, bool]:
"""Discover a frontend message or atomically create exactly one fallback."""
if status not in TERMINAL_STATUSES:
raise ValueError(status)
@@ -412,6 +567,9 @@ def create_and_bind_terminal_fallback(
run = conn.execute("SELECT * FROM research_runs WHERE id=?", (run_id,)).fetchone()
if run is None:
raise KeyError(run_id)
+ if expected_attempt is not None and int(run["retry_count"]) != expected_attempt:
+ conn.commit()
+ return None, False
can_prepare_completion = (
completion_worker_id is not None
and status == "completed"
@@ -430,7 +588,8 @@ def create_and_bind_terminal_fallback(
conn.commit()
return message_id, False
- message_id = f"research-{run_id}"
+ attempt = int(run["retry_count"])
+ message_id = f"research-{run_id}" if attempt == 0 else f"research-{run_id}-{attempt}"
parts: list[dict[str, Any]] = [{"type": "text", "text": text, "researchRunId": run_id}]
for source in sources or []:
parts.append(
@@ -493,9 +652,18 @@ def set_plan(
plan: dict,
expected_revision: int | None = None,
worker_id: str | None = None,
+ auto_approve: bool = False,
) -> dict:
+ """Store the plan and either park the run for review or queue it in the same write.
+
+ Arming research in the composer is the approval, so the worker queues its own plan with
+ ``auto_approve``. Done in one transaction: a separate approve call left a window where
+ the run sat at awaiting_approval, flashing the review card and letting a concurrent plan
+ edit fail the run. The endpoint still parks a hand-edited plan for the user to confirm.
+ """
raw, digest = canonical_plan(plan)
steps = plan.get("steps") or []
+ status = "queued" if auto_approve else "awaiting_approval"
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
@@ -522,9 +690,9 @@ def set_plan(
revision += 1
conn.execute(
"UPDATE research_runs SET plan_json = ?, plan_revision = ?, plan_hash = ?, "
- "status = 'awaiting_approval', error_message = NULL, lease_owner = NULL, "
+ "status = ?, error_message = NULL, lease_owner = NULL, "
"lease_expires_at = NULL, updated_at = ? WHERE id = ?",
- (raw, revision, digest, now_ms(), run_id),
+ (raw, revision, digest, status, now_ms(), run_id),
)
conn.execute("DELETE FROM research_plan_steps WHERE run_id = ?", (run_id,))
conn.executemany(
@@ -539,12 +707,14 @@ def set_plan(
run_id,
"plan.ready",
{
- "status": "awaiting_approval",
+ "status": status,
"plan": plan,
"planRevision": revision,
"planHash": digest,
},
)
+ if auto_approve:
+ _event_locked(conn, run_id, "run.approved", {"status": status})
_commit_event(conn)
return {"plan": plan, "planRevision": revision, "planHash": digest}
except Exception:
@@ -628,7 +798,16 @@ def retry(run_id: str, max_retries: int = 3) -> str:
raise KeyError(run_id)
if row["status"] not in {"failed", "cancelled"}:
raise ResearchConflictError("Only failed or cancelled runs can be retried")
- if int(row["retry_count"]) >= max_retries:
+ # Counted per question, not per run row: a thread holds one run for its lifetime and
+ # re-points it at each new question, so a raw retry_count would hand a fresh question
+ # whatever the stopped one left over -- and nothing at all once three were spent.
+ spent = conn.execute(
+ "SELECT COUNT(*) FROM research_events WHERE run_id=? AND event_type='run.retried' "
+ "AND seq > COALESCE((SELECT MAX(seq) FROM research_events "
+ "WHERE run_id=? AND event_type='run.rebound'), 0)",
+ (run_id, run_id),
+ ).fetchone()[0]
+ if int(spent) >= max_retries:
raise ResearchConflictError("Retry budget exhausted")
claim = conn.execute(
"SELECT owner_subject FROM research_thread_claims WHERE thread_id=?",
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 7d10c2722eb..788b0e8b8ac 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -3075,10 +3075,33 @@ def _ensure_chat_attachment_inventory_current(conn: sqlite3.Connection) -> None:
raise
-def upsert_chat_message(message: dict, *, allow_research_update: bool = False) -> dict:
+def upsert_chat_message(
+ message: dict,
+ *,
+ allow_research_update: bool = False,
+ expected_research_run_id: str | None = None,
+ expected_research_attempt: int | None = None,
+) -> dict | None:
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
+ if expected_research_run_id is not None:
+ if expected_research_attempt is None:
+ raise ValueError("expected_research_attempt is required with a research run")
+ current = conn.execute(
+ "SELECT 1 FROM research_runs "
+ "WHERE id = ? AND thread_id = ? AND assistant_message_id = ? "
+ "AND retry_count = ?",
+ (
+ expected_research_run_id,
+ message["threadId"],
+ message["id"],
+ expected_research_attempt,
+ ),
+ ).fetchone()
+ if current is None:
+ conn.rollback()
+ return None
_ensure_chat_attachment_inventory_current(conn)
if not allow_research_update:
_guard_research_messages(conn, message["threadId"], [message])
diff --git a/studio/backend/tests/test_deep_research_handoff_simulation.py b/studio/backend/tests/test_deep_research_handoff_simulation.py
new file mode 100644
index 00000000000..8c06c3fee30
--- /dev/null
+++ b/studio/backend/tests/test_deep_research_handoff_simulation.py
@@ -0,0 +1,515 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""End-to-end simulation of the Deep Research handoff, and of what it must not change.
+
+Arming research used to create a run before the model read the message, so "hi" spent the
+thread's one run on a greeting. Now the model is offered a `deep_research` tool and decides.
+These drive the real loop, the real tool catalog and the real supervisor with a scripted model,
+covering both halves: that the decision reaches the run, and that every path that existed
+before still behaves the way it did.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import studio_tool_loop as loop_mod
+from core.inference.studio_tool_loop import (
+ ToolLoopPolicy,
+ ToolLoopRun,
+ stream_with_studio_tools,
+)
+from core.inference.tools import (
+ DEEP_RESEARCH_STARTED,
+ DEEP_RESEARCH_STARTED_MARKER,
+ DEEP_RESEARCH_TOOL,
+ execute_tool,
+)
+from storage import research_runs_db as research_db
+from storage import studio_db
+
+
+RAW_MESSAGE = "breeds of dogs"
+REFINED = "Which small dog breeds suit a flat with no garden?"
+
+
+def research_home(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(studio_db, "_schema_ready", False)
+ studio_db.upsert_chat_thread(
+ {
+ "id": "thread-1",
+ "title": "Research",
+ "modelType": "base",
+ "modelId": "local-model",
+ "createdAt": 1,
+ }
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": "user-1",
+ "threadId": "thread-1",
+ "role": "user",
+ "content": [{"type": "text", "text": RAW_MESSAGE}],
+ "createdAt": 2,
+ }
+ )
+ return tmp_path
+
+
+# ── The scripted model ────────────────────────────────────────────
+
+_DONE = "data: [DONE]"
+
+
+def _sse(delta = None, finish = None) -> str:
+ choice: dict = {"index": 0, "delta": delta or {}}
+ if finish is not None:
+ choice["finish_reason"] = finish
+ return "data: " + json.dumps({"choices": [choice]})
+
+
+def _says(text: str) -> list[str]:
+ return [_sse({"content": text}), _sse(finish = "stop"), _DONE]
+
+
+def _calls_research(question: str, preamble: str = "") -> list[str]:
+ lines = [_sse({"content": preamble})] if preamble else []
+ lines += [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_r",
+ "function": {
+ "name": "deep_research",
+ "arguments": json.dumps({"question": question}),
+ },
+ }
+ ]
+ }
+ ),
+ _sse(finish = "tool_calls"),
+ _DONE,
+ ]
+ return lines
+
+
+class ScriptedModel:
+ def __init__(self, turns):
+ self.turns = [list(turn) for turn in turns]
+ self.heals_text_tool_calls = True
+ self.requests: list[dict] = []
+
+ def stream(self, *, messages, tools, tool_choice, cancel_event):
+ self.requests.append({"tools": tools, "tool_choice": tool_choice})
+ lines = self.turns.pop(0) if self.turns else [_DONE]
+
+ async def _gen():
+ for line in lines:
+ yield line
+
+ return _gen()
+
+
+def _run_turn(
+ model,
+ *,
+ tools,
+ monkeypatch,
+ permission_mode = "off",
+ verdict = None,
+):
+ def _execute(name, arguments, **kwargs):
+ return execute_tool(name, arguments) if name == "deep_research" else f"RESULT<{name}>"
+
+ monkeypatch.setattr(loop_mod, "execute_tool", _execute)
+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)
+ if verdict is not None:
+ monkeypatch.setattr(loop_mod, "begin_tool_decision", lambda *a, **k: object())
+ monkeypatch.setattr(loop_mod, "abort_tool_decision", lambda *a, **k: None)
+ monkeypatch.setattr(loop_mod, "wait_tool_decision", lambda *a, **k: verdict)
+
+ async def _collect():
+ out = []
+ agen = stream_with_studio_tools(
+ model,
+ run = ToolLoopRun(
+ messages = [{"role": "user", "content": RAW_MESSAGE}],
+ session_id = "s1",
+ thread_id = "thread-1",
+ tool_choice = None,
+ ),
+ policy = ToolLoopPolicy(
+ tools = tools,
+ max_calls = 25,
+ timeout = 300,
+ permission_mode = permission_mode,
+ confirm_calls = permission_mode == "ask",
+ bypass_permissions = False,
+ rag_scope = None,
+ ),
+ cancel_event = threading.Event(),
+ )
+ async for line in agen:
+ out.append(line)
+ return out
+
+ return asyncio.run(_collect())
+
+
+def _tool_events(lines, tool_name = "deep_research") -> list[dict]:
+ """Every event the client reads the handoff off, in the order it is published."""
+ events = []
+ for line in lines:
+ if not line.startswith("data: ") or line[6:] == "[DONE]":
+ continue
+ payload = json.loads(line[6:])
+ if payload.get("type") in ("tool_start", "tool_end") and (
+ payload.get("tool_name") == tool_name
+ ):
+ events.append(payload)
+ return events
+
+
+def _visible(lines) -> str:
+ text = []
+ for line in lines:
+ if not line.startswith("data: ") or line[6:] == "[DONE]":
+ continue
+ payload = json.loads(line[6:])
+ if payload.get("type") in ("tool_start", "tool_end"):
+ continue
+ for choice in payload.get("choices") or []:
+ content = (choice.get("delta") or {}).get("content")
+ if isinstance(content, str):
+ text.append(content)
+ return "".join(text)
+
+
+# ── What the loop publishes, which is all the client has to go on ─
+
+
+def test_the_loop_publishes_the_question_and_a_result_that_says_it_ran(research_home, monkeypatch):
+ model = ScriptedModel([_calls_research(REFINED), _says("Looking into it.")])
+ lines = _run_turn(model, tools = [DEEP_RESEARCH_TOOL], monkeypatch = monkeypatch)
+
+ started, ended = _tool_events(lines)
+ assert started["type"] == "tool_start"
+ assert started["arguments"]["question"] == REFINED
+ assert started["tool_call_id"] == ended["tool_call_id"]
+ assert ended["result"] == DEEP_RESEARCH_STARTED
+ assert ended["result"].startswith(DEEP_RESEARCH_STARTED_MARKER)
+ assert _visible(lines) == "Looking into it."
+
+
+def test_a_denied_call_is_closed_by_the_same_event_and_says_it_did_not_run(
+ research_home, monkeypatch
+):
+ """Ask mode gates every tool. The client cannot read tool_end as "it ran"."""
+ model = ScriptedModel([_calls_research(REFINED), _says("Alright.")])
+ lines = _run_turn(
+ model,
+ tools = [DEEP_RESEARCH_TOOL],
+ monkeypatch = monkeypatch,
+ permission_mode = "ask",
+ verdict = "deny",
+ )
+
+ started, ended = _tool_events(lines)
+ # The card carries the approval prompt, so the client has to draw it: the loop is blocked
+ # on a verdict until someone answers.
+ assert started["awaiting_confirmation"] is True
+ assert started["approval_id"]
+ assert ended["result"] != DEEP_RESEARCH_STARTED
+ assert not ended["result"].startswith(DEEP_RESEARCH_STARTED_MARKER)
+
+
+def test_an_approved_call_runs_like_any_other(research_home, monkeypatch):
+ model = ScriptedModel([_calls_research(REFINED), _says("Looking into it.")])
+ lines = _run_turn(
+ model,
+ tools = [DEEP_RESEARCH_TOOL],
+ monkeypatch = monkeypatch,
+ permission_mode = "ask",
+ verdict = "allow",
+ )
+
+ started, ended = _tool_events(lines)
+ assert started["awaiting_confirmation"] is True
+ assert ended["result"] == DEEP_RESEARCH_STARTED
+
+
+def test_a_spent_call_budget_closes_the_card_without_running_it(research_home, monkeypatch):
+ """The same tool_end shape, for a call the loop announced and refused."""
+ model = ScriptedModel([_calls_research(REFINED), _says("Alright.")])
+
+ def _execute(name, arguments, **kwargs):
+ raise AssertionError("the budget was spent; nothing may run")
+
+ monkeypatch.setattr(loop_mod, "execute_tool", _execute)
+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)
+
+ async def _collect():
+ out = []
+ async for line in stream_with_studio_tools(
+ model,
+ run = ToolLoopRun(
+ messages = [{"role": "user", "content": RAW_MESSAGE}],
+ session_id = "s1",
+ thread_id = "thread-1",
+ tool_choice = None,
+ ),
+ policy = ToolLoopPolicy(
+ tools = [DEEP_RESEARCH_TOOL],
+ max_calls = 0,
+ timeout = 300,
+ permission_mode = "off",
+ confirm_calls = False,
+ bypass_permissions = False,
+ rag_scope = None,
+ ),
+ cancel_event = threading.Event(),
+ ):
+ out.append(line)
+ return out
+
+ _started, ended = _tool_events(asyncio.run(_collect()))
+ assert not ended["result"].startswith(DEEP_RESEARCH_STARTED_MARKER)
+
+
+def test_the_tool_is_only_offered_to_the_model_when_it_is_in_the_catalog(
+ research_home, monkeypatch
+):
+ model = ScriptedModel([_says("Hello.")])
+ _run_turn(model, tools = [DEEP_RESEARCH_TOOL], monkeypatch = monkeypatch)
+ offered = [tool["function"]["name"] for tool in model.requests[0]["tools"]]
+
+ assert offered == ["deep_research"]
+
+
+# ── What the change is for ────────────────────────────────────────
+
+
+def test_the_handed_off_question_is_what_actually_gets_researched(research_home, monkeypatch):
+ """The refined question reaches the planner, not the raw message it came from."""
+ from core import research_runs as worker
+
+ research_db.create_run(
+ run_id = "run-1",
+ owner_subject = "alice",
+ thread_id = "thread-1",
+ user_message_id = "user-1",
+ assistant_message_id = None,
+ config = {
+ "model": "local-model",
+ "inferenceRequest": {"model": "local-model"},
+ "ragScope": None,
+ "instructions": "",
+ "question": REFINED,
+ "budgets": {
+ "maxSteps": 5,
+ "maxSources": 15,
+ "modelTimeoutSeconds": 30,
+ "toolTimeoutSeconds": 10,
+ },
+ },
+ )
+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))
+ prompts: list[str] = []
+
+ async def fake_stream_completion(run, messages, **kwargs):
+ prompts.append(messages[-1]["content"])
+ plan = {"title": "Plan", "steps": [{"title": "Step", "query": "small dog breeds flat"}]}
+ return json.dumps(plan), "", "stop", None
+
+ monkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)
+ claimed = research_db.claim_next(supervisor.worker_id)
+ asyncio.run(supervisor._plan(claimed))
+
+ assert REFINED in prompts[0]
+ assert RAW_MESSAGE not in prompts[0].split("Latest research request:")[-1]
+
+
+def test_planning_no_longer_stops_to_ask_for_approval(research_home, monkeypatch):
+ from core import research_runs as worker
+
+ research_db.create_run(
+ run_id = "run-1",
+ owner_subject = "alice",
+ thread_id = "thread-1",
+ user_message_id = "user-1",
+ assistant_message_id = None,
+ config = {
+ "model": "local-model",
+ "inferenceRequest": {"model": "local-model"},
+ "ragScope": None,
+ "instructions": "",
+ "budgets": {
+ "maxSteps": 5,
+ "maxSources": 15,
+ "modelTimeoutSeconds": 30,
+ "toolTimeoutSeconds": 10,
+ },
+ },
+ )
+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))
+
+ async def fake_stream_completion(run, messages, **kwargs):
+ plan = {"title": "Plan", "steps": [{"title": "Step", "query": "q"}]}
+ return json.dumps(plan), "", "stop", None
+
+ monkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)
+ claimed = research_db.claim_next(supervisor.worker_id)
+ asyncio.run(supervisor._plan(claimed))
+
+ assert research_db.get_run("run-1")["status"] == "queued"
+
+
+# ── What the change must not break ────────────────────────────────
+
+
+def test_a_run_from_an_old_install_researches_its_user_message(research_home, monkeypatch):
+ """Config written before this change has no "question" key at all."""
+ from core import research_runs as worker
+
+ research_db.create_run(
+ run_id = "run-1",
+ owner_subject = "alice",
+ thread_id = "thread-1",
+ user_message_id = "user-1",
+ assistant_message_id = None,
+ config = {
+ "model": "local-model",
+ "inferenceRequest": {"model": "local-model"},
+ "ragScope": None,
+ "instructions": "",
+ "budgets": {
+ "maxSteps": 5,
+ "maxSources": 15,
+ "modelTimeoutSeconds": 30,
+ "toolTimeoutSeconds": 10,
+ },
+ },
+ )
+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))
+ prompts: list[str] = []
+
+ async def fake_stream_completion(run, messages, **kwargs):
+ prompts.append(messages[-1]["content"])
+ plan = {"title": "Plan", "steps": [{"title": "Step", "query": "q"}]}
+ return json.dumps(plan), "", "stop", None
+
+ monkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)
+ claimed = research_db.claim_next(supervisor.worker_id)
+ asyncio.run(supervisor._plan(claimed))
+
+ assert RAW_MESSAGE in prompts[0]
+
+
+def test_a_run_left_awaiting_approval_by_an_old_install_still_runs(research_home):
+ """Upgrading mid-run must not strand it: the approval endpoint still moves it along."""
+ research_db.create_run(
+ run_id = "run-1",
+ owner_subject = "alice",
+ thread_id = "thread-1",
+ user_message_id = "user-1",
+ assistant_message_id = None,
+ config = {
+ "model": "local-model",
+ "inferenceRequest": {"model": "local-model"},
+ "ragScope": None,
+ "instructions": "",
+ "budgets": {
+ "maxSteps": 5,
+ "maxSources": 15,
+ "modelTimeoutSeconds": 30,
+ "toolTimeoutSeconds": 10,
+ },
+ },
+ )
+ plan = research_db.set_plan(
+ "run-1", {"title": "Plan", "steps": [{"title": "Step", "query": "q"}]}
+ )
+ assert research_db.get_run("run-1")["status"] == "awaiting_approval"
+
+ assert research_db.approve("run-1", plan["planRevision"], plan["planHash"]) == "queued"
+ assert research_db.claim_next("worker-1") is not None
+
+
[email protected]("armed", [True, False])
+def test_the_tool_is_offered_only_when_research_is_armed(armed):
+ from models.inference import ChatCompletionRequest
+ from routes.inference import _select_request_tools
+
+ payload = ChatCompletionRequest(
+ model = "local-model",
+ messages = [{"role": "user", "content": RAW_MESSAGE}],
+ enabled_tools = [],
+ deep_research_armed = armed,
+ )
+ tools = asyncio.run(_select_request_tools(payload, tools_on = True, mcp_allowed = False))
+ names = [tool["function"]["name"] for tool in tools]
+
+ assert ("deep_research" in names) is armed
+
+
+def test_an_unarmed_request_is_byte_identical_to_before():
+ """The tool list a normal chat sends must not move because this feature exists.
+
+ Compared against the armed selection rather than a frozen catalog, which any unrelated
+ built-in would fail without saying anything about this feature.
+ """
+ from models.inference import ChatCompletionRequest
+ from routes.inference import _select_request_tools
+
+ def _names(**extra):
+ payload = ChatCompletionRequest(
+ model = "local-model",
+ messages = [{"role": "user", "content": "hello"}],
+ **extra,
+ )
+ tools = asyncio.run(_select_request_tools(payload, tools_on = True, mcp_allowed = False))
+ return [tool["function"]["name"] for tool in tools]
+
+ unarmed = _names()
+ assert "deep_research" not in unarmed
+ assert unarmed
+ # Appended, and nothing else moves: same catalog, in the same order, plus the one tool.
+ assert _names(deep_research_armed = True) == [*unarmed, "deep_research"]
+
+
+def test_a_client_that_never_heard_of_the_field_still_validates():
+ """Old clients, and third parties on the OpenAI-compatible API, send no such field."""
+ from models.inference import ChatCompletionRequest
+
+ payload = ChatCompletionRequest(
+ model = "local-model", messages = [{"role": "user", "content": "hi"}]
+ )
+ assert payload.deep_research_armed is None
+
+
+def test_an_empty_question_is_refused_rather_than_researched_blank():
+ from core.inference.tools import execute_tool
+
+ result = execute_tool("deep_research", {"question": " "})
+ assert result != DEEP_RESEARCH_STARTED
+ assert "Error" in result
+
+
+def test_the_result_is_an_ordinary_string_every_tool_loop_can_feed_back():
+ """Studio runs three tool loops; only a plain result behaves the same in all of them."""
+ from core.inference.tools import execute_tool, is_high_risk_tool_call
+
+ result = execute_tool("deep_research", {"question": "x" * 10_000})
+ assert result == DEEP_RESEARCH_STARTED
+ assert result.isprintable()
+ assert is_high_risk_tool_call("deep_research", {"question": "x"}) is False
diff --git a/studio/backend/tests/test_research_runs_storage.py b/studio/backend/tests/test_research_runs_storage.py
index 8b16039be76..1b00bdc774f 100644
--- a/studio/backend/tests/test_research_runs_storage.py
+++ b/studio/backend/tests/test_research_runs_storage.py
@@ -1780,13 +1780,14 @@ def test_supervisor_planning_and_research_are_durable_with_mocked_io(
planning = research_db.claim_next(supervisor.worker_id)
asyncio.run(supervisor._process(planning))
planned = research_db.get_run("run-1")
- assert planned["status"] == "awaiting_approval"
+ # Planning approves itself: arming research in the composer is the approval, so there is
+ # no second confirmation between the plan and the evidence gathering.
+ assert planned["status"] == "queued"
assert planned["planRevision"] == 1
assert planned["assistantMessageId"] is None
- research_db.approve("run-1", planned["planRevision"], planned["planHash"])
running = research_db.claim_next(supervisor.worker_id)
- assert running is not None # planning released its lease; approval starts immediately
+ assert running is not None # planning released its lease; the queued run starts immediately
asyncio.run(supervisor._process(running))
completed = research_db.get_run("run-1")
@@ -2785,6 +2786,28 @@ def test_shared_chat_subject_can_follow_and_cancel_research(research_home):
assert cancelled["status"] == "cancelling"
+def test_shared_chat_subject_can_repoint_stopped_research(research_home):
+ from routes.research_runs import CreateResearchRun, create_research_run
+
+ _create()
+ _cancel_run()
+ _new_user_message()
+
+ reused = create_research_run(
+ CreateResearchRun(
+ threadId = "thread-1",
+ userMessageId = "user-2",
+ inferenceRequest = {"model": "local-model"},
+ ),
+ SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace())),
+ current_subject = "bob",
+ )
+
+ assert reused["id"] == "run-1"
+ assert reused["ownerSubject"] == "alice"
+ assert reused["status"] == "planning"
+
+
def test_list_active_returns_complete_snapshots(research_home):
_create()
research_db.set_plan("run-1", _plan())
@@ -3746,3 +3769,581 @@ def test_an_authorized_reparent_of_a_research_row_is_not_overwritten(research_ho
assert studio_db.get_chat_message("thread-1", "ancestor") is None
assert studio_db.get_chat_message("thread-1", "user-1")["parentId"] == "keeper"
assert _thread_imports_cleanly()
+
+
+def _new_user_message(message_id = "user-2", created_at = 20):
+ studio_db.upsert_chat_message(
+ {
+ "id": message_id,
+ "threadId": "thread-1",
+ "role": "user",
+ "content": [{"type": "text", "text": "What changed in the EU AI Act?"}],
+ "createdAt": created_at,
+ }
+ )
+ return message_id
+
+
+def _rebind(
+ user_message_id,
+ assistant_message_id = None,
+ thread_id = "thread-1",
+):
+ return research_db.rebind_cancelled(
+ thread_id = thread_id,
+ user_message_id = user_message_id,
+ assistant_message_id = assistant_message_id,
+ config = {
+ "model": "local-model",
+ "inferenceRequest": {"model": "local-model"},
+ "ragScope": None,
+ "instructions": "",
+ "budgets": {
+ "maxSteps": 5,
+ "maxSources": 15,
+ "modelTimeoutSeconds": 30,
+ "toolTimeoutSeconds": 10,
+ },
+ },
+ )
+
+
+def _cancel_run():
+ research_db.request_cancel("run-1")
+ research_db.claim_next("worker-1")
+ research_db.finish("run-1", "worker-1", "cancelled")
+
+
+def test_stopped_run_is_repointed_at_a_newer_message(research_home):
+ _create()
+ _cancel_run()
+
+ reused = _rebind(_new_user_message())
+ assert reused is not None
+ assert reused["id"] == "run-1"
+ assert reused["status"] == "planning"
+ assert reused["userMessageId"] == "user-2"
+ assert research_db.has_thread_claim("thread-1") is True
+
+
+def test_no_placeholder_rebind_gets_a_fresh_terminal_fallback(research_home):
+ _create(assistant_message_id = None)
+ _cancel_run()
+ first_id, first_created = research_db.create_and_bind_terminal_fallback(
+ "run-1", text = "Research cancelled.", status = "cancelled"
+ )
+ assert first_created is True
+
+ assert _rebind(_new_user_message(), assistant_message_id = None) is not None
+ research_db.set_plan("run-1", _plan())
+ assert research_db.request_cancel("run-1") == "cancelled"
+ second_id, second_created = research_db.create_and_bind_terminal_fallback(
+ "run-1", text = "Research cancelled again.", status = "cancelled"
+ )
+
+ assert second_created is True
+ assert second_id != first_id
+ first = studio_db.get_chat_message("thread-1", first_id)
+ second = studio_db.get_chat_message("thread-1", second_id)
+ assert first["parentId"] == "user-1"
+ assert second["parentId"] == "user-2"
+ assert second["content"][0]["text"] == "Research cancelled again."
+
+
+def test_migrated_history_does_not_hide_the_claim_owner_s_stopped_run(research_home):
+ _create()
+ conn = studio_db.get_connection()
+ try:
+ conn.executemany(
+ """INSERT INTO research_runs
+ (id, owner_subject, thread_id, user_message_id, status, config_json,
+ created_at, updated_at, completed_at, error_message)
+ VALUES (?, ?, 'thread-1', 'user-1', ?, '{}', ?, ?, ?, ?)""",
+ [
+ ("legacy-completed", "alice", "completed", 1, 1, 1, None),
+ ("legacy-superseded", "bob", "failed", 2, 2, 2, "Superseded"),
+ ],
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ _cancel_run()
+
+ assert research_db.research_spent("thread-1") is False
+ reused = _rebind(_new_user_message())
+ assert reused is not None
+ assert reused["id"] == "run-1"
+ assert reused["status"] == "planning"
+
+
+def test_repointed_run_starts_a_fresh_attempt_clock(research_home, monkeypatch):
+ _create()
+ _cancel_run()
+ monkeypatch.setattr(research_db, "now_ms", lambda: 5_000_000)
+
+ reused = _rebind(_new_user_message())
+
+ assert reused is not None
+ assert reused["createdAt"] == 5_000_000
+ assert reused["heartbeatAt"] == 5_000_000
+ assert reused["updatedAt"] == 5_000_000
+
+
+def test_repointing_clears_the_stopped_run_of_its_old_question(research_home):
+ _create()
+ plan = research_db.set_plan("run-1", _plan())
+ research_db.approve("run-1", plan["planRevision"], plan["planHash"])
+ research_db.claim_next("worker-1")
+ research_db.upsert_source("run-1", 0, "https://example.com/a", "A", "snippet")
+ research_db.request_cancel("run-1")
+ research_db.finish("run-1", "worker-1", "cancelled")
+
+ reused = _rebind(_new_user_message())
+ assert reused is not None
+ assert reused["plan"] is None
+ assert reused["steps"] == []
+ assert reused["sources"] == []
+ assert reused["planRevision"] > plan["planRevision"]
+ # Events replay into the activity panel, so a kept approval would claim the new question's
+ # plan was already approved.
+ types = [event["type"] for event in research_db.list_events("run-1")]
+ assert "run.approved" not in types
+ assert types[-1] == "run.rebound"
+
+
+def test_repointing_refuses_a_run_that_is_still_going(research_home):
+ _create()
+ assert _rebind(_new_user_message()) is None
+
+ plan = research_db.set_plan("run-1", _plan())
+ research_db.approve("run-1", plan["planRevision"], plan["planHash"])
+ assert _rebind("user-2") is None
+
+
+def test_repointing_refuses_a_message_that_is_not_this_thread_s_question(research_home):
+ _create()
+ _cancel_run()
+
+ studio_db.upsert_chat_thread(
+ {
+ "id": "thread-2",
+ "title": "Other",
+ "modelType": "base",
+ "modelId": "local-model",
+ "createdAt": 1,
+ }
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": "user-elsewhere",
+ "threadId": "thread-2",
+ "role": "user",
+ "content": [{"type": "text", "text": "Elsewhere"}],
+ "createdAt": 20,
+ }
+ )
+ assert _rebind("user-elsewhere") is None
+ assert _rebind("assistant-1") is None
+ assert _rebind("missing-message") is None
+
+
+def test_route_repoints_a_stopped_run_at_the_next_question(research_home):
+ from routes.research_runs import CreateResearchRun, create_research_run
+
+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
+ created = create_research_run(
+ CreateResearchRun(
+ threadId = "thread-1",
+ userMessageId = "user-1",
+ inferenceRequest = {"model": "local-model"},
+ ),
+ request,
+ current_subject = "alice",
+ )
+ assert created["status"] == "planning"
+
+ research_db.request_cancel(created["id"])
+ research_db.claim_next("worker-1")
+ research_db.finish(created["id"], "worker-1", "cancelled")
+
+ _new_user_message()
+ reused = create_research_run(
+ CreateResearchRun(
+ threadId = "thread-1",
+ userMessageId = "user-2",
+ inferenceRequest = {"model": "local-model"},
+ ),
+ request,
+ current_subject = "alice",
+ )
+ assert reused["id"] == created["id"]
+ assert reused["status"] == "planning"
+ assert reused["userMessageId"] == "user-2"
+
+
+def test_route_still_refuses_a_second_run_while_one_is_going(research_home):
+ from fastapi import HTTPException
+ from routes.research_runs import CreateResearchRun, create_research_run
+
+ request = SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace()))
+ create_research_run(
+ CreateResearchRun(
+ threadId = "thread-1",
+ userMessageId = "user-1",
+ inferenceRequest = {"model": "local-model"},
+ ),
+ request,
+ current_subject = "alice",
+ )
+ _new_user_message()
+ with pytest.raises(HTTPException, match = "already has") as caught:
+ create_research_run(
+ CreateResearchRun(
+ threadId = "thread-1",
+ userMessageId = "user-2",
+ inferenceRequest = {"model": "local-model"},
+ ),
+ request,
+ current_subject = "alice",
+ )
+ assert caught.value.status_code == 409
+
+
+def test_repointing_unbinds_the_reply_it_leaves_behind(research_home):
+ _create()
+ _cancel_run()
+ studio_db.upsert_chat_message(
+ {
+ "id": "assistant-2",
+ "threadId": "thread-1",
+ "parentId": "user-2",
+ "role": "assistant",
+ "content": [],
+ "createdAt": 21,
+ }
+ )
+
+ reused = _rebind(_new_user_message(), assistant_message_id = "assistant-2")
+ assert reused is not None
+ assert reused["assistantMessageId"] == "assistant-2"
+
+ # Both replies pointing at one run would render its live card twice.
+ stale = studio_db.get_chat_message("thread-1", "assistant-1")
+ assert "researchRunId" not in (stale.get("metadata") or {})
+ fresh = studio_db.get_chat_message("thread-1", "assistant-2")
+ assert fresh["metadata"]["researchRunId"] == "run-1"
+
+
+def test_research_is_spent_by_a_finished_run_but_not_by_a_stopped_one(research_home):
+ _create()
+ assert research_db.research_spent("thread-1") is True
+
+ _cancel_run()
+ # The claim is still held (it is what lets the run be re-pointed), but the composer must
+ # offer research again after a stop, so this is what /active reports as hasRun.
+ assert research_db.has_thread_claim("thread-1") is True
+ assert research_db.research_spent("thread-1") is False
+
+ reused = _rebind(_new_user_message())
+ assert reused is not None
+ assert research_db.research_spent("thread-1") is True
+
+
+def test_research_stays_spent_after_a_completed_run(research_home):
+ _create()
+ plan = research_db.set_plan("run-1", _plan())
+ research_db.approve("run-1", plan["planRevision"], plan["planHash"])
+ research_db.claim_next("worker-1")
+ research_db.finish("run-1", "worker-1", "completed")
+ assert research_db.research_spent("thread-1") is True
+
+
+def test_the_new_question_does_not_inherit_the_stopped_one_s_reasoning(research_home):
+ """get_reasoning_text joins every reasoning event at the run's current attempt.
+
+ The run row is reused, so without a new attempt the report written for the new question
+ opens with the thinking the user stopped.
+ """
+ _create()
+ research_db.append_event("run-1", "reasoning.updated", {"reasoningDelta": "about dog breeds"})
+ _cancel_run()
+
+ assert _rebind(_new_user_message()) is not None
+ research_db.append_event("run-1", "reasoning.updated", {"reasoningDelta": "about the AI Act"})
+
+ assert research_db.get_reasoning_text("run-1") == "about the AI Act"
+ # The stopped question's activity is still there to read, under its own attempt.
+ kept = [
+ event for event in research_db.list_events("run-1") if event["type"] == "reasoning.updated"
+ ]
+ assert len(kept) == 2
+ assert kept[0]["data"]["attempt"] != kept[1]["data"]["attempt"]
+
+
+def test_the_new_question_gets_its_own_retry_budget(research_home):
+ """Retries belong to the question, not to the run row the thread reuses forever."""
+ _create()
+ for _ in range(3):
+ _cancel_run()
+ research_db.retry("run-1")
+ _cancel_run()
+ with pytest.raises(research_db.ResearchConflictError):
+ research_db.retry("run-1")
+
+ assert _rebind(_new_user_message()) is not None
+ _cancel_run()
+ assert research_db.retry("run-1") == "planning"
+
+
+def test_cancel_route_sync_cannot_cross_a_rebind(research_home):
+ from routes.research_runs import _sync_assistant
+
+ _create()
+ _cancel_run()
+ stopped = research_db.get_run("run-1")
+ assert stopped is not None and stopped["status"] == "cancelled"
+
+ studio_db.upsert_chat_message(
+ {
+ "id": "assistant-2",
+ "threadId": "thread-1",
+ "parentId": "user-2",
+ "role": "assistant",
+ "content": [],
+ "createdAt": 21,
+ }
+ )
+ assert _rebind(_new_user_message(), assistant_message_id = "assistant-2") is not None
+
+ # A cancel request can hold this snapshot while another tab starts the next question.
+ _sync_assistant(stopped)
+
+ current = research_db.get_run("run-1")
+ reply = studio_db.get_chat_message("thread-1", "assistant-2")
+ assert current is not None and current["status"] == "planning"
+ assert current["retryCount"] == 1
+ assert reply["metadata"]["researchStatus"] == "planning"
+ assert reply["metadata"]["researchPlanRevision"] == current["planRevision"]
+
+
+def test_a_stopped_worker_does_not_stamp_cancelled_on_the_next_question(research_home, monkeypatch):
+ """The worker finishes a stop, then writes its reply. The user can ask in between.
+
+ Both replies are resolved by the same reused run id, so without the attempt guard the new
+ question's placeholder is written "Research cancelled." and stays that way.
+ """
+ from core import research_runs as worker
+
+ _create()
+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))
+ research_db.request_cancel("run-1")
+ claimed = research_db.claim_next(supervisor.worker_id)
+
+ async def cancelled_plan(run):
+ raise worker.RunCancelled()
+
+ # The window: the run reaches "cancelled", the user asks the next question, and only then
+ # does the worker get round to writing its reply.
+ real_get_run = research_db.get_run
+
+ def racing_get_run(run_id, *args, **kwargs):
+ if research_db.get_run.calls == 0:
+ research_db.get_run.calls += 1
+ # No placeholder written by hand: rebind_cancelled creates and binds it, exactly
+ # as the endpoint does for the next armed question.
+ research_db.rebind_cancelled(
+ thread_id = "thread-1",
+ user_message_id = _new_user_message(),
+ assistant_message_id = "assistant-2",
+ config = dict(real_get_run("run-1")["config"]),
+ )
+ return real_get_run(run_id, *args, **kwargs)
+
+ racing_get_run.calls = 0
+ monkeypatch.setattr(supervisor, "_plan", cancelled_plan)
+ monkeypatch.setattr(research_db, "get_run", racing_get_run)
+ research_db.get_run.calls = 0
+ asyncio.run(supervisor._process(claimed))
+
+ # real_get_run, not the patched name: undoing the patch here would also undo the fixture's
+ # UNSLOTH_STUDIO_HOME and read a different database.
+ rebound = real_get_run("run-1")
+ assert racing_get_run.calls == 1
+ assert rebound["status"] == "planning"
+ assert rebound["assistantMessageId"] == "assistant-2"
+ new_reply = studio_db.get_chat_message("thread-1", "assistant-2")
+ assert (new_reply["metadata"] or {}).get("researchStatus") != "cancelled"
+ assert "Research cancelled." not in json.dumps(new_reply["content"])
+
+
+def test_terminal_write_cannot_cross_a_rebind_after_the_worker_guard(research_home, monkeypatch):
+ from core import research_runs as worker
+
+ _create()
+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))
+ research_db.request_cancel("run-1")
+ claimed = research_db.claim_next(supervisor.worker_id)
+ assert claimed is not None
+
+ async def cancelled_plan(run):
+ raise worker.RunCancelled()
+
+ original_update = worker._update_assistant
+ rebound = False
+
+ def rebind_after_guard(*args, **kwargs):
+ nonlocal rebound
+ if not rebound:
+ rebound = True
+ studio_db.upsert_chat_message(
+ {
+ "id": "assistant-2",
+ "threadId": "thread-1",
+ "parentId": "user-2",
+ "role": "assistant",
+ "content": [],
+ "createdAt": 21,
+ }
+ )
+ assert _rebind(_new_user_message(), assistant_message_id = "assistant-2") is not None
+ return original_update(*args, **kwargs)
+
+ monkeypatch.setattr(supervisor, "_plan", cancelled_plan)
+ monkeypatch.setattr(worker, "_update_assistant", rebind_after_guard)
+ asyncio.run(supervisor._process(claimed))
+
+ current = research_db.get_run("run-1")
+ reply = studio_db.get_chat_message("thread-1", "assistant-2")
+ assert current is not None and current["status"] == "planning"
+ assert current["retryCount"] == 1
+ assert (reply["metadata"] or {}).get("researchStatus") != "cancelled"
+ assert "Research cancelled." not in json.dumps(reply["content"])
+
+
+def test_terminal_fallback_cannot_cross_a_no_placeholder_rebind(research_home, monkeypatch):
+ from core import research_runs as worker
+
+ _create(assistant_message_id = None)
+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))
+ research_db.request_cancel("run-1")
+ claimed = research_db.claim_next(supervisor.worker_id)
+ assert claimed is not None
+
+ async def cancelled_plan(run):
+ raise worker.RunCancelled()
+
+ original_update = worker._update_assistant
+ rebound = False
+
+ def rebind_after_guard(*args, **kwargs):
+ nonlocal rebound
+ if not rebound:
+ rebound = True
+ assert _rebind(_new_user_message(), assistant_message_id = None) is not None
+ return original_update(*args, **kwargs)
+
+ monkeypatch.setattr(supervisor, "_plan", cancelled_plan)
+ monkeypatch.setattr(worker, "_update_assistant", rebind_after_guard)
+ asyncio.run(supervisor._process(claimed))
+
+ current = research_db.get_run("run-1")
+ assert current is not None and current["status"] == "planning"
+ assert current["retryCount"] == 1
+ assert current["assistantMessageId"] is None
+ assert studio_db.get_chat_message("thread-1", "research-run-1") is None
+
+
+def test_terminal_write_cannot_cross_a_retry_after_the_worker_guard(research_home, monkeypatch):
+ from core import research_runs as worker
+
+ _create()
+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))
+ research_db.request_cancel("run-1")
+ claimed = research_db.claim_next(supervisor.worker_id)
+ assert claimed is not None
+
+ async def cancelled_plan(run):
+ raise worker.RunCancelled()
+
+ original_update = worker._update_assistant
+ retried = False
+
+ def retry_after_guard(*args, **kwargs):
+ nonlocal retried
+ if not retried:
+ retried = True
+ assert research_db.retry("run-1") == "planning"
+ return original_update(*args, **kwargs)
+
+ monkeypatch.setattr(supervisor, "_plan", cancelled_plan)
+ monkeypatch.setattr(worker, "_update_assistant", retry_after_guard)
+ asyncio.run(supervisor._process(claimed))
+
+ current = research_db.get_run("run-1")
+ reply = studio_db.get_chat_message("thread-1", "assistant-1")
+ assert current is not None and current["status"] == "planning"
+ assert current["retryCount"] == 1
+ assert (reply["metadata"] or {}).get("researchStatus") != "cancelled"
+ assert "Research cancelled." not in json.dumps(reply["content"])
+
+
+def _attachment_only_message(message_id = "user-img", created_at = 40):
+ """What the composer sends for an image-only turn: attachments, no text."""
+ studio_db.upsert_chat_message(
+ {
+ "id": message_id,
+ "threadId": "thread-1",
+ "role": "user",
+ "content": [],
+ "attachments": [{"id": "att-1", "type": "image", "name": "chart.png", "content": []}],
+ "createdAt": created_at,
+ }
+ )
+ return message_id
+
+
+def _create_via_route(user_message_id, question = None):
+ from fastapi import Request
+ from routes.research_runs import CreateResearchRun, create_research_run
+
+ payload = CreateResearchRun(
+ threadId = "thread-1",
+ userMessageId = user_message_id,
+ assistantMessageId = None,
+ inferenceRequest = {"model": "local-model"},
+ **({"question": question} if question is not None else {}),
+ )
+ request = Request(
+ {
+ "type": "http",
+ "headers": [],
+ "app": SimpleNamespace(state = SimpleNamespace(research_supervisor = None)),
+ }
+ )
+ return create_research_run(payload, request, current_subject = "alice")
+
+
+def test_an_attachment_only_turn_researches_the_handed_off_question(research_home):
+ """A multimodal model reads the image and hands off a question; the message has no text.
+
+ The worker researches config.question, so refusing on the message's own text ends an
+ otherwise complete handoff in "Deep research could not start".
+ """
+ message_id = _attachment_only_message()
+
+ run = _create_via_route(message_id, question = "What does this revenue chart show for Q3?")
+
+ assert run["status"] == "planning"
+ assert run["config"]["question"] == "What does this revenue chart show for Q3?"
+
+
+def test_an_attachment_only_turn_with_no_question_is_still_refused(research_home):
+ """Nothing to research: neither the message nor the handoff carries a question."""
+ import fastapi
+
+ message_id = _attachment_only_message("user-img-2", 41)
+
+ with pytest.raises(fastapi.HTTPException) as excinfo:
+ _create_via_route(message_id)
+ assert excinfo.value.status_code == 400
+ assert "non-empty text" in excinfo.value.detail
diff --git a/studio/backend/tests/test_run_tools_locally_discriminator.py b/studio/backend/tests/test_run_tools_locally_discriminator.py
index 2c37a26935b..52587f3a948 100644
--- a/studio/backend/tests/test_run_tools_locally_discriminator.py
+++ b/studio/backend/tests/test_run_tools_locally_discriminator.py
@@ -192,8 +192,28 @@ def test_the_field_defaults_to_absent_not_false():
assert "run_tools_locally" not in dumped
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_armed_research_is_never_a_purely_hosted_selection(provider_type):
+ """deep_research is Unsloth's own and rides past enabled_tools, so it is not in the names.
+
+ Read by name alone, an armed turn with only hosted pills lit looks like a hosted request,
+ the turn proxies through, the tool is never offered and arming Deep Research does nothing.
+ """
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(enabled_tools = ["web_search"], deep_research_armed = True)
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is False
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_an_unarmed_hosted_selection_is_unchanged(provider_type):
+ from routes.inference import _selects_only_provider_hosted_tools
+ payload = _payload(enabled_tools = ["web_search"], deep_research_armed = False)
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is True
+
+
def test_local_gguf_search_only_is_not_a_hosted_request():
- """#9730: a loaded GGUF has no provider_type; web_search is Studio's tool."""
+ """#9730: a loaded GGUF has no provider_type; web_search is Unsloth's tool."""
from models.inference import ChatCompletionRequest
from routes.inference import _select_request_tools, _selects_only_provider_hosted_tools
diff --git a/studio/frontend/src/components/assistant-ui/thread-research-presence.ts b/studio/frontend/src/components/assistant-ui/thread-research-presence.ts
index 32a34d73e85..ec95b0b66cb 100644
--- a/studio/frontend/src/components/assistant-ui/thread-research-presence.ts
+++ b/studio/frontend/src/components/assistant-ui/thread-research-presence.ts
@@ -30,26 +30,70 @@
export type ResearchPresenceMessage = { metadata?: unknown };
const presenceByMessages = new WeakMap<object, boolean>();
+const presenceByLiveRun = new WeakMap<object, Map<string, boolean>>();
-/** Whether any message carries `metadata.custom.researchRunId` as a string. */
+/**
+ * Whether a message holds the thread's spent research: a run that finished.
+ *
+ * A run still going keeps the toggle lit rather than taking it away, and a stopped run is
+ * re-pointed at the next question rather than refused, so neither counts here -- otherwise the
+ * composer hides deep research for a thread that is researching or would still research.
+ * A run id with no status at all is older metadata and counts, to stay on the safe side.
+ */
export function messageHasResearchRunId(
message: ResearchPresenceMessage,
+ liveRunId?: string,
): boolean {
const custom = (
- message.metadata as { custom?: { researchRunId?: unknown } } | undefined
+ message.metadata as
+ | {
+ custom?: {
+ researchRunId?: unknown;
+ researchStatus?: unknown;
+ researchRun?: { status?: unknown };
+ };
+ }
+ | undefined
)?.custom;
- return typeof custom?.researchRunId === "string";
+ if (typeof custom?.researchRunId !== "string") {
+ return false;
+ }
+ if (custom.researchRunId === liveRunId) {
+ return false;
+ }
+ const status = custom.researchRun?.status ?? custom.researchStatus;
+ if (typeof status !== "string") {
+ return true;
+ }
+ return status === "completed" || status === "failed";
}
/** @param messages the thread's message array, used as the revision key. */
export function threadHasResearchMessage(
messages: readonly ResearchPresenceMessage[],
+ liveRunId?: string,
): boolean {
+ if (liveRunId) {
+ const knownByRun = presenceByLiveRun.get(messages);
+ const known = knownByRun?.get(liveRunId);
+ if (known !== undefined) {
+ return known;
+ }
+ const answer = messages.some((message) =>
+ messageHasResearchRunId(message, liveRunId),
+ );
+ const next = knownByRun ?? new Map<string, boolean>();
+ next.set(liveRunId, answer);
+ if (!knownByRun) {
+ presenceByLiveRun.set(messages, next);
+ }
+ return answer;
+ }
const known = presenceByMessages.get(messages);
if (known !== undefined) {
return known;
}
- const answer = messages.some(messageHasResearchRunId);
+ const answer = messages.some((message) => messageHasResearchRunId(message));
presenceByMessages.set(messages, answer);
return answer;
}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index d41dd96d92f..2b61188fbe7 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -128,6 +128,7 @@ import {
ingestResearchUpdate,
useResearchRunStore,
} from "@/features/chat/stores/research-run-store";
+import { researchReplyOwnsRun } from "@/features/chat/utils/research-run-binding";
import {
parseExternalModelId,
providerModelSupportsStudioTools,
@@ -354,6 +355,8 @@ type PromptQueueTarget = {
usesThreadDocuments: boolean;
usesLocalModel: boolean;
usesDeepResearch: boolean;
+ /** Whether a research run now holds this queue's thread. */
+ researchStarted: () => boolean;
temporary: boolean;
consumeDeepResearch: () => void;
};
@@ -502,7 +505,13 @@ function consumePromptQueueDeepResearch(
run: PromptQueueRun,
item: PromptQueueItem,
) {
- if (run.deepResearchConsumed || !item.target.usesDeepResearch) {
+ // The model decides whether an armed prompt becomes research, so the queue's one research
+ // is spent only once a run actually started, not on the first prompt that was merely armed.
+ if (
+ run.deepResearchConsumed ||
+ !item.target.usesDeepResearch ||
+ !item.target.researchStarted()
+ ) {
return;
}
run.deepResearchConsumed = true;
@@ -2269,6 +2278,9 @@ const Composer: FC<{
const researchThreadClaimed = useResearchRunStore((state) =>
researchThreadId ? Boolean(state.claimedThreadIds[researchThreadId]) : false,
);
+ const liveResearchRunId = useResearchRunStore((state) =>
+ researchThreadId ? state.latestRunByThreadId[researchThreadId] : undefined,
+ );
// Derive in the selector, as useThreadResearchActive does: a bare run selector re-renders the
// composer on every streamed research delta.
const isResearchActive = useResearchRunStore((state) => {
@@ -2281,7 +2293,7 @@ const Composer: FC<{
);
});
const hasResearchMessage = useAuiState(({ thread }) =>
- threadHasResearchMessage(thread.messages),
+ threadHasResearchMessage(thread.messages, liveResearchRunId),
);
const researchUsed = researchThreadClaimed || hasResearchMessage;
const effectiveDeepResearchEnabled = deepResearchEnabled && !researchUsed;
@@ -3645,6 +3657,10 @@ const Composer: FC<{
usesLocalModel:
parseExternalModelId(runSettingsAtQueueStart.params.checkpoint) === null,
usesDeepResearch: runSettingsAtQueueStart.deepResearchEnabled,
+ researchStarted: () => {
+ const claimed = useResearchRunStore.getState().claimedThreadIds;
+ return getQueueThreadIds().some((id) => Boolean(claimed[id]));
+ },
temporary: incognitoAtQueueStart,
consumeDeepResearch: () => {
runSettingsAtQueueStart.deepResearchEnabled = false;
@@ -6794,9 +6810,6 @@ const ContinueMessageBarForLastMessage: FC = () => {
const activeModel = s.models.find((m) => m.id === s.params.checkpoint);
return Boolean(activeModel?.isAudio && !activeModel.hasAudioInput);
});
- // Research armed after the cut owns no run yet, so the gates above stay clear.
- const deepResearchArmed = useChatRuntimeStore((s) => s.deepResearchEnabled);
-
// Cancelled comes through status (the adapter yields nothing after an abort); the
// other two are stamped on metadata so they survive a reload.
const stamped = readIncompleteInfo(metadata);
@@ -6816,7 +6829,6 @@ const ContinueMessageBarForLastMessage: FC = () => {
modeAllowsContinuation({
fromAudioInput,
audioOutputModel,
- deepResearchArmed,
}) &&
Boolean(partial.trim());
@@ -7252,6 +7264,8 @@ function useActionBarFocusReveal() {
return { ref: rootRef, onFocus: handleFocus, onBlur: handleBlur };
}
+const ResearchMessageRunIdContext = createContext<string | null>(null);
+
/**
* AssistantMessage handles the display and inline-editing of AI responses.
*
@@ -7264,16 +7278,19 @@ const AssistantMessage: FC = () => {
const focusReveal = useActionBarFocusReveal();
const messageId = useAuiState(({ message }) => message.id);
const messageContent = useAuiState(({ message }) => message.content);
- const researchRunId = useAuiState(({ message }) => {
- const custom = (
- message.metadata as
- | { custom?: { researchRunId?: unknown } }
- | undefined
- )?.custom;
- return typeof custom?.researchRunId === "string"
- ? custom.researchRunId
+ const metadataResearchRunId = useAuiState(({ message }) =>
+ getResearchRunId(message.metadata),
+ );
+ const boundResearchAssistantMessageId = useResearchRunStore((state) =>
+ metadataResearchRunId
+ ? state.sessions[metadataResearchRunId]?.run?.assistantMessageId
+ : undefined,
+ );
+ const researchRunId =
+ metadataResearchRunId &&
+ researchReplyOwnsRun(boundResearchAssistantMessageId, messageId)
+ ? metadataResearchRunId
: null;
- });
// Persisted on the assistant turn that compacted, so the notice survives a reload.
const contextTruncation = useAuiState(({ message }) => {
const custom = (
@@ -7365,7 +7382,8 @@ const AssistantMessage: FC = () => {
};
return (
- <MessagePrimitive.Root
+ <ResearchMessageRunIdContext.Provider value={researchRunId}>
+ <MessagePrimitive.Root
className="group/assistant-message aui-assistant-message-root relative mx-auto min-w-0 w-full max-w-(--thread-content-max-width) pt-0.5 pb-4 text-ui-15p5 [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em]"
data-role="assistant"
// The message itself is the tab stop that lets the reveal below fire. Without it, a reply
@@ -7479,7 +7497,8 @@ const AssistantMessage: FC = () => {
tabIndex={0}
aria-label="Message actions"
/>
- </MessagePrimitive.Root>
+ </MessagePrimitive.Root>
+ </ResearchMessageRunIdContext.Provider>
);
};
@@ -7676,7 +7695,7 @@ const getResearchRunId = (metadata: unknown): string | null => {
};
const useResearchMessageRunId = () => {
- return useAuiState(({ message }) => getResearchRunId(message.metadata));
+ return useContext(ResearchMessageRunIdContext);
};
// Boolean(), not `!== null`: getResearchRunId returns whatever string it found, and an empty one
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index b3d77d2886e..7b149e26216 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -61,6 +61,10 @@ import {
releasePreStreamRunReservation,
} from "../utils/pre-stream-run-reservation";
import { readThreadCreationClaim } from "../utils/chat-thread-creation-claim";
+import {
+ newDeepResearchHandoff,
+ readDeepResearchToolEvent,
+} from "../utils/deep-research-handoff";
import {
consumeQueuedChatRunSettings,
shouldPersistResolvedQueuedModel,
@@ -1851,6 +1855,7 @@ export async function buildLocalTokenCountExtras(
ragTopK,
autoHealToolCalls,
bypassPermissions,
+ deepResearchEnabled,
} = useChatRuntimeStore.getState();
if (!supportsTools) return {};
@@ -1864,7 +1869,8 @@ export async function buildLocalTokenCountExtras(
!codeToolsEnabled &&
!artifactsEnabled &&
!mcpEnabledForChat &&
- !ragOn
+ !ragOn &&
+ !deepResearchEnabled
) {
// Explicit false, not an omitted field: the server defaults tools on for a
// request that never mentions them, so every pill being off has to say so.
@@ -1890,6 +1896,8 @@ export async function buildLocalTokenCountExtras(
...(artifactsEnabled ? ["render_html"] : []),
],
mcp_enabled: mcpEnabledForChat,
+ // Armed research puts the deep_research schema in the prompt, so the count carries it.
+ ...(deepResearchEnabled ? { deep_research_armed: true } : {}),
// the ids name the attached documents in the nudge server-side; no retrieval runs for a count.
...(ragOn
? {
@@ -3985,15 +3993,16 @@ export function createOpenAIStreamAdapter(
runtime = useChatRuntimeStore.getState();
}
}
- if (
- runtime.deepResearchEnabled &&
- !options.pairId &&
- (options.modelType === undefined || options.modelType === "base")
+ // Started only when the model hands this turn off, never on the toggle alone: arming
+ // research offers it the tool, and it decides whether the message wants researching.
+ const startDeepResearch = async function* (
+ researchQuestion: string,
+ transitionSignal: AbortSignal = abortSignal,
) {
if (runtime.modelLoading) {
toast.info("Waiting for model to finish loading…");
try {
- await waitForModelReady(abortSignal);
+ await waitForModelReady(transitionSignal);
} catch (error) {
throw error;
}
@@ -4003,7 +4012,7 @@ export function createOpenAIStreamAdapter(
ReturnType<typeof resolveQueuedEmptyLocalModel>
>;
try {
- resolution = await resolveQueuedEmptyLocalModel(abortSignal);
+ resolution = await resolveQueuedEmptyLocalModel(transitionSignal);
} catch (error) {
throw error;
}
@@ -4025,58 +4034,52 @@ export function createOpenAIStreamAdapter(
throw new Error("Load a model first.");
}
}
- const liveRuntime = useChatRuntimeStore.getState();
- runtime = queuedRunSettings
- ? queuedRunSettings.params.checkpoint
- ? { ...liveRuntime, ...queuedRunSettings }
+ // The turn's own settings, not the store's now. This generator runs AFTER the
+ // model's stream, and the model selector stays usable while a turn is streaming: a
+ // live read researched the question model A handed off with whichever model B had
+ // since been picked, or failed outright when B runs no Studio tools. The one thing
+ // that legitimately happened after the send is the empty-model resolution above.
+ const sendTimeRuntime = runtime;
+ const withResolvedModel = <T extends typeof sendTimeRuntime>(base: T): T =>
+ queuedEmptyModelRuntime === null
+ ? base
: {
- ...liveRuntime,
- ...queuedRunSettings,
+ ...base,
params: {
- ...queuedRunSettings.params,
- checkpoint:
- queuedEmptyModelRuntime?.checkpoint ??
- liveRuntime.params.checkpoint,
+ ...base.params,
+ checkpoint: queuedEmptyModelRuntime.checkpoint,
},
- activeGgufVariant:
- queuedEmptyModelRuntime !== null
- ? queuedEmptyModelRuntime.activeGgufVariant
- : liveRuntime.activeGgufVariant,
- supportsTools:
- queuedEmptyModelRuntime?.supportsTools ??
- liveRuntime.supportsTools,
- supportsReasoning:
- queuedEmptyModelRuntime?.supportsReasoning ??
- liveRuntime.supportsReasoning,
- reasoningAlwaysOn:
- queuedEmptyModelRuntime?.reasoningAlwaysOn ??
- liveRuntime.reasoningAlwaysOn,
- reasoningStyle:
- queuedEmptyModelRuntime?.reasoningStyle ??
- liveRuntime.reasoningStyle,
- supportsReasoningOff:
- queuedEmptyModelRuntime?.supportsReasoningOff ??
- liveRuntime.supportsReasoningOff,
- reasoningEffortLevels:
- queuedEmptyModelRuntime?.reasoningEffortLevels ??
- liveRuntime.reasoningEffortLevels,
+ activeGgufVariant: queuedEmptyModelRuntime.activeGgufVariant,
+ supportsTools: queuedEmptyModelRuntime.supportsTools,
+ supportsReasoning: queuedEmptyModelRuntime.supportsReasoning,
+ reasoningAlwaysOn: queuedEmptyModelRuntime.reasoningAlwaysOn,
+ reasoningStyle: queuedEmptyModelRuntime.reasoningStyle,
+ supportsReasoningOff: queuedEmptyModelRuntime.supportsReasoningOff,
+ reasoningEffortLevels: queuedEmptyModelRuntime.reasoningEffortLevels,
supportsPreserveThinking:
- queuedEmptyModelRuntime?.supportsPreserveThinking ??
- liveRuntime.supportsPreserveThinking,
- preserveThinking:
- queuedEmptyModelRuntime?.preserveThinking ??
- liveRuntime.preserveThinking,
- ggufContextLength:
- queuedEmptyModelRuntime !== null
- ? queuedEmptyModelRuntime.ggufContextLength
- : liveRuntime.ggufContextLength,
+ queuedEmptyModelRuntime.supportsPreserveThinking,
+ preserveThinking: queuedEmptyModelRuntime.preserveThinking,
+ ggufContextLength: queuedEmptyModelRuntime.ggufContextLength,
models: mergeQueuedModelCapabilities(
- liveRuntime.models,
- queuedEmptyModelRuntime?.checkpoint ?? "",
- queuedEmptyModelRuntime?.modelCapabilities ?? null,
+ base.models,
+ queuedEmptyModelRuntime.checkpoint,
+ queuedEmptyModelRuntime.modelCapabilities,
),
- }
- : liveRuntime;
+ };
+ runtime = queuedRunSettings
+ ? queuedRunSettings.params.checkpoint
+ ? { ...sendTimeRuntime, ...queuedRunSettings }
+ : withResolvedModel({
+ ...sendTimeRuntime,
+ ...queuedRunSettings,
+ // The queued snapshot carries no model of its own; without a resolution
+ // this turn's own is the answer.
+ params: {
+ ...queuedRunSettings.params,
+ checkpoint: sendTimeRuntime.params.checkpoint,
+ },
+ })
+ : withResolvedModel(sendTimeRuntime);
if (!resolvedThreadId) throw new Error("Research requires a saved chat.");
if (!unstable_assistantMessageId) {
throw new Error(
@@ -4147,6 +4150,7 @@ export function createOpenAIStreamAdapter(
params.systemVariables,
readThreadRecord,
);
+ if (transitionSignal.aborted) return;
const ragScope =
runtime.ragEnabled || projectRagEnabled
? runtime.ragEnabled && runtime.ragSource.type === "kb"
@@ -4219,6 +4223,9 @@ export function createOpenAIStreamAdapter(
userMessageId: userMessage.id,
assistantMessageId: unstable_assistantMessageId,
inferenceRequest,
+ // Omitted when empty rather than sent as "": CreateResearchRun forbids unknown
+ // fields, so an unconditional send 422s against a backend that predates it.
+ ...(researchQuestion ? { question: researchQuestion } : {}),
...(researchInstructions ? { instructions: researchInstructions } : {}),
...(ragScope ? { ragScope } : {}),
budgets: {
@@ -4240,13 +4247,8 @@ export function createOpenAIStreamAdapter(
createdRun,
detachResearchFollow,
);
- if (
- !queuedRunSettings ||
- resolvedThreadId ===
- useChatRuntimeStore.getState().activeThreadId
- ) {
- runtime.setDeepResearchEnabled(false);
- }
+ // The toggle stays on through the run: it is what the user turned on, and it is what
+ // is happening. The composer takes it away only once the chat's research is spent.
if (abortSignal.aborted) {
const detached = Boolean(
(abortSignal.reason as { detach?: boolean } | undefined)?.detach,
@@ -4296,8 +4298,13 @@ export function createOpenAIStreamAdapter(
runtime.clearThreadServerCancel(threadKey, researchServerCancel);
runtime.setThreadRunning(threadKey, false, { owner: researchServerCancel });
}
- return;
- }
+ };
+ const deepResearchHandoff = newDeepResearchHandoff();
+ const continuation = readContinuationRequest(runConfig);
+ let deepResearchArmed =
+ runtime.deepResearchEnabled &&
+ !options.pairId &&
+ (options.modelType === undefined || options.modelType === "base");
const toolConfirmationIdsByBackendId = new Map<string, string>();
// Local tool ids ("call_0") repeat across turns, panes and conversations, so scope by pane
// AND thread. unstable_threadId alone, no activeThreadId fallback: the reader has only
@@ -4464,6 +4471,18 @@ export function createOpenAIStreamAdapter(
ragAutoInject,
ragAutoInjectMinScore,
} = runtime;
+ if (
+ deepResearchArmed &&
+ !supportsTools &&
+ !isExternalModelId(params.checkpoint)
+ ) {
+ deepResearchArmed = false;
+ if (!queuedRunSettings) {
+ runtime.setDeepResearchEnabled(false);
+ }
+ runtime = { ...runtime, deepResearchEnabled: false };
+ toast.info("Deep Research needs a model that supports tools");
+ }
// Project sources auto-scope: a chat inside a project retrieves from the
// project's indexed sources even when the Docs pill is off. The probe is
// cached, so this is one round trip per project every ~30s at most.
@@ -4664,7 +4683,6 @@ export function createOpenAIStreamAdapter(
// The run's messages stop at the user turn (this is a sibling branch), so the
// partial is appended here for the backend to resume.
- const continuation = readContinuationRequest(runConfig);
if (continuation) {
outboundMessages.push({
role: "assistant",
@@ -5580,7 +5598,12 @@ export function createOpenAIStreamAdapter(
studioLocalCodeTools.length > 0 ||
mcpEnabledForChat ||
ragEnabled ||
- projectRagEnabled)
+ projectRagEnabled ||
+ // Armed research needs Studio's loop for the same reason the local body
+ // does: deep_research is appended past every tool filter, but only for a
+ // request that asked for the loop at all. Without it the turn proxies
+ // through, the model is never offered the tool, and arming does nothing.
+ deepResearchArmed)
? {
enable_tools: true,
enabled_tools: [
@@ -5682,6 +5705,9 @@ export function createOpenAIStreamAdapter(
// server's tools-on default, which would bill provider
// server tools.
{ enable_tools: false }),
+ // Also on this body, not just the local one: a provider whose models run Studio
+ // tools can hand off too, and omitting it here makes arming research a no-op.
+ ...(deepResearchArmed ? { deep_research_armed: true } : {}),
provider_id: externalProvider.id,
provider_type: externalBackendProviderType,
external_model: externalSelection.modelId,
@@ -5804,13 +5830,15 @@ export function createOpenAIStreamAdapter(
? {}
: { confirm_tool_calls: permissionMode === "ask" }),
bypass_permissions: bypassPermissions,
+ ...(deepResearchArmed ? { deep_research_armed: true } : {}),
...(supportsTools &&
(toolsEnabled ||
codeToolsEnabled ||
renderHtmlToolEnabledForThisTurn ||
mcpEnabledForChat ||
ragEnabled ||
- projectRagEnabled)
+ projectRagEnabled ||
+ deepResearchArmed)
? {
enable_tools: true,
enabled_tools: [
@@ -5990,6 +6018,17 @@ export function createOpenAIStreamAdapter(
chunk as unknown as { _toolEvent?: Record<string, unknown> }
)._toolEvent;
if (toolEvent !== undefined) {
+ // Deep Research is an ordinary tool to every loop that runs it, so the handoff
+ // is read off the events they all publish rather than a bespoke frame. An
+ // ungated pair is not rendered: the research card is the reply, a tool pill
+ // would just precede it saying the same thing.
+ if (
+ toolEvent.tool_name === "deep_research" &&
+ readDeepResearchToolEvent(deepResearchHandoff, toolEvent)
+ ) {
+ if (deepResearchHandoff.question !== null) break;
+ continue;
+ }
// Persist container_id onto the thread (OpenAI / Anthropic).
if (toolEvent.type === "container_ready") {
const newContainerId = toolEvent.container_id as
@@ -6840,9 +6879,40 @@ export function createOpenAIStreamAdapter(
retriedWithRefreshedKey = true;
continue;
}
+ // The tool ran, so the run it announced is owed whatever the acknowledgement
+ // did next: a small model that stalls on the follow-up sentence, a timeout, a
+ // dropped connection. Its card replaces this reply anyway, so nothing the
+ // failed acknowledgement would have said is lost. Not after Stop.
+ if (deepResearchHandoff.question !== null && !runSignal.aborted) {
+ try {
+ yield* startDeepResearch(deepResearchHandoff.question, runSignal);
+ return;
+ } catch (researchError) {
+ toast.error("Deep research could not start", {
+ description:
+ researchError instanceof Error
+ ? researchError.message
+ : String(researchError),
+ });
+ }
+ }
throw streamError;
}
}
+ // The model asked for Deep Research, so the run takes over from here and its card
+ // replaces this reply. Not after Stop: the user ended the turn before it got there.
+ if (deepResearchHandoff.question !== null && !runSignal.aborted) {
+ try {
+ yield* startDeepResearch(deepResearchHandoff.question, runSignal);
+ } catch (error) {
+ // The reply the model already wrote stays; the user can send again.
+ toast.error("Deep research could not start", {
+ description:
+ error instanceof Error ? error.message : String(error),
+ });
+ }
+ return;
+ }
// Strip a trailing ${...} template-literal fragment from external
// streams (mistral magistral occasionally emits one at the end of an
// otherwise complete answer).
diff --git a/studio/frontend/src/features/chat/components/research-message.tsx b/studio/frontend/src/features/chat/components/research-message.tsx
index 7e9eb9943c5..9e1492fbd5e 100644
--- a/studio/frontend/src/features/chat/components/research-message.tsx
+++ b/studio/frontend/src/features/chat/components/research-message.tsx
@@ -22,9 +22,10 @@ import {
useResearchRunStore,
} from "../stores/research-run-store";
import type { ResearchMessageMetadata } from "../types/research";
+import { researchReplyOwnsRun } from "../utils/research-run-binding";
import { researchStatusLabel } from "./research-activity-panel";
-export function ResearchMessage(): ReactElement {
+export function ResearchMessage(): ReactElement | null {
const metadata = useAuiState(
({ message }) =>
(message.metadata as { custom?: ResearchMessageMetadata } | undefined)
@@ -36,13 +37,18 @@ export function ResearchMessage(): ReactElement {
.map((part) => part.text)
.join("\n"),
);
+ const messageId = useAuiState(({ message }) => message.id);
const runId = metadata.researchRunId ?? metadata.researchRun?.id ?? "";
const session = useResearchRunStore((state) => state.sessions[runId]);
const openPanel = useResearchRunStore((state) => state.openPanel);
const initialRun = metadata.researchRun;
+ const ownsRun = researchReplyOwnsRun(
+ session?.run?.assistantMessageId,
+ messageId,
+ );
useEffect(() => {
- if (!runId) {
+ if (!runId || !ownsRun) {
return;
}
if (initialRun) {
@@ -51,9 +57,9 @@ export function ResearchMessage(): ReactElement {
if (!session?.following) {
ensureResearchRunFollowed(runId, initialRun);
}
- }, [runId, initialRun, session?.following]);
+ }, [runId, initialRun, ownsRun, session?.following]);
- const run = session?.run ?? metadata.researchRun;
+ const run = ownsRun ? (session?.run ?? metadata.researchRun) : undefined;
if (!run) {
if (fallbackText.trim()) {
return (
@@ -63,6 +69,9 @@ export function ResearchMessage(): ReactElement {
/>
);
}
+ if (!ownsRun) {
+ return null;
+ }
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Spinner /> Loading research…
diff --git a/studio/frontend/src/features/chat/stores/research-run-store.ts b/studio/frontend/src/features/chat/stores/research-run-store.ts
index 7ca6dbf050b..440f37941b9 100644
--- a/studio/frontend/src/features/chat/stores/research-run-store.ts
+++ b/studio/frontend/src/features/chat/stores/research-run-store.ts
@@ -134,6 +134,13 @@ function statusActivity(event: ResearchEvent): ResearchActivity | null {
detail: "Previous activity is preserved below.",
state: "complete",
};
+ case "run.rebound":
+ return {
+ ...base,
+ title: "Moved to a new question",
+ detail: "Activity from the stopped question is preserved below.",
+ state: "complete",
+ };
case "run.completed":
return { ...base, title: "Research completed", state: "complete" };
case "run.failed":
@@ -634,11 +641,18 @@ export const useResearchRunStore = create<ResearchRunState>((set) => ({
state.planReviewByRunId[run.id],
run,
);
+ // Claimed means spent: a finished run is the chat's one research. A run still going
+ // keeps the toggle lit (it is what is happening) and a stopped one can be re-pointed,
+ // so neither takes the toggle away.
+ const claimed = shouldBecomeLatest
+ ? run.status === "completed" || run.status === "failed"
+ : Boolean(state.claimedThreadIds[run.threadId]);
return {
sessions: { ...state.sessions, [run.id]: session },
- claimedThreadIds: state.claimedThreadIds[run.threadId]
- ? state.claimedThreadIds
- : { ...state.claimedThreadIds, [run.threadId]: true },
+ claimedThreadIds:
+ state.claimedThreadIds[run.threadId] === claimed
+ ? state.claimedThreadIds
+ : { ...state.claimedThreadIds, [run.threadId]: claimed },
latestRunByThreadId: shouldBecomeLatest
? { ...state.latestRunByThreadId, [run.threadId]: run.id }
: state.latestRunByThreadId,
diff --git a/studio/frontend/src/features/chat/types/research.ts b/studio/frontend/src/features/chat/types/research.ts
index ce0d07f83a6..61f1c5997e7 100644
--- a/studio/frontend/src/features/chat/types/research.ts
+++ b/studio/frontend/src/features/chat/types/research.ts
@@ -106,6 +106,8 @@ export interface CreateResearchRunInput {
budgets?: Partial<ResearchBudgets>;
websitePolicy?: ResearchWebsitePolicy;
instructions?: string;
+ /** The question the model handed off, which is what gets researched. */
+ question?: string;
}
export interface ResearchRun {
@@ -157,6 +159,7 @@ export type ResearchEventType =
| "run.cancelRequested"
| "run.cancelled"
| "run.retried"
+ | "run.rebound"
| "run.completed"
| "run.failed";
diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.ts
index 6584e02c539..7f0913481b6 100644
--- a/studio/frontend/src/features/chat/utils/continuation.ts
+++ b/studio/frontend/src/features/chat/utils/continuation.ts
@@ -230,20 +230,19 @@ export function resumesExactly(providerType: string | undefined): boolean {
/**
* Whether the run this thread would start can resume a partial at all.
*
- * These three answer from scratch before the continuation request is read: audio input
- * re-listens, an audio-output model regenerates the clip, and armed Deep Research
- * replaces the turn with a report. Continue would restart, so it is hidden.
+ * These two answer from scratch before the continuation request is read: audio input
+ * re-listens and an audio-output model regenerates the clip. Continue would restart, so
+ * it is hidden. Armed Deep Research is not here: the model decides whether an armed turn
+ * becomes research, and a turn that did is hidden by its run, not by the toggle.
*/
export function modeAllowsContinuation({
fromAudioInput,
audioOutputModel,
- deepResearchArmed,
}: {
fromAudioInput: boolean;
audioOutputModel: boolean;
- deepResearchArmed: boolean;
}): boolean {
- return !(fromAudioInput || audioOutputModel || deepResearchArmed);
+ return !(fromAudioInput || audioOutputModel);
}
/** Asks for a continuation when the partial cannot be sent as a prefill. */
diff --git a/studio/frontend/src/features/chat/utils/deep-research-handoff.ts b/studio/frontend/src/features/chat/utils/deep-research-handoff.ts
new file mode 100644
index 00000000000..24181ee6014
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/deep-research-handoff.ts
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Reading the model's Deep Research handoff off the tool events every loop publishes.
+ *
+ * `deep_research` is an ordinary tool to the three loops that run it, so there is no bespoke
+ * frame to key on: the question rides on `tool_start` and the result on `tool_end`.
+ */
+
+/** The opening of the backend's `DEEP_RESEARCH_STARTED`, which is what says the call ran. */
+export const DEEP_RESEARCH_STARTED_MARKER = "Deep Research has started";
+
+/** `CreateResearchRun.question`'s max_length; a longer question would 422 the whole handoff. */
+export const DEEP_RESEARCH_QUESTION_MAX_CHARS = 2000;
+
+export type DeepResearchToolEvent = {
+ type?: unknown;
+ tool_call_id?: unknown;
+ arguments?: unknown;
+ result?: unknown;
+ awaiting_confirmation?: unknown;
+};
+
+export type DeepResearchHandoff = {
+ /** The question to research; "" means the user's own message, null means no handoff yet. */
+ question: string | null;
+ pendingCallId: string;
+ pendingQuestion: string;
+ hiddenCallIds: Set<string>;
+};
+
+export function newDeepResearchHandoff(): DeepResearchHandoff {
+ return {
+ question: null,
+ pendingCallId: "",
+ pendingQuestion: "",
+ hiddenCallIds: new Set(),
+ };
+}
+
+/**
+ * Fold one `deep_research` tool event into the handoff.
+ *
+ * @returns whether the adapter should swallow the event instead of drawing a tool card. An
+ * ungated call is hidden on both halves: the research card is the reply, and a tool pill would
+ * just precede it saying the same thing.
+ */
+export function readDeepResearchToolEvent(
+ handoff: DeepResearchHandoff,
+ event: DeepResearchToolEvent,
+): boolean {
+ const callId =
+ typeof event.tool_call_id === "string" ? event.tool_call_id : "";
+ if (event.type === "tool_start") {
+ // The local loop paints a provisional tool_start with empty arguments before the real
+ // one, so only a start carrying a question is remembered, and only the first: a second
+ // call in the same turn is the model repeating itself.
+ const args = event.arguments;
+ const question =
+ args && typeof args === "object"
+ ? String((args as { question?: unknown }).question ?? "").trim()
+ : "";
+ if (handoff.question === null && question) {
+ handoff.pendingCallId = callId;
+ // Clamped, not refused: the endpoint rejects a longer one and the whole handoff would
+ // fail, where a small model padding the question still asked something researchable.
+ handoff.pendingQuestion = Array.from(question)
+ .slice(0, DEEP_RESEARCH_QUESTION_MAX_CHARS)
+ .join("");
+ }
+ // A gated call has to keep its Allow / Deny card: the loop blocks on a verdict, so
+ // hiding the card asks the user nothing and the turn hangs there.
+ if (event.awaiting_confirmation === true) {
+ return false;
+ }
+ handoff.hiddenCallIds.add(callId);
+ return true;
+ }
+ if (event.type !== "tool_end") {
+ return false;
+ }
+ // The result is what says the tool ran. tool_end on its own does not: a denied, skipped,
+ // truncated or budget-exhausted call is closed by the same event, and handing off on one
+ // researches a question the loop refused to pass on -- spending the chat's one run.
+ const result = typeof event.result === "string" ? event.result : "";
+ if (
+ result.startsWith(DEEP_RESEARCH_STARTED_MARKER) &&
+ handoff.question === null
+ ) {
+ // The run starts on the question the model passed; if that could not be read, on the
+ // user's own message, which is what research did before the model had a say.
+ handoff.question =
+ callId === handoff.pendingCallId ? handoff.pendingQuestion : "";
+ }
+ // Close whatever this pair opened: a hidden start gets a hidden end, and a card the user
+ // was asked to approve gets closed by the event that ends it.
+ return handoff.hiddenCallIds.has(callId);
+}
diff --git a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
index bda4a3b60da..3d0b097699a 100644
--- a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
+++ b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
@@ -207,10 +207,6 @@ export async function refreshContextUsage(
);
if (activeModel?.isAudio && !activeModel?.hasAudioInput) return;
- // Deep Research routes the turn to a server-side research run whose reply carries no usage, so
- // a total counted here would describe a request that is never made and nothing would correct it.
- if (store.deepResearchEnabled) return;
-
// 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 less
diff --git a/studio/frontend/src/features/chat/utils/research-run-binding.ts b/studio/frontend/src/features/chat/utils/research-run-binding.ts
new file mode 100644
index 00000000000..c7d6e2b028a
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/research-run-binding.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Whether a reply still owns the research run its metadata names.
+ *
+ * A thread holds one run for its lifetime, so a stopped run is re-pointed at the next question
+ * and keeps its id. The server moves the binding to the new reply and clears it from the old
+ * row, but a message already in memory keeps the copy it was loaded with -- and the run store
+ * is keyed by run id, so the stopped reply would render whatever that run is doing now: the new
+ * question's live card, and then its report, in two places at once.
+ *
+ * The run's own `assistantMessageId` is the answer, since that is exactly what the server moves.
+ * A run that never named one (created without a placeholder) belongs to whoever asks.
+ */
+export function researchReplyOwnsRun(
+ boundAssistantMessageId: unknown,
+ messageId: unknown,
+): boolean {
+ if (typeof boundAssistantMessageId !== "string" || !boundAssistantMessageId) {
+ return true;
+ }
+ if (typeof messageId !== "string" || !messageId) {
+ return true;
+ }
+ return boundAssistantMessageId === messageId;
+}
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index f36bfe56d9b..5eedd12cf6f 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -242,7 +242,6 @@ test("modes that answer from scratch do not offer Continue", () => {
const plain = {
fromAudioInput: false,
audioOutputModel: false,
- deepResearchArmed: false,
};
assert.equal(modeAllowsContinuation(plain), true);
assert.equal(
@@ -255,11 +254,6 @@ test("modes that answer from scratch do not offer Continue", () => {
modeAllowsContinuation({ ...plain, audioOutputModel: true }),
false,
);
- // Research armed after the cut: the run replaces the partial with its report.
- assert.equal(
- modeAllowsContinuation({ ...plain, deepResearchArmed: true }),
- false,
- );
});
test("the overlap repair can eat a legitimate repeat, so local output skips it", () => {
diff --git a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
index c47c502d765..a463d886e59 100644
--- a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
+++ b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
@@ -91,7 +91,12 @@ test("the composer asks the thread-wide research question through the cache", ()
// orphaned helper would leave the scan where it was.
assert.match(
thread,
- /useAuiState\(\(\{ thread \}\) =>\s*threadHasResearchMessage\(thread\.messages\),?\s*\)/,
+ /state\.latestRunByThreadId\[researchThreadId\]/,
+ "the live run must override stale assistant-message status after retry or stop",
+ );
+ assert.match(
+ thread,
+ /useAuiState\(\(\{ thread \}\) =>\s*threadHasResearchMessage\(thread\.messages, liveResearchRunId\),?\s*\)/,
);
assert.doesNotMatch(
thread,
diff --git a/studio/frontend/tests/deep-research-handoff.test.ts b/studio/frontend/tests/deep-research-handoff.test.ts
new file mode 100644
index 00000000000..60988584749
--- /dev/null
+++ b/studio/frontend/tests/deep-research-handoff.test.ts
@@ -0,0 +1,136 @@
+// 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 handoff is read off the tool events every loop publishes, and those events also close a
+// call that never ran. Reading a run out of one spends the chat's single Deep Research on a
+// question the loop refused to pass on, and hiding a gated call's card hangs the turn on a
+// verdict the user is never asked for.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ DEEP_RESEARCH_QUESTION_MAX_CHARS,
+ DEEP_RESEARCH_STARTED_MARKER,
+ newDeepResearchHandoff,
+ readDeepResearchToolEvent,
+} from "../src/features/chat/utils/deep-research-handoff.ts";
+
+const STARTED = `${DEEP_RESEARCH_STARTED_MARKER} on that question. Reply with one short sentence.`;
+const QUESTION = "Which small dog breeds suit a flat with no garden?";
+
+const start = (over: Record<string, unknown> = {}) => ({
+ type: "tool_start",
+ tool_call_id: "call_r",
+ arguments: { question: QUESTION },
+ ...over,
+});
+
+const end = (over: Record<string, unknown> = {}) => ({
+ type: "tool_end",
+ tool_call_id: "call_r",
+ result: STARTED,
+ ...over,
+});
+
+test("a call that ran hands off its question and draws no tool card", () => {
+ const handoff = newDeepResearchHandoff();
+ assert.equal(readDeepResearchToolEvent(handoff, start()), true);
+ assert.equal(handoff.question, null);
+ assert.equal(readDeepResearchToolEvent(handoff, end()), true);
+ assert.equal(handoff.question, QUESTION);
+});
+
+test("the provisional start the local loop paints first is ignored", () => {
+ const handoff = newDeepResearchHandoff();
+ readDeepResearchToolEvent(
+ handoff,
+ start({ arguments: {}, tool_call_id: "" }),
+ );
+ readDeepResearchToolEvent(handoff, start());
+ readDeepResearchToolEvent(handoff, end());
+ assert.equal(handoff.question, QUESTION);
+});
+
+test("a start whose question could not be read falls back to the user's message", () => {
+ const handoff = newDeepResearchHandoff();
+ readDeepResearchToolEvent(handoff, start({ arguments: undefined }));
+ readDeepResearchToolEvent(handoff, end());
+ assert.equal(handoff.question, "");
+});
+
+test("a denied call is not a handoff, and keeps the card that asked", () => {
+ const handoff = newDeepResearchHandoff();
+ // A gated start has to reach the renderer, or the Allow / Deny buttons never paint and the
+ // loop blocks on a verdict for the rest of the turn.
+ assert.equal(
+ readDeepResearchToolEvent(handoff, start({ awaiting_confirmation: true })),
+ false,
+ );
+ assert.equal(
+ readDeepResearchToolEvent(
+ handoff,
+ end({ result: "Tool call rejected by user." }),
+ ),
+ false,
+ );
+ assert.equal(handoff.question, null);
+});
+
+test("an approved gated call hands off and closes its own card", () => {
+ const handoff = newDeepResearchHandoff();
+ readDeepResearchToolEvent(handoff, start({ awaiting_confirmation: true }));
+ assert.equal(readDeepResearchToolEvent(handoff, end()), false);
+ assert.equal(handoff.question, QUESTION);
+});
+
+test("a call the loop announced but never ran is not a handoff", () => {
+ for (const result of [
+ "Tool call budget for this message is exhausted.",
+ "Studio did not run this call.",
+ "Tool call was cut off mid-write.",
+ ]) {
+ const handoff = newDeepResearchHandoff();
+ readDeepResearchToolEvent(handoff, start());
+ readDeepResearchToolEvent(handoff, end({ result }));
+ assert.equal(handoff.question, null, result);
+ }
+});
+
+test("the question is clamped to what the endpoint accepts", () => {
+ const handoff = newDeepResearchHandoff();
+ const long = "x".repeat(DEEP_RESEARCH_QUESTION_MAX_CHARS + 500);
+ readDeepResearchToolEvent(handoff, start({ arguments: { question: long } }));
+ readDeepResearchToolEvent(handoff, end());
+ assert.equal(handoff.question?.length, DEEP_RESEARCH_QUESTION_MAX_CHARS);
+});
+
+test("the question clamp does not split an astral Unicode character", () => {
+ const handoff = newDeepResearchHandoff();
+ const prefix = "x".repeat(DEEP_RESEARCH_QUESTION_MAX_CHARS - 1);
+ readDeepResearchToolEvent(
+ handoff,
+ start({ arguments: { question: `${prefix}\u{1f600}tail` } }),
+ );
+ readDeepResearchToolEvent(handoff, end());
+ assert.equal(handoff.question, `${prefix}\u{1f600}`);
+ assert.equal(
+ Array.from(handoff.question ?? "").length,
+ DEEP_RESEARCH_QUESTION_MAX_CHARS,
+ );
+});
+
+test("a second call in the same turn is the model repeating itself", () => {
+ const handoff = newDeepResearchHandoff();
+ readDeepResearchToolEvent(handoff, start());
+ readDeepResearchToolEvent(handoff, end());
+ readDeepResearchToolEvent(
+ handoff,
+ start({
+ tool_call_id: "call_2",
+ arguments: { question: "something else" },
+ }),
+ );
+ readDeepResearchToolEvent(handoff, end({ tool_call_id: "call_2" }));
+ assert.equal(handoff.question, QUESTION);
+});
diff --git a/studio/frontend/tests/research-reoffered-after-stop.test.ts b/studio/frontend/tests/research-reoffered-after-stop.test.ts
new file mode 100644
index 00000000000..d4da336db94
--- /dev/null
+++ b/studio/frontend/tests/research-reoffered-after-stop.test.ts
@@ -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
+
+// The backend re-points a stopped run at the next question instead of refusing it, so the
+// composer has to offer deep research again. If either half of this drifts the user is locked
+// out of research for a chat the server would happily research.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ messageHasResearchRunId,
+ threadHasResearchMessage,
+} from "../src/components/assistant-ui/thread-research-presence.ts";
+
+const message = (custom: Record<string, unknown>) => ({ metadata: { custom } });
+
+test("a finished research reply holds the thread", () => {
+ for (const status of ["completed", "failed"]) {
+ assert.equal(
+ messageHasResearchRunId(
+ message({ researchRunId: "run_1", researchStatus: status }),
+ ),
+ true,
+ status,
+ );
+ }
+ // No status at all is older metadata: count it, to stay on the safe side.
+ assert.equal(
+ messageHasResearchRunId(message({ researchRunId: "run_1" })),
+ true,
+ );
+});
+
+test("a reply whose run is still going keeps the toggle lit instead", () => {
+ for (const status of ["planning", "queued", "running", "cancelling"]) {
+ assert.equal(
+ messageHasResearchRunId(
+ message({ researchRunId: "run_1", researchStatus: status }),
+ ),
+ false,
+ status,
+ );
+ }
+});
+
+test("a stopped research reply does not, from history or from a live run", () => {
+ assert.equal(
+ messageHasResearchRunId(
+ message({ researchRunId: "run_1", researchStatus: "cancelled" }),
+ ),
+ false,
+ );
+ assert.equal(
+ messageHasResearchRunId(
+ message({ researchRunId: "run_1", researchRun: { status: "cancelled" } }),
+ ),
+ false,
+ );
+});
+
+test("the live run wins over the stored status, which lags a stop by one write", () => {
+ assert.equal(
+ messageHasResearchRunId(
+ message({
+ researchRunId: "run_1",
+ researchStatus: "running",
+ researchRun: { status: "cancelled" },
+ }),
+ ),
+ false,
+ );
+});
+
+test("a live retry overrides the failed status stored on the assistant message", () => {
+ const messages = [
+ message({ researchRunId: "run_1", researchStatus: "failed" }),
+ ];
+
+ assert.equal(threadHasResearchMessage(messages), true);
+ assert.equal(threadHasResearchMessage(messages, "run_1"), false);
+});
+
+test("a thread whose only research reply was stopped reads as unused", () => {
+ assert.equal(
+ threadHasResearchMessage([
+ {},
+ message({ researchRunId: "run_1", researchStatus: "cancelled" }),
+ ]),
+ false,
+ );
+ assert.equal(
+ threadHasResearchMessage([
+ message({ researchRunId: "run_1", researchStatus: "cancelled" }),
+ message({ researchRunId: "run_2", researchStatus: "completed" }),
+ ]),
+ true,
+ );
+});
+
+test("a message with no run id is unaffected", () => {
+ assert.equal(messageHasResearchRunId({}), false);
+ assert.equal(messageHasResearchRunId(message({})), false);
+ assert.equal(
+ messageHasResearchRunId(message({ researchStatus: "cancelled" })),
+ false,
+ );
+});
diff --git a/studio/frontend/tests/research-run-binding.test.ts b/studio/frontend/tests/research-run-binding.test.ts
new file mode 100644
index 00000000000..0077bcb1c02
--- /dev/null
+++ b/studio/frontend/tests/research-run-binding.test.ts
@@ -0,0 +1,34 @@
+// 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 run store is keyed by run id and a re-pointed run keeps its id, so the reply it left
+// behind would otherwise render the new question's card -- and then its report -- twice.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { researchReplyOwnsRun } from "../src/features/chat/utils/research-run-binding.ts";
+
+test("the reply the run points at owns it", () => {
+ assert.equal(researchReplyOwnsRun("assistant-1", "assistant-1"), true);
+});
+
+test("the reply the run was re-pointed away from does not", () => {
+ assert.equal(researchReplyOwnsRun("assistant-2", "assistant-1"), false);
+});
+
+test("a run that named no reply belongs to whoever asks", () => {
+ for (const bound of [undefined, null, ""]) {
+ assert.equal(
+ researchReplyOwnsRun(bound, "assistant-1"),
+ true,
+ String(bound),
+ );
+ }
+});
+
+test("a message with no id of its own is left as it was", () => {
+ for (const id of [undefined, null, ""]) {
+ assert.equal(researchReplyOwnsRun("assistant-2", id), true, String(id));
+ }
+});
diff --git a/studio/frontend/tests/research-thread-claim-release.test.ts b/studio/frontend/tests/research-thread-claim-release.test.ts
new file mode 100644
index 00000000000..de2df569942
--- /dev/null
+++ b/studio/frontend/tests/research-thread-claim-release.test.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// claimedThreadIds is what the composer reads to take deep research away. Only a finished run
+// spends the chat's research: one still going keeps the toggle lit, and a stopped one is
+// re-pointed at the next question rather than refused, so neither may claim the thread.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+register("./helpers/vite-env-loader.mjs", import.meta.url);
+registerBundlerResolver();
+installLocalStorageFake();
+Object.assign(globalThis.window as object, { addEventListener: () => {} });
+
+const { ingestResearchUpdate, resetResearchRunState, useResearchRunStore } =
+ await import("../src/features/chat/stores/research-run-store.ts");
+
+type AnyRecord = Record<string, unknown>;
+
+function run(overrides: AnyRecord = {}): AnyRecord {
+ return {
+ id: "run-1",
+ threadId: "thread-1",
+ userMessageId: "user-1",
+ status: "planning",
+ plan: null,
+ planRevision: 0,
+ planHash: null,
+ steps: [],
+ sources: [],
+ documentSources: [],
+ lastEventSeq: 0,
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ ...overrides,
+ };
+}
+
+// biome-ignore lint/suspicious/noExplicitAny: the store's run shape is exercised structurally
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const ingest = ingestResearchUpdate as any;
+
+const claimed = (threadId = "thread-1") =>
+ Boolean(useResearchRunStore.getState().claimedThreadIds[threadId]);
+
+test("a run still going keeps the toggle, a finished one takes it", () => {
+ resetResearchRunState();
+ for (const status of ["planning", "queued", "running", "cancelling"]) {
+ ingest(run({ status }));
+ assert.equal(claimed(), false, status);
+ }
+ ingest(run({ status: "completed" }));
+ assert.equal(claimed(), true);
+});
+
+test("a failed run spends the research too, retry is its way back", () => {
+ resetResearchRunState();
+ ingest(run({ status: "failed" }));
+ assert.equal(claimed(), true);
+});
+
+test("stopping the run leaves the thread unclaimed", () => {
+ resetResearchRunState();
+ ingest(run());
+ ingest(run({ status: "cancelled" }));
+ assert.equal(claimed(), false);
+});
+
+test("an older stopped run does not unclaim a thread a newer finished run spent", () => {
+ resetResearchRunState();
+ ingest(run({ id: "run-2", createdAt: 5, status: "completed" }));
+ ingest(run({ id: "run-1", createdAt: 1, status: "cancelled" }));
+ assert.equal(claimed(), true);
+});
+
+test("re-pointing the stopped run keeps the toggle until it finishes", () => {
+ resetResearchRunState();
+ ingest(run({ status: "cancelled" }));
+ assert.equal(claimed(), false);
+ ingest(run({ status: "planning", userMessageId: "user-2", planRevision: 1 }));
+ assert.equal(claimed(), false);
+ ingest(run({ status: "completed", userMessageId: "user-2", planRevision: 1 }));
+ assert.equal(claimed(), true);
+});
diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.py
index 3b87f2dad6a..c4318ca5fae 100644
--- a/tests/studio/test_deep_research_frontend_contract.py
+++ b/tests/studio/test_deep_research_frontend_contract.py
@@ -71,10 +71,21 @@ def test_research_mode_is_single_chat_and_detaches_without_cancel() -> None:
# runSignal, not abortSignal: each run gets its own controller, forwarded from the thread
# signal, so one chat's Stop cannot abort a sibling streaming in the background.
assert "if (runSignal.aborted) return" in adapter
- research = adapter.split("if (\n runtime.deepResearchEnabled", 1)[1].split(
+ # The model decides: arming research offers it the deep_research tool, and the run starts
+ # off the tool events every loop already publishes, never off the toggle alone.
+ assert "deep_research_armed: true" in adapter
+ assert 'toolEvent.tool_name === "deep_research"' in adapter
+ assert "readDeepResearchToolEvent(deepResearchHandoff, toolEvent)" in adapter
+ assert "if (deepResearchHandoff.question !== null && !runSignal.aborted)" in adapter
+ assert 'yield* startDeepResearch("")' not in adapter
+ # Armed research asks for Studio's tool loop on the external body too. Without it the
+ # turn proxies through, the model is never offered the tool, and arming does nothing.
+ assert "projectRagEnabled ||" in adapter
+ assert "deepResearchArmed)" in adapter
+ research = adapter.split("const startDeepResearch = async function*", 1)[1].split(
"const sandboxSessionId", 1
)[0]
- assert "await resolveQueuedEmptyLocalModel(abortSignal)" in research
+ assert "await resolveQueuedEmptyLocalModel(transitionSignal)" in research
assert "queuedEmptyModelRuntime = resolution.modelRuntime" in research
assert "signal: researchFollowController.signal" in adapter
assert "beginExternalResearchFollow(" in adapter
@@ -97,6 +108,22 @@ def test_research_mode_is_single_chat_and_detaches_without_cancel() -> None:
assert "resolveChatInstructions" in adapter
+def test_research_handoff_transition_honors_the_original_run_stop() -> None:
+ adapter = source("features/chat/api/chat-adapter.ts")
+ research = adapter.split("const startDeepResearch = async function*", 1)[1].split(
+ "const deepResearchHandoff = newDeepResearchHandoff();", 1
+ )[0]
+
+ assert "transitionSignal: AbortSignal = abortSignal" in research
+ assert "await waitForModelReady(transitionSignal)" in research
+ assert "await resolveQueuedEmptyLocalModel(transitionSignal)" in research
+ registered = research.index(
+ "runtime.registerThreadServerCancel(threadKey, researchServerCancel);"
+ )
+ assert research.rfind("if (transitionSignal.aborted) return;", 0, registered) >= 0
+ assert adapter.count("startDeepResearch(deepResearchHandoff.question, runSignal)") == 2
+
+
def test_research_reasoning_effort_is_clamped_to_the_loaded_model() -> None:
# A level the loaded model lacks is dropped by llama.cpp, so the durable run would silently
# fall back to the template default. Must use the same helper and levels as normal local
@@ -155,6 +182,10 @@ def test_research_presentation_is_integrated() -> None:
assert "if (researchRunId) return null" in thread
assert "!researchRunId &&" in thread
assert "if (researchRunId || ownsResearchMessage)" in thread
+ assert "ResearchMessageRunIdContext = createContext<string | null>(null)" in thread
+ assert "researchReplyOwnsRun(boundResearchAssistantMessageId, messageId)" in thread
+ assert "<ResearchMessageRunIdContext.Provider value={researchRunId}>" in thread
+ assert "useContext(ResearchMessageRunIdContext)" in thread
# A prompt whose reply is a research message loses its edit and delete controls. Ownership is
# a question about the whole repository, not the visible message list: a reply can sit on a
# branch the view is not showing. It used to be one export per user message (quadratic in
@@ -186,6 +217,13 @@ def test_research_presentation_is_integrated() -> None:
assert "Stop research" not in activity
assert "retryResearchRun" in activity
assert "Deep research completed" in message
+ empty_fallback = message.split("if (!run) {", 1)[1].split("if (run.status", 1)[0]
+ assert (
+ empty_fallback.index("if (fallbackText.trim())")
+ < empty_fallback.index("if (!ownsRun)")
+ < empty_fallback.index("Loading research…")
+ )
+ assert "return null;" in empty_fallback
assert "<DocumentSourcesGroup" in message
assert "urlTransform={safeMarkdownUrl}" in markdown_preview
assert 'node.tagName !== "img"' in safe_markdown_url
@@ -336,3 +374,73 @@ def test_research_stop_is_prompt_only_and_deduplicated() -> None:
assert "Stop research" not in activity
assert "abortSignal.reason as { detach?: boolean }" in adapter
assert "await cancelResearchRun(createdRun.id)" in adapter
+
+
+def test_the_handoff_is_keyed_on_the_result_the_backend_writes() -> None:
+ """tool_end alone closes a denied, skipped or budget-exhausted call too.
+
+ Reading a run out of one spends the chat's single Deep Research on a question the loop
+ refused to pass on, so the two sides have to agree on what "it ran" looks like.
+ """
+ helper = source("features/chat/utils/deep-research-handoff.ts")
+ tools = (ROOT / "studio" / "backend" / "core" / "inference" / "tools.py").read_text(
+ encoding = "utf-8"
+ )
+ marker = re.search(r'DEEP_RESEARCH_STARTED_MARKER = "([^"]+)"', tools)
+ assert marker is not None
+ assert f'DEEP_RESEARCH_STARTED_MARKER = "{marker.group(1)}"' in helper
+ assert "result.startsWith(DEEP_RESEARCH_STARTED_MARKER)" in helper
+ # A gated call keeps its Allow / Deny card: the loop blocks on a verdict, so hiding it
+ # asks the user nothing and the turn hangs there.
+ assert "if (event.awaiting_confirmation === true) {\n return false;" in helper
+
+ # The clamp is the endpoint's own limit; a longer question 422s the whole handoff.
+ routes = (ROOT / "studio" / "backend" / "routes" / "research_runs.py").read_text(
+ encoding = "utf-8"
+ )
+ max_length = re.search(
+ r"question: str \| None = Field\(default = None, max_length = ([\d_]+)\)", routes
+ )
+ assert max_length is not None
+ limit = int(max_length.group(1).replace("_", ""))
+ assert f"DEEP_RESEARCH_QUESTION_MAX_CHARS = {limit}" in helper
+
+
+def test_the_handoff_uses_the_turn_that_asked_for_it() -> None:
+ """The handoff runs after the model's stream, and the model selector stays usable.
+
+ Reading the store there researched model A's handoff with whichever model B had since
+ been picked, or failed outright when B runs no Studio tools.
+ """
+ adapter = source("features/chat/api/chat-adapter.ts")
+ # The generator's own body: the main path's re-read after an auto-load is a different
+ # thing, and it happens at send time where reading the store is right.
+ research = adapter.split("const startDeepResearch = async function*", 1)[1].split(
+ "const deepResearchHandoff = newDeepResearchHandoff();", 1
+ )[0]
+ assert "const sendTimeRuntime = runtime;" in research
+ assert "withResolvedModel(sendTimeRuntime)" in research
+ # Only the empty-model resolution, which happens inside this call, may override it.
+ assert "useChatRuntimeStore.getState()" not in research
+
+
+def test_a_local_model_without_tools_cannot_consume_research_without_classifying() -> None:
+ adapter = source("features/chat/api/chat-adapter.ts")
+ fallback = adapter.split("if (\n deepResearchArmed &&", 1)[1].split(
+ "// Project sources auto-scope", 1
+ )[0]
+
+ assert "!supportsTools" in fallback
+ assert "!isExternalModelId(params.checkpoint)" in fallback
+ assert "deepResearchArmed = false" in fallback
+ assert "runtime.setDeepResearchEnabled(false)" in fallback
+ assert "yield* startDeepResearch" not in fallback
+
+
+def test_a_tool_that_ran_starts_its_run_even_if_the_reply_never_finished() -> None:
+ """The acknowledgement can error, time out or drop; the run it announced is still owed."""
+ adapter = source("features/chat/api/chat-adapter.ts")
+ stream_error = adapter.split("} catch (streamError) {", 1)[1].split("throw streamError;", 1)[0]
+ assert "deepResearchHandoff.question !== null && !runSignal.aborted" in stream_error
+ assert "yield* startDeepResearch(deepResearchHandoff.question, runSignal)" in stream_error
+ assert "if (deepResearchHandoff.question !== null) break;" in adapter
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index eb4099807f7..e1befe6a858 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -365,10 +365,11 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
) < CHAT_ADAPTER.index("if (runtime.deepResearchEnabled && threadAlreadyResearched)")
research = _between(
CHAT_ADAPTER,
- "if (\n runtime.deepResearchEnabled",
- "const sandboxSessionId",
+ "const startDeepResearch = async function*",
+ "const deepResearchHandoff",
)
- assert "const liveRuntime = useChatRuntimeStore.getState()" in research
+ assert "const sendTimeRuntime = runtime" in research
+ assert "const liveRuntime = useChatRuntimeStore.getState()" not in research
assert "...queuedRunSettings" in research
auto_load_merge = _between(
CHAT_ADAPTER,
@@ -412,7 +413,8 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
assert "const visibleRoute = window.location.href" in CHAT_ADAPTER
assert "window.location.href === visibleRoute" in CHAT_ADAPTER
assert "trackQueuedSettings: false" in CHAT_ADAPTER
- assert CHAT_ADAPTER.count("await resolveQueuedEmptyLocalModel(abortSignal)") >= 2
+ assert "await resolveQueuedEmptyLocalModel(transitionSignal)" in CHAT_ADAPTER
+ assert "await resolveQueuedEmptyLocalModel(abortSignal)" in CHAT_ADAPTER
assert "persist: !options?.preserveVisibleSettings" in CHAT_ADAPTER
assert "beginModelLoading()" in CHAT_ADAPTER
assert "endModelLoading(lifecycleLease)" in CHAT_ADAPTER
@@ -693,8 +695,8 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
)
assert "force_cancel_active:" in SHARED_COMPOSER
assert (
- "resolvedThreadId ===\n useChatRuntimeStore.getState().activeThreadId"
- in CHAT_ADAPTER
+ "useChatRuntimeStore.getState().activeThreadId ===\n"
+ " (usageThreadKey ?? activeThreadIdAtRunStart)" in CHAT_ADAPTER
)
assert (
"findLatestUserAudioBase64(\n survivingMessages,\n !queuedRunSettings"
diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.py
index 628938c94f3..b688eb54b4d 100644
--- a/tests/studio/test_new_chat_context_recount.py
+++ b/tests/studio/test_new_chat_context_recount.py
@@ -1393,10 +1393,13 @@ def test_history_hydration_keeps_saved_usage_it_restored(
), "the completion half of an exact total must survive hydration"
-def test_deep_research_declines_the_recount():
- """With Deep Research on, the next send creates a server-side research run instead of posting
- this history, and the research reply carries no usage to correct a guess with. Counting would
- put a total on the bar describing a request that is never made, and leave it there."""
+def test_deep_research_recounts_before_the_model_decides():
+ """Arming Deep Research no longer guarantees a server-side research run.
+
+ The model first receives the ordinary chat turn and may answer directly, so the bar must price
+ that request just like any other send. A later tool handoff replaces the reply with research
+ state, but cannot justify hiding the context estimate before the model decides.
+ """
out = _run(
textwrap.dedent(
f"""
@@ -1412,8 +1415,8 @@ def test_deep_research_declines_the_recount():
"""
)
)
- assert out["counts"] == 0, "a research turn must not be priced as a chat completion"
- assert out["contextUsage"] is None
+ assert out["counts"] == 1, "the model-decision turn must be priced before it can hand off"
+ assert out["contextUsage"] is not None
def test_an_image_branch_is_declined_before_it_is_sent():