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: tell the agent a project's working folder is where its tools run, so it reads the files instead of asking for them (#16251)
oobaboogaef943ab3b700
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex bcc41cf17f5..b2323595597 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -9992,6 +9992,23 @@ def _project_workdir_for(session_id: "str | None") -> "str | None":return _get_project_workdir(session_id)+def session_runs_in_user_folder(session_id: "str | None") -> bool:+ """Whether this session's code tools run in the owner's chosen project folder, resolved as the executor does."""+ if not session_id or not session_id.startswith(_PROJECT_SESSION_PREFIX):+ return False+ try:+ from storage.studio_db import available_project_working_folder, get_chat_project++ # One read rules out most projects before the four the full resolution makes.+ project = get_chat_project(session_id[len(_PROJECT_SESSION_PREFIX) :])+ if not available_project_working_folder(project):+ return False+ workdir = _project_workdir_for(session_id)+ return bool(workdir) and _is_user_project_folder(session_id, workdir)+ except Exception:+ return False++def _get_project_workdir(session_id: str) -> str | None:# Host project paths are single-user only; managed accounts use their sandbox.if not is_owner_context():diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 2e68d6e8126..96c25e3071d 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -3551,6 +3551,13 @@ class ChatCountTokensRequest(ReasoningControlsRequest):"the same id the completion sends to price them."),)+ session_id: Optional[str] = Field(+ None,+ description = (+ "[x-unsloth] The tool session the completion sends. A project's chosen working "+ "folder adds a sentence to the tool nudge, so the count needs it to price that."+ ),+ )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.pyindex 65905f3c521..66237cceca0 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -5632,6 +5632,35 @@ def _full_access_tip(code_tools: list[str]) -> str:)+def _project_folder_tip(tool_names) -> str:+ """The tool schemas say "sandbox" outside Full access, so models deny a chosen folder they can reach."""+ readers = [name for name in ("terminal", "python") if name in tool_names]+ if not readers:+ return ""+ # Named: told only "a tool call", small models list the folder and then web-search how to read a file.+ reader = " or ".join(readers) + " tool"+ web = "; web_search cannot see them" if "web_search" in tool_names else ""+ return (+ "This chat belongs to a project, and the current working directory is the folder the "+ 'user chose for it, so "my project" and "my files" mean the files there. When asked '+ f"about the project or its files, list and read them with the {reader} first{web}. "+ "Read them rather than asking the user to upload or paste them, and if a read fails or "+ "is denied, say what failed instead of saying you have no access. Use relative paths."+ )+++async def _tools_run_in_user_folder(payload, tools) -> bool:+ session_id = getattr(payload, "session_id", None)+ names = {+ (tool.get("function") or {}).get("name") for tool in tools or () if isinstance(tool, dict)+ }+ if not session_id or not names.intersection({"terminal", "python"}):+ return False+ from core.inference.tools import session_runs_in_user_folder++ return await asyncio.to_thread(session_runs_in_user_folder, session_id)++# Avoid the word 'greetings': small models then greet instead of researching._TOOL_RESEARCH_TIP = ("Deep Research is turned on for this conversation. For factual questions or requests "@@ -5736,8 +5765,9 @@ def _build_tool_action_nudge(model_name: str,full_access: bool = False,full_access_only: bool = False,+ user_folder: bool = False,) -> str:- """full_access_only keeps just the Full access sentence and skills catalog, not the general guidance."""+ """full_access_only keeps just the environment sentences (Full access, project folder) and skills catalog, not the general guidance."""tool_names = {(tool.get("function") or {}).get("name")for tool in tools@@ -5765,10 +5795,13 @@ def _build_tool_action_nudge(can_run_scripts = bool({"python", "terminal"} & tool_names),compact = compact,)+ folder_tip = _project_folder_tip(tool_names) if user_folder else ""if full_access_only:tips = []if full_access and has_code:tips.append(_full_access_tip(code_tools))+ if folder_tip:+ tips.append(folder_tip)if has_skills:tips.append(skill_tip)return " ".join(tip for tip in tips if tip)@@ -5790,6 +5823,8 @@ def _build_tool_action_nudge(tool_tip_parts.append(_TOOL_CODE_TIP)if full_access:tool_tip_parts.append(_full_access_tip(code_tools))+ if folder_tip:+ tool_tip_parts.append(folder_tip)if has_artifact:tool_tip_parts.append(_TOOL_ARTIFACT_TIP)if has_research:@@ -28581,6 +28616,7 @@ async def _proxy_to_external_provider(tools = studio_tool_payloads,model_name = model,full_access = bool(payload.bypass_permissions),+ user_folder = await _tools_run_in_user_folder(payload, studio_tool_payloads),full_access_only = True,)chat_messages = _append_to_codex_instructions(chat_messages, _codex_nudge)@@ -28951,6 +28987,7 @@ async def _proxy_to_external_provider(tools = external_studio_tools,model_name = model,full_access = bool(payload.bypass_permissions),+ user_folder = await _tools_run_in_user_folder(payload, external_studio_tools),full_access_only = True,)# The compaction nudge is not part of the general nudge: once the thread has an archive@@ -31814,6 +31851,7 @@ async def produce_openai_chat_completions(tools = tools_to_use,model_name = model_name,full_access = bool(payload.bypass_permissions),+ user_folder = await _tools_run_in_user_folder(payload, tools_to_use),)# Nudge the model to ground in attached documents instead of memory.@@ -33819,6 +33857,7 @@ async def produce_openai_chat_completions(tools = _sf_tools_to_use,model_name = model_name,full_access = bool(payload.bypass_permissions),+ user_folder = await _tools_run_in_user_folder(payload, _sf_tools_to_use),)# RAG nudge, mirroring the GGUF path.@@ -41639,6 +41678,7 @@ async def _mlx_count_chat_tokens(tools = _tools_to_use,model_name = public_model_id(active) or payload.model,full_access = bool(payload.bypass_permissions),+ user_folder = await _tools_run_in_user_folder(payload, _tools_to_use),),_tools_to_use,rag_scope = payload.rag_scope,@@ -42034,6 +42074,7 @@ async def chat_count_tokens(tools = tools_to_use,model_name = _llama_public_model_id(llama_backend, payload.model),full_access = bool(payload.bypass_permissions),+ user_folder = await _tools_run_in_user_folder(payload, tools_to_use),),tools_to_use,rag_scope = payload.rag_scope,@@ -42226,6 +42267,8 @@ async def _anthropic_in_process_count(fields = _anthropic_chat_fields(payload, reads_images = bool(entry.get("is_vision")), server_tools = server_tools)+ # The completion sends it too (anthropic_messages builds its ChatCompletionRequest with it).+ fields["session_id"] = payload.session_idreturn JSONResponse(content = {"input_tokens": await _anthropic_chat_count(fields, request, current_subject)})@@ -42809,6 +42852,7 @@ async def anthropic_count_tokens(tools = openai_tools,model_name = _llama_public_model_id(llama_backend, payload.model),full_access = _count_full_access,+ user_folder = await _tools_run_in_user_folder(payload, openai_tools),)openai_messages = _append_to_system_message(openai_messages, _count_nudge)@@ -43978,6 +44022,7 @@ async def anthropic_messages(tools = openai_tools,model_name = model_name,full_access = _full_access,+ user_folder = await _tools_run_in_user_folder(payload, openai_tools),)if _nudge:diff --git a/studio/backend/tests/test_full_access_tool_prompt.py b/studio/backend/tests/test_full_access_tool_prompt.pyindex daa23709b01..a3f5a1e7a22 100644--- a/studio/backend/tests/test_full_access_tool_prompt.py+++ b/studio/backend/tests/test_full_access_tool_prompt.py@@ -24,6 +24,7 @@ from routes.inference import (_append_to_codex_instructions,_build_tool_action_nudge,_full_access_tip,+ _project_folder_tip,_select_request_tools,)@@ -287,6 +288,97 @@ def test_full_access_tip_needs_a_code_tool():assert nudge == _build_tool_action_nudge(tools = _WEB_ONLY, model_name = "test-8B")+_FOLDER_MARKER = "the current working directory is the folder the user chose for it"++[email protected]("full_access", [False, True], ids = ["sandboxed", "full_access"])+def test_a_chosen_project_folder_is_named_in_every_mode(full_access):+ """In Ask/Approve for me the tools run in the user's folder (_prepare_tool_launch's+ user_working_folder), yet the schemas still say sandbox: without this sentence a model+ answers "What project/files?", as reported on Reddit. Full access runs there too."""+ plain = _build_tool_action_nudge(+ tools = _CODE_TOOLS, model_name = "test-8B", full_access = full_access+ )+ nudge = _build_tool_action_nudge(+ tools = _CODE_TOOLS, model_name = "test-8B", full_access = full_access, user_folder = True+ )+ assert _FOLDER_MARKER not in plain+ assert _FOLDER_MARKER in nudge+ assert "list and read them with the terminal or python tool first" in nudge+ assert "rather than asking the user to upload or paste them" in nudge+ # A read can fail or an approval be denied: the model reports that, not a blanket "no access".+ assert "if a read fails or is denied, say what failed" in nudge+ # Additive: nothing the nudge said before is dropped.+ assert nudge == plain + " " + _project_folder_tip({"python", "terminal"})+ assert ("where Unsloth Studio is running" in nudge) == full_access++[email protected]("names", [{"web_search"}, {"edit_file"}, {"web_search", "edit_file"}])+def test_the_folder_sentence_needs_a_tool_that_can_read(names):+ """Neither web_search nor edit_file can list or read the folder, so the sentence would ask+ for a look the model cannot take."""+ tools = [t for t in ALL_TOOLS if t["function"]["name"] in names]+ nudge = _build_tool_action_nudge(tools = tools, model_name = "test-8B", user_folder = True)+ assert _FOLDER_MARKER not in nudge+ assert nudge == _build_tool_action_nudge(tools = tools, model_name = "test-8B")+++ ("names", "reader", "web"),+ [+ ({"terminal"}, "with the terminal tool first", False),+ ({"python", "edit_file"}, "with the python tool first", False),+ ({"python", "terminal", "web_search"}, "with the terminal or python tool first", True),+ ],+)+def test_the_folder_sentence_names_the_tools_that_can_read(names, reader, web):+ """Told only "a tool call", Qwen3.5-4B listed the folder and then web-searched how to read+ app.py until it gave up with an empty answer."""+ tip = _project_folder_tip(names)+ assert reader in tip+ assert ("web_search cannot see them" in tip) == web++[email protected]("full_access", [False, True], ids = ["sandboxed", "full_access"])+def test_the_studio_tool_loop_paths_carry_the_folder_sentence(full_access):+ """External providers and Codex run python/terminal in the same workdir, with only the+ environment sentences."""+ only = _build_tool_action_nudge(+ tools = _CODE_TOOLS,+ model_name = "test-8B",+ full_access = full_access,+ full_access_only = True,+ user_folder = True,+ )+ assert _FOLDER_MARKER in only+ assert "Tools are available when they materially improve" not in only+ assert ("where Unsloth Studio is running" in only) == full_access+++def test_every_nudge_call_site_passes_the_folder_flag():+ """Structural on purpose: the eight call sites are completions and counts on different+ backends, and one that drops the flag silently loses the sentence or skews the count."""+ import ast+ from pathlib import Path++ import routes.inference as inference++ tree = ast.parse(Path(inference.__file__).read_text(encoding = "utf-8"))+ calls = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "_build_tool_action_nudge"+ ]+ assert len(calls) >= 8+ for call in calls:+ assert "user_folder" in {kw.arg for kw in call.keywords}, ast.unparse(call)+++def test_count_request_carries_the_session():+ assert _count_request(session_id = "project-p1").session_id == "project-p1"++def test_full_access_tip_needs_tools_at_all():assert _build_tool_action_nudge(tools = [], model_name = "test-8B", full_access = True) == ""diff --git a/studio/backend/tests/test_project_working_folder.py b/studio/backend/tests/test_project_working_folder.pyindex 672f82038fd..19ae958c45d 100644--- a/studio/backend/tests/test_project_working_folder.py+++ b/studio/backend/tests/test_project_working_folder.py@@ -7,6 +7,7 @@ The folder is only ever pointed at: the managed workspace stays where it was, aremoves that and nothing else, and a folder that moved or was replaced is never followed."""+import asyncioimport osimport base64import hashlib@@ -483,6 +484,47 @@ def test_agents_md_is_read_from_the_users_folder(env, monkeypatch):assert "Use tabs." in agents_md.agents_md_text(studio_db.get_chat_project("p1"))+def test_the_prompt_names_the_users_folder_exactly_when_the_tools_run_there(env, monkeypatch):+ """The nudge says the cwd is the user's project, where a model otherwise answered "What+ project/files?"; it must not say so for the managed folder, a replaced folder, another+ account or a plain chat."""+ runs_there = env.tools.session_runs_in_user_folder+ assert not runs_there("project-p1")+ assert not runs_there("thread-1")+ assert not runs_there(None)++ _use_repo(env)+ assert runs_there("project-p1")+ assert env.tools._get_workdir("project-p1") == os.path.realpath(env.repo)++ with monkeypatch.context() as patch:+ patch.setattr(env.tools, "is_owner_context", lambda: False)+ assert not runs_there("project-p1")++ env.repo.rename(env.repo.with_name("repo-moved"))+ env.repo.mkdir()+ assert not runs_there("project-p1")+++def test_the_route_reads_the_folder_from_the_requests_session(env):+ from models.inference import ChatCompletionRequest, ChatCountTokensRequest+ from routes.inference import _tools_run_in_user_folder++ _use_repo(env)+ base = {+ "model": "test-model",+ "messages": [{"role": "user", "content": "What files are in my project?"}],+ }+ code = [t for t in env.tools.ALL_TOOLS if t["function"]["name"] == "terminal"]+ web = [t for t in env.tools.ALL_TOOLS if t["function"]["name"] == "web_search"]+ for request_type in (ChatCompletionRequest, ChatCountTokensRequest):+ project = request_type(**base, session_id = "project-p1")+ assert asyncio.run(_tools_run_in_user_folder(project, code))+ assert not asyncio.run(_tools_run_in_user_folder(request_type(**base), code))+ # Nothing can look in the folder, so the project row is not read at all.+ assert not asyncio.run(_tools_run_in_user_folder(project, web))++def test_add_to_project_lands_where_the_tools_run(env, tmp_path):from core.inference import gallery_projectsdiff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 8833ec10e63..75ac5c7d8a3 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -2312,6 +2312,8 @@ export async function buildLocalTokenCountExtras(? await projectHasSources(ragProjectId): false;const ragOn = ragEnabled || projectRagEnabled;+ // Same id the completion sends (resolveSandboxSessionId).+ const sessionId = sandboxSessionIdFor(threadId, ragProjectId);// re-fetch for every counted user turn so skills created since page load match request pricing.await settleSkillsForText(userTexts(messages).join("\n"));@@ -2362,6 +2364,7 @@ export async function buildLocalTokenCountExtras(...localMediaTools,],mcp_enabled: mcpEnabledForChat,+ ...(sessionId ? { session_id: sessionId } : {}),// Top level, not in rag_scope: archived threads add search_conversation regardless of RAG....threadField,// Armed research puts the deep_research schema in the prompt, so the count carries it.