Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio research: run each step's knowledge base and MCP lookups alongside its web search (#17287)
Daniel Han1cc11b204d9f
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex 2ec1f36999d..b0dd90cc7f4 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -2175,7 +2175,9 @@ class ResearchSupervisor:await heartbeatexcept asyncio.CancelledError:pass+ # Stops side lookups that outlive a failed step.self._cancel_events.pop(account_key(run["id"]), None)+ cancel_event.set()self._lost_leases.discard(account_key(run["id"]))self._report_drafts.pop(account_key(run["id"]), None)@@ -2608,28 +2610,46 @@ class ResearchSupervisor:rag_result = ""else:used_queries.add(argument)- result = await asyncio.to_thread(- execute_tool,- "web_search",- {"query": argument},- cancel_event = self._cancel_event(run["id"]),- timeout = tool_timeout,- website_policy = website_policy,+ # Side lookups overlap the web search; awaited after it so a web error still wins.+ rag_task = (+ asyncio.ensure_future(+ asyncio.to_thread(+ execute_tool,+ "search_knowledge_base",+ {"query": argument},+ cancel_event = self._cancel_event(run["id"]),+ timeout = tool_timeout,+ rag_scope = run["config"]["ragScope"],+ )+ )+ if run["config"].get("ragScope")+ else None)- rag_result = ""- if run["config"].get("ragScope"):- rag_result = await asyncio.to_thread(+ mcp_task = (+ asyncio.ensure_future(+ self._search_mcp_tools(run, mcp_tools, argument, position, tool_timeout)+ )+ if mcp_tools+ else None+ )+ side_tasks = [task for task in (rag_task, mcp_task) if task is not None]+ try:+ result = await asyncio.to_thread(execute_tool,- "search_knowledge_base",+ "web_search",{"query": argument},cancel_event = self._cancel_event(run["id"]),timeout = tool_timeout,- rag_scope = run["config"]["ragScope"],- )- if mcp_tools:- mcp_sources = await self._search_mcp_tools(- run, mcp_tools, argument, position, tool_timeout+ website_policy = website_policy,)+ rag_result = await rag_task if rag_task is not None else ""+ if mcp_task is not None:+ mcp_sources = await mcp_task+ except BaseException:+ for task in side_tasks:+ task.cancel()+ await asyncio.gather(*side_tasks, return_exceptions = True)+ raiserag_result, rag_sources = _split_rag_result(rag_result)await self._check_active(run["id"])document_source_keys = {diff --git a/studio/backend/tests/test_research_mcp_sources.py b/studio/backend/tests/test_research_mcp_sources.pyindex 127c3f87603..8c317e910e2 100644--- a/studio/backend/tests/test_research_mcp_sources.py+++ b/studio/backend/tests/test_research_mcp_sources.py@@ -441,3 +441,133 @@ def test_identically_named_mcp_sources_have_distinct_citations(monkeypatch):)sources = asyncio.run(supervisor._search_mcp_tools({"id": "r"}, tools, "query", 0, 10))assert len({_document_source_citation(source) for source in sources}) == 2+++def test_step_lookups_run_alongside_the_web_search(notes_server, monkeypatch):+ import threading++ from core import research_runs as worker+ from routes.research_runs import CreateResearchRun, _sanitize_config++ config = _sanitize_config(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ ragScope = {"thread_id": "thread-1"},+ mcpSources = [{"serverId": "notes", "tool": "search_notes"}],+ ),+ {"modelId": "local-model"},+ )+ 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 = config,+ created_at = 10,+ )+ plan = research_db.set_plan("run-1", PLAN)+ research_db.approve("run-1", plan["planRevision"], plan["planHash"])+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))++ decisions = iter(+ (+ json.dumps({"action": "search", "title": "Launch", "query": "zephyr beta launch"}),+ json.dumps({"action": "finish", "title": "Enough"}),+ )+ )+ report = "# Zephyr\n\nThe beta shipped on 14 March 2031 [MCP: Project Notes · search_notes]."++ async def fake_stream_completion(run, messages, **kwargs):+ if "iterative research process" in messages[0]["content"]:+ return next(decisions), "", "stop", None+ research_db.set_report_progress(run["id"], report)+ return report, "", "stop", None++ kb_started = threading.Event()+ mcp_started = threading.Event()+ seen_during_web = {}++ def fake_tool(name, arguments, *args, **kwargs):+ if name == "web_search":+ seen_during_web["kb"] = kb_started.wait(5)+ seen_during_web["mcp"] = mcp_started.wait(5)+ return "No results found."+ if name == "search_knowledge_base":+ kb_started.set()+ return "No relevant documents found."+ mcp_started.set()+ return f"Zephyr notes for {arguments['query']}: the beta shipped on 14 March 2031."++ monkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)+ monkeypatch.setattr(worker, "execute_tool", fake_tool)+ monkeypatch.setattr(worker, "execute_mcp_tool", fake_tool)+ asyncio.run(supervisor._process(research_db.claim_next(supervisor.worker_id)))++ completed = research_db.get_run("run-1")+ assert completed["status"] == "completed"+ assert seen_during_web == {"kb": True, "mcp": True}+ assert [(s["kind"], s["filename"]) for s in completed["documentSources"]] == [+ ("mcp", "Project Notes · search_notes"),+ ]+++def test_side_lookups_are_told_to_stop_when_the_web_search_fails(notes_server, monkeypatch):+ import threading++ from core import research_runs as worker+ from routes.research_runs import CreateResearchRun, _sanitize_config++ config = _sanitize_config(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ mcpSources = [{"serverId": "notes", "tool": "search_notes"}],+ ),+ {"modelId": "local-model"},+ )+ 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 = config,+ created_at = 10,+ )+ plan = research_db.set_plan("run-1", PLAN)+ research_db.approve("run-1", plan["planRevision"], plan["planHash"])+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))++ async def fake_stream_completion(run, messages, **kwargs):+ decision = {"action": "search", "title": "Launch", "query": "zephyr beta launch"}+ return json.dumps(decision), "", "stop", None++ mcp_started = threading.Event()+ mcp_stopped = threading.Event()++ def fake_tool(+ name,+ arguments,+ *args,+ cancel_event = None,+ **kwargs,+ ):+ if name == "web_search":+ mcp_started.wait(5)+ raise RuntimeError("search backend crashed")+ mcp_started.set()+ if cancel_event.wait(5):+ mcp_stopped.set()+ return "Error: cancelled"++ monkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)+ monkeypatch.setattr(worker, "execute_tool", fake_tool)+ monkeypatch.setattr(worker, "execute_mcp_tool", fake_tool)+ asyncio.run(supervisor._process(research_db.claim_next(supervisor.worker_id)))++ assert research_db.get_run("run-1")["status"] == "failed"+ assert mcp_stopped.wait(5)