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: confirm Full Access directly from a chat tool approval (#15485)
Daniel Han31131970c432
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex bfb7d37ac81..7c3877c192e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -36767,6 +36767,7 @@ class LlamaCppBackend:sandbox_level: Optional[str] = None,compact_context: bool = False,website_policy: Optional[dict] = None,+ live_permissions = None,) -> Generator[dict, None, None]:"""Agentic loop: let the model call tools, execute them, and continue.@@ -36816,6 +36817,10 @@ class LlamaCppBackend:permission_mode, bypass_permissions = normalize_tool_permissions(permission_mode, bypass_permissions)+ from state.tool_approvals import LiveToolPermissions, bind_permission_upgrade++ if live_permissions is None:+ live_permissions = LiveToolPermissions(session_id, cancel_event)sandbox_level = normalize_sandbox_level(sandbox_level)stream_tool_execution = account_tool_stream(stream_tool_execution)@@ -38892,6 +38897,9 @@ class LlamaCppBackend:# Bypass wins here too, so a direct internal caller with both# flags never prompts. "auto" pauses only high-risk calls; "off"# pauses only a high-risk python/terminal call without OS isolation.+ permission_mode, bypass_permissions = live_permissions.apply(+ permission_mode, bypass_permissions+ )needs_confirm = needs_tool_confirmation(confirm_tool_calls = bool(confirm_tool_calls),bypass_permissions = bypass_permissions,@@ -38919,6 +38927,9 @@ class LlamaCppBackend:decision_slot = (begin_tool_decision(session_id, approval_id) if needs_confirm else None)+ bind_permission_upgrade(+ decision_slot, live_permissions, eligible = image_share is None+ )if needs_confirm:note_host_access(approval_id, decision.tool_name, decision.arguments)start_event = decision.tool_start_event()@@ -38954,6 +38965,11 @@ class LlamaCppBackend:)# Read before decision_slot is dropped in the deny branch._decision_reason = decision_reason(decision_slot)+ permission_mode, bypass_permissions = live_permissions.apply(+ permission_mode, bypass_permissions+ )+ if bypass_permissions:+ strict_isolation = Falseif _decision is not None and _decision != "deny":# tool_approved first: the route forwards it before retaking the model slot.yield decision.tool_approved_event(approval_id)diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex 7e79bf5ab69..24afe033b50 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -633,6 +633,9 @@ def run_safetensors_tool_loop(permission_mode, bypass_permissions = normalize_tool_permissions(permission_mode, bypass_permissions)+ from state.tool_approvals import LiveToolPermissions, bind_permission_upgrade++ live_permissions = LiveToolPermissions(session_id, cancel_event)sandbox_level = normalize_sandbox_level(sandbox_level)stream_tool_execution = account_tool_stream(stream_tool_execution)from core.inference.skill_mentions import load_mentioned_skills@@ -645,6 +648,7 @@ def run_safetensors_tool_loop(confirm_tool_calls = confirm_tool_calls,session_id = session_id,cancel_event = cancel_event,+ permission_upgrade = live_permissions,context_length = context_length,continue_final_message = continue_final_message,# The downstream tokenizer owns fitting; only system context is guaranteed.@@ -1441,6 +1445,9 @@ def run_safetensors_tool_loop(# Bypass wins here too, so a direct internal caller with both flags# never prompts. "auto" pauses only high-risk calls; "off" pauses only a# high-risk python/terminal call without OS isolation.+ permission_mode, bypass_permissions = live_permissions.apply(+ permission_mode, bypass_permissions+ )needs_confirm = needs_tool_confirmation(confirm_tool_calls = bool(confirm_tool_calls),bypass_permissions = bypass_permissions,@@ -1463,6 +1470,7 @@ def run_safetensors_tool_loop()approval_id = new_approval_id() if needs_confirm else ""decision_slot = begin_tool_decision(session_id, approval_id) if needs_confirm else None+ bind_permission_upgrade(decision_slot, live_permissions, eligible = image_share is None)if needs_confirm:note_host_access(approval_id, decision.tool_name, decision.arguments)start_event = decision.tool_start_event()@@ -1494,6 +1502,11 @@ def run_safetensors_tool_loop()# Read before decision_slot is dropped in the deny branch below._decision_reason = decision_reason(decision_slot)+ permission_mode, bypass_permissions = live_permissions.apply(+ permission_mode, bypass_permissions+ )+ if bypass_permissions:+ strict_isolation = Falseif _decision is not None and _decision != "deny":yield decision.tool_approved_event(approval_id)yield {"type": "status", "text": decision.status_text}diff --git a/studio/backend/core/inference/skill_mentions.py b/studio/backend/core/inference/skill_mentions.pyindex 7c578418698..1c891147d2c 100644--- a/studio/backend/core/inference/skill_mentions.py+++ b/studio/backend/core/inference/skill_mentions.py@@ -144,6 +144,7 @@ def load_mentioned_skills(continue_final_message = False,protected_message_ids = None,dedup_tool_context = True,+ permission_upgrade = None,):"""Inject complete manifests before generation; never a partial one. Caller gates on read_skill."""if continue_final_message or not any(@@ -177,6 +178,8 @@ def load_mentioned_skills()loaded_bytes = 0for name in names:+ if permission_upgrade is not None:+ mode, bypass = permission_upgrade.apply(mode, bypass)if cancel_event is not None and cancel_event.is_set():returnevent = {@@ -188,6 +191,9 @@ def load_mentioned_skills(if name in loadable and confirm_tool_calls and not bypass and mode not in ("auto", "off"):approval_id = new_approval_id()slot = begin_tool_decision(session_id, approval_id)+ from state.tool_approvals import bind_permission_upgrade++ bind_permission_upgrade(slot, permission_upgrade)try:yield {**event, "status": "awaiting_approval", "approval_id": approval_id}verdict = wait_tool_decision(slot, approval_id, cancel_event = cancel_event)diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex 7fcdc6cab65..17f96ecc8bf 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -1348,6 +1348,9 @@ async def stream_with_studio_tools(permission_mode, bypass_permissions = normalize_tool_permissions(policy.permission_mode, policy.bypass_permissions)+ from state.tool_approvals import LiveToolPermissions, bind_permission_upgrade++ live_permissions = LiveToolPermissions(session_id, cancel_event)scoped_tool_stream = account_tool_stream(stream_tool_execution)confirm_tool_calls = policy.confirm_callsrag_scope = policy.rag_scope@@ -1365,6 +1368,7 @@ async def stream_with_studio_tools(confirm_tool_calls = confirm_tool_calls,session_id = session_id,cancel_event = cancel_event,+ permission_upgrade = live_permissions,continue_final_message = run.continue_final_message,)load_task = None@@ -1813,6 +1817,9 @@ async def stream_with_studio_tools(call_id = decision.tool_call_id# Same id for a call the provider named; for one it did not, the card answers to the id the client mintedcard_id = decision.card_id+ permission_mode, bypass_permissions = live_permissions.apply(+ permission_mode, bypass_permissions+ )needs_confirmation = needs_tool_confirmation(confirm_tool_calls = confirm_tool_calls,bypass_permissions = bypass_permissions,@@ -1840,6 +1847,7 @@ async def stream_with_studio_tools(decision_slot = (begin_tool_decision(session_id, approval_id) if needs_confirmation else None)+ bind_permission_upgrade(decision_slot, live_permissions, eligible = image_share is None)if needs_confirmation:note_host_access(approval_id, name, arguments)@@ -1877,6 +1885,11 @@ async def stream_with_studio_tools(if not waiter.done():waiter.cancel()verdict = waiter.result() if waiter.done() else None+ permission_mode, bypass_permissions = live_permissions.apply(+ permission_mode, bypass_permissions+ )+ if bypass_permissions:+ strict_isolation = Falseif verdict == "deny":# Read decision_slot before it is dropped: it tells a user's refusal from an unanswered approval.denied_reason = decision_reason(decision_slot)diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 7b19c099da9..e7059caed06 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -3574,6 +3574,13 @@ class ToolConfirmRequest(BaseModel):session_id: Optional[str] = Noneapproval_id: Optional[str] = Nonedecision: Literal["allow", "deny"] = "deny"+ permission_mode: Optional[Literal["full"]] = None++ @model_validator(mode = "after")+ def _check_full_access_upgrade(self):+ if self.permission_mode == "full" and (self.decision != "allow" or not self.session_id):+ raise ValueError("A Full access upgrade requires Allow and the exact chat session")+ return selfclass BrowserActionResultRequest(BaseModel):diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex f91d21798c3..34a340cdfb1 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -21144,6 +21144,15 @@ async def cancel_inference(request: Request, current_subject: str = Depends(get_async def confirm_tool_call(request: ToolConfirmRequest, current_subject: str = Depends(get_current_subject)):+ full_access = request.permission_mode == "full"+ if full_access and (+ not auth_policy.full_access_permitted() or auth_policy.api_full_access_refused()+ ):+ raise HTTPException(+ status_code = 403,+ detail = "Full access is only available to the installation owner in the Unsloth UI "+ "(API callers require UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS=1).",+ )# Approving a host-path call unsandboxes it: like Full access, the UI's choice, not an API key's. Deny stays open.if (request.decision == "allow"@@ -21160,10 +21169,12 @@ async def confirm_tool_call(request.approval_id,request.decision,session_id = request.session_id,+ full_access = full_access,)if not matched:raise HTTPException(status_code = 404, detail = "No pending tool call confirmation")- return {"resolved": True}+ # An older backend ignores the new request field; clients require this acknowledgement.+ return {"resolved": True, **({"full_access_granted": True} if full_access else {})}@studio_router.post("/browser-action-result")@@ -31302,6 +31313,9 @@ async def produce_openai_chat_completions(def gguf_generate_with_tools():from core.inference.skill_mentions import load_mentioned_skills+ from state.tool_approvals import LiveToolPermissions++ gguf_live_permissions = LiveToolPermissions(payload.session_id, cancel_event)skill_instruction_ids = set()yield from load_mentioned_skills(@@ -31318,8 +31332,10 @@ async def produce_openai_chat_completions(context_length = llama_backend.context_length,continue_final_message = _continue_final_message(payload, thought = True),protected_message_ids = skill_instruction_ids,+ permission_upgrade = gguf_live_permissions,)yield from llama_backend.generate_chat_completion_with_tools(+ live_permissions = gguf_live_permissions,instruction_anchor_ids = skill_instruction_ids,messages = gguf_messages,replayed_image_parts = tuple(_gguf_replayed_image_parts),diff --git a/studio/backend/state/tool_approvals.py b/studio/backend/state/tool_approvals.pyindex 3f8b54d3e85..200ef835ae2 100644--- a/studio/backend/state/tool_approvals.py+++ b/studio/backend/state/tool_approvals.py@@ -71,6 +71,42 @@ _lock = threading.Lock()_pending: dict[str, dict] = {}+class LiveToolPermissions:+ """One live tool loop's upgrade, never a process/session-wide permission grant."""++ def __init__(+ self,+ session_id,+ cancel_event = None,+ ):+ from utils.account_context import current_account++ self.session_id = session_id or ""+ self.account = current_account()+ self.account_id = self.account.account_id+ self.cancel_event = cancel_event+ self._full = threading.Event()++ def apply(self, permission_mode, bypass_permissions):+ if self._full.is_set():+ return "full", True+ return permission_mode, bypass_permissions+++def bind_permission_upgrade(+ slot,+ permissions,+ *,+ eligible = True,+):+ """Bind before yielding the approval card; image disclosure alone never grants full access."""+ if not isinstance(slot, dict) or not eligible or permissions is None:+ return+ with _lock:+ if slot.get("session") == permissions.session_id and permissions.session_id:+ slot["permission_upgrade"] = permissions++def new_approval_id() -> str:"""Mint an unguessable id for one pending tool-call confirmation."""return secrets.token_urlsafe(16)@@ -78,8 +114,11 @@ def new_approval_id() -> str:def begin_tool_decision(session_id, approval_id) -> dict:"""Register a pending decision slot and return it. Call this *before* yielding the ``tool_start`` event so the waiter always exists by the time the user's confirmation can arrive."""+ from utils.account_context import current_account_id+slot = {"event": threading.Event(),+ "account_id": current_account_id(),"decision": None,"session": session_id or "",# Filled in by wait_tool_decision; read back with decision_reason().@@ -133,7 +172,12 @@ def wait_tool_decision(renew_lease = getattr(cancel_event, "renew_lease", None)def _settle(verdict, reason):- if isinstance(slot, dict):+ if not isinstance(slot, dict):+ return verdict+ # Under the resolver's lock: an Allow committed first wins, else the resolver sees the reason and refuses.+ with _lock:+ if slot["event"].is_set():+ verdict, reason = slot["decision"] or "deny", DECISION_ANSWEREDslot["reason"] = reasonreturn verdict@@ -212,6 +256,8 @@ def resolve_tool_decision(approval_id,decision,session_id = None,+ *,+ full_access = False,) -> bool:"""Record the user's "allow"/"deny" decision and unblock the loop. Returns ``True`` if a pending call matched, ``False`` otherwise (a stale or duplicate confirmation, or a session-scope mismatch). The first decision wins: once a slot's event is set, a later confirmation for the same id is rejected without mutating the recorded decision, so an Allow can never be flipped to Deny in the window before the waiter reads ``slot["decision"]`` and pops the slot."""if not approval_id:@@ -222,8 +268,32 @@ def resolve_tool_decision(return Falseif session_id is not None and slot["session"] != (session_id or ""):return False- if slot["event"].is_set():+ from utils.account_context import current_account_id++ if (+ slot.get("account_id") != current_account_id()+ or slot["event"].is_set()+ or slot.get("reason") is not None+ ):return False+ if full_access:+ permissions = slot.get("permission_upgrade")+ if (+ decision != "allow"+ or not session_id+ or permissions is None+ or permissions.account_id != current_account_id()+ or permissions.session_id != session_id+ or (permissions.cancel_event is not None and permissions.cancel_event.is_set())+ ):+ return False+ from state.tool_policy import require_tool_access+ from utils.account_context import run_as++ require_tool_access("full")+ # The tool worker keeps the run's API/UI identity: never acknowledge a grant it would refuse.+ run_as(permissions.account, require_tool_access, "full")+ permissions._full.set()slot["decision"] = decisionslot["event"].set()return Truediff --git a/studio/backend/tests/test_llama_admission_compat_matrix.py b/studio/backend/tests/test_llama_admission_compat_matrix.pyindex 0236808d9b0..f8f3314b089 100644--- a/studio/backend/tests/test_llama_admission_compat_matrix.py+++ b/studio/backend/tests/test_llama_admission_compat_matrix.py@@ -237,7 +237,7 @@ class TestOldCallers:inspect.signature(LlamaCppBackend.generate_chat_completion_with_tools).parameters)assert names.index("sandbox_level") == names.index("instruction_anchor_ids") + 1- assert names[-2:] == ["compact_context", "website_policy"]+ assert names[-3:] == ["compact_context", "website_policy", "live_permissions"]assert names.index("promote_reasoning_only") == names.index("permission_mode") + 1def test_the_wait_timeout_has_a_sane_default(self):diff --git a/studio/backend/tests/test_tool_full_access_upgrade.py b/studio/backend/tests/test_tool_full_access_upgrade.pynew file mode 100644index 00000000000..43eeeade6f7--- /dev/null+++ b/studio/backend/tests/test_tool_full_access_upgrade.py@@ -0,0 +1,423 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import asyncio+import json+import sys+import threading+from pathlib import Path++import pytest+from fastapi import HTTPException++from state import tool_approvals as approvals+from utils.account_context import AccountContext, OWNER, as_api_caller, run_as++# Reuse the neighboring scripted tool transports and authenticated client harness.+_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++[email protected](autouse = True)+def clean(monkeypatch):+ monkeypatch.delenv("UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS", raising = False)+ with approvals._lock:+ approvals._pending.clear()+ yield+ with approvals._lock:+ approvals._pending.clear()+++def _slot(+ *,+ session = "chat-a",+ eligible = True,+ bind = True,+ cancel = None,+):+ permissions = approvals.LiveToolPermissions(session, cancel)+ approval_id = approvals.new_approval_id()+ slot = approvals.begin_tool_decision(session, approval_id)+ if bind:+ approvals.bind_permission_upgrade(slot, permissions, eligible = eligible)+ return approval_id, slot, permissions+++def test_upgrade_is_atomic_and_local_to_one_bound_loop():+ approval_id, slot, permissions = _slot()+ other = approvals.LiveToolPermissions("chat-a")+ assert not approvals.resolve_tool_decision(+ approval_id, "allow", session_id = "wrong", full_access = True+ )+ assert not slot["event"].is_set()+ assert approvals.resolve_tool_decision(+ approval_id, "allow", session_id = "chat-a", full_access = True+ )+ assert slot["event"].is_set() and slot["decision"] == "allow"+ assert permissions.apply("ask", False) == ("full", True)+ assert other.apply("ask", False) == ("ask", False)+ assert not approvals.resolve_tool_decision(approval_id, "deny", session_id = "chat-a")+++ "case", ["unbound", "image", "expired", "cancelled", "answered", "no-session"]+)+def test_unavailable_approval_never_grants_full_access(case):+ cancel = threading.Event()+ approval_id, slot, permissions = _slot(+ bind = case != "unbound", eligible = case != "image", cancel = cancel+ )+ if case == "expired":+ slot["reason"] = approvals.DECISION_EXPIRED+ if case == "cancelled":+ cancel.set()+ if case == "answered":+ assert approvals.resolve_tool_decision(approval_id, "deny", session_id = "chat-a")+ assert not approvals.resolve_tool_decision(+ approval_id,+ "allow",+ session_id = None if case == "no-session" else "chat-a",+ full_access = True,+ )+ assert permissions.apply("ask", False) == ("ask", False)+ if case != "answered":+ assert not slot["event"].is_set()+++def test_another_account_cannot_answer_or_upgrade_the_slot():+ approval_id, slot, permissions = _slot()+ user = AccountContext("other", "other")+ assert not run_as(+ user,+ approvals.resolve_tool_decision,+ approval_id,+ "allow",+ session_id = "chat-a",+ full_access = True,+ )+ assert not slot["event"].is_set()+ assert permissions.apply("ask", False) == ("ask", False)+++def test_ui_cannot_upgrade_an_api_origin_without_the_operator_opt_in(monkeypatch):+ approval_id, slot, permissions = run_as(as_api_caller(OWNER), _slot)+ with pytest.raises(HTTPException, match = "API keys"):+ approvals.resolve_tool_decision(approval_id, "allow", session_id = "chat-a", full_access = True)+ assert not slot["event"].is_set()+ assert permissions.apply("ask", False) == ("ask", False)+ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS", "1")+ assert approvals.resolve_tool_decision(+ approval_id, "allow", session_id = "chat-a", full_access = True+ )+++def test_route_acknowledges_only_a_real_upgrade_and_rejects_stale_requests():+ from test_api_key_tool_confirm import _client_for+ approval_id, _pending, permissions = _slot()+ with _client_for(OWNER) as client:+ response = client.post(+ "/api/inference/tool-confirm",+ json = {+ "approval_id": approval_id,+ "session_id": "chat-a",+ "decision": "allow",+ "permission_mode": "full",+ },+ )+ assert response.status_code == 200+ assert response.json() == {"resolved": True, "full_access_granted": True}+ assert permissions.apply("ask", False) == ("full", True)+ assert (+ client.post(+ "/api/inference/tool-confirm",+ json = {+ "approval_id": approval_id,+ "session_id": "chat-a",+ "decision": "allow",+ "permission_mode": "full",+ },+ ).status_code+ == 404+ )+ aid, _slot_state, ordinary = _slot()+ response = client.post(+ "/api/inference/tool-confirm",+ json = {+ "approval_id": aid,+ "session_id": "chat-a",+ "decision": "allow",+ },+ )+ assert response.json() == {"resolved": True}+ assert ordinary.apply("ask", False) == ("ask", False)++[email protected]("account", [AccountContext("managed", "managed"), as_api_caller(OWNER)])+def test_route_rejects_disallowed_confirmers_without_resolving(account):+ from test_api_key_tool_confirm import _client_for++ approval_id, slot, permissions = _slot()+ with _client_for(account) as client:+ response = client.post(+ "/api/inference/tool-confirm",+ json = {+ "approval_id": approval_id,+ "session_id": "chat-a",+ "decision": "allow",+ "permission_mode": "full",+ },+ )+ assert response.status_code == 403+ assert not slot["event"].is_set()+ assert permissions.apply("ask", False) == ("ask", False)+++def test_full_access_request_requires_allow_and_the_exact_session():+ from pydantic import ValidationError+ from models.inference import ToolConfirmRequest+ for patch in ({"decision": "deny", "session_id": "chat-a"}, {"decision": "allow"}):+ with pytest.raises(ValidationError):+ ToolConfirmRequest(permission_mode = "full", **patch)+++def _run_two_calls(loop, monkeypatch, execute, answer):+ from core.inference import llama_cpp, safetensors_agentic, studio_tool_loop+ from test_api_key_tool_confirm import _tool_call_markup++ session = "chat-a"+ tool = {"type": "function", "function": {"name": "python"}}+ if loop == "safetensors":+ monkeypatch.setattr(safetensors_agentic, "wait_tool_decision", answer)+ turns = iter([_tool_call_markup("print(1)"), _tool_call_markup("print(2)"), "done"])++ def turn(_messages):+ yield next(turns)++ list(+ safetensors_agentic.run_safetensors_tool_loop(+ single_turn = turn,+ messages = [{"role": "user", "content": "hi"}],+ tools = [tool],+ execute_tool = execute,+ session_id = session,+ confirm_tool_calls = True,+ permission_mode = "ask",+ max_tool_iterations = 3,+ )+ )+ return+ if loop == "llama_cpp":+ from test_llama_cpp_tool_loop import (+ _backend_and_payloads,+ _run_tool_loop,+ _streamed_structured_tool_call,+ _sse,+ _done,+ )++ monkeypatch.setattr(llama_cpp, "wait_tool_decision", answer)+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)+ backend, _ = _backend_and_payloads(+ monkeypatch,+ [+ _streamed_structured_tool_call("python", {"code": "print(1)"}, "call_1"),+ _streamed_structured_tool_call("python", {"code": "print(2)"}, "call_2"),+ [_sse({"content": "Done."}), _done()],+ ],+ )+ monkeypatch.setattr(backend, "count_chat_tokens", lambda *args, **kwargs: 20)+ _run_tool_loop(+ backend,+ [{"role": "user", "content": "hi"}],+ [tool],+ max_tool_iterations = 3,+ confirm_tool_calls = True,+ permission_mode = "ask",+ session_id = session,+ )+ return+ from test_studio_tool_loop import FakeTransport, _sse, _DONE++ monkeypatch.setattr(studio_tool_loop, "wait_tool_decision", answer)+ monkeypatch.setattr(studio_tool_loop, "execute_tool", execute)+ monkeypatch.setattr(studio_tool_loop, "build_rag_autoinject", lambda *a, **k: None)+ turns = []+ for index in (1, 2):+ call = {+ "index": 0,+ "id": f"c{index}",+ "function": {"name": "python", "arguments": json.dumps({"code": f"print({index})"})},+ }+ turns.append([_sse({"tool_calls": [call]}), _sse(finish = "tool_calls"), _DONE])+ turns.append([_sse({"content": "ok"}), _sse(finish = "stop"), _DONE])++ async def collect():+ async for _ in studio_tool_loop.stream_with_studio_tools(+ FakeTransport(turns),+ run = studio_tool_loop.ToolLoopRun(+ messages = [{"role": "user", "content": "hi"}], session_id = session+ ),+ policy = studio_tool_loop.ToolLoopPolicy(+ tools = [tool],+ max_calls = 3,+ timeout = 300,+ permission_mode = "ask",+ confirm_calls = True,+ bypass_permissions = False,+ rag_scope = None,+ ),+ cancel_event = threading.Event(),+ ):+ pass++ asyncio.run(collect())++[email protected]("loop", ["safetensors", "llama_cpp", "studio"])[email protected]("upgrade", [False, True])+def test_current_and_later_calls_use_confirmed_live_permissions(monkeypatch, loop, upgrade):+ from test_api_key_tool_confirm import _client_for++ asks, executions = [], []++ def execute(name, arguments, **kwargs):+ executions.append(kwargs)+ return "OK"++ with _client_for(OWNER) as client:++ def answer(slot, approval_id, *args, **kwargs):+ asks.append(approval_id)+ response = client.post(+ "/api/inference/tool-confirm",+ json = {+ "approval_id": approval_id,+ "session_id": "chat-a",+ "decision": "allow",+ **({"permission_mode": "full"} if upgrade else {}),+ },+ )+ assert response.status_code == 200, response.text+ if upgrade:+ assert response.json()["full_access_granted"] is True+ return approvals.wait_tool_decision(slot, approval_id, timeout = 0.1)++ _run_two_calls(loop, monkeypatch, execute, answer)+ assert len(asks) == (1 if upgrade else 2)+ assert len(executions) == 2+ assert [call["disable_sandbox"] for call in executions] == [upgrade, upgrade]+ if upgrade:+ assert all(call.get("tool_execution_mode") != "required" for call in executions)+++def test_skill_preload_upgrade_uses_the_same_live_policy_for_later_mentions(monkeypatch):+ from core.inference import skill_mentions++ permissions = approvals.LiveToolPermissions("chat-a")+ asked = []+ monkeypatch.setattr(+ skill_mentions,+ "list_skills",+ lambda: [+ {"name": name, "valid": True, "shadowed": False, "enabled": True}+ for name in ("first", "second")+ ],+ )+ monkeypatch.setattr(+ skill_mentions, "read_skill_instructions", lambda name: f"Complete instructions for {name}"+ )++ def answer(slot, approval_id, **kwargs):+ asked.append(approval_id)+ assert approvals.resolve_tool_decision(+ approval_id, "allow", session_id = "chat-a", full_access = True+ )+ return approvals.wait_tool_decision(slot, approval_id, timeout = 0.1)++ monkeypatch.setattr(skill_mentions, "wait_tool_decision", answer)+ events = list(+ skill_mentions.load_mentioned_skills(+ [{"role": "user", "content": "@first @second"}],+ [{"function": {"name": "read_skill"}}],+ permission_mode = "ask",+ confirm_tool_calls = True,+ session_id = "chat-a",+ permission_upgrade = permissions,+ )+ )+ assert len(asked) == 1+ assert [event["name"] for event in events if event["status"] == "loaded"] == ["first", "second"]+ assert permissions.apply("ask", False) == ("full", True)+++class _AnswerDuringPoll(threading.Event):+ """The first poll times out just as a confirmation lands: the race a Stop or expiry meets."""++ def __init__(self, answer):+ super().__init__()+ self._answer = answer++ def wait(self, timeout = None):+ answer, self._answer = self._answer, None+ if answer is not None:+ answer()+ return False+ return super().wait(timeout)++[email protected]("full_access", [True, False])+def test_a_committed_allow_wins_over_a_concurrent_stop(full_access):+ cancel = threading.Event()+ approval_id, slot, permissions = _slot(cancel = cancel)++ def answer():+ assert approvals.resolve_tool_decision(+ approval_id, "allow", session_id = "chat-a", full_access = full_access+ )+ cancel.set()++ slot["event"] = _AnswerDuringPoll(answer)+ slot["event"].clear()+ verdict = approvals.wait_tool_decision(slot, approval_id, cancel_event = cancel)+ assert verdict == "allow"+ assert slot["reason"] == approvals.DECISION_ANSWERED+ assert permissions.apply("ask", False) == (("full", True) if full_access else ("ask", False))++[email protected]("full_access", [True, False])+def test_a_settled_expiry_refuses_a_late_confirmation(full_access):+ approval_id, slot, permissions = _slot()+ slot["reason"] = approvals.DECISION_EXPIRED+ assert not approvals.resolve_tool_decision(+ approval_id, "allow", session_id = "chat-a", full_access = full_access+ )+ assert not slot["event"].is_set() and slot["decision"] is None+ assert permissions.apply("ask", False) == ("ask", False)+++def test_gguf_skill_preload_and_tool_loop_share_one_live_permission():+ import ast++ source = (Path(__file__).resolve().parents[1] / "routes" / "inference.py").read_text(+ encoding = "utf-8"+ )+ fn = next(+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.FunctionDef) and node.name == "gguf_generate_with_tools"+ )+ passed = {+ call.func.attr if isinstance(call.func, ast.Attribute) else call.func.id: {+ kw.arg: ast.unparse(kw.value) for kw in call.keywords+ }+ for call in ast.walk(fn)+ if isinstance(call, ast.Call)+ and isinstance(call.func, (ast.Name, ast.Attribute))+ and (getattr(call.func, "id", None) or getattr(call.func, "attr", None))+ in ("load_mentioned_skills", "generate_chat_completion_with_tools")+ }+ assert passed["load_mentioned_skills"]["permission_upgrade"] == "gguf_live_permissions"+ assert (+ passed["generate_chat_completion_with_tools"]["live_permissions"] == "gguf_live_permissions"+ )diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex a93d285ec8a..6f5e7bf4883 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -432,8 +432,11 @@ export const BUDGET = {// 2,101,285 B transfer against 9c397197e0, Node 24, 106 -> 109 chunks). Raised by that growth.// Mermaid, node-forge and js-yaml load on first use: -998.5 KB raw / -260.1 KB transfer against 4e673d32e.// Lowered by that, so the headroom stays what it was and a regression of that size fails here.- transferBytes: 1_836_868,- rawBytes: 5_954_165,+ // Full Access from a tool approval card (#15485: per-chat grant store and the card's confirm dialog) adds+ // 5,293 B raw / 1,953 B transfer to the eager chat chunk (5,940,337 -> 5,945,630 B raw, 1,835,497 ->+ // 1,837,450 B transfer against 8222149ee, Node 24, 85 chunks). Raised by that growth.+ transferBytes: 1_838_821,+ rawBytes: 5_959_458,};// Chunk count is not budgeted: splitting a page out raises it while lowering bytes.diff --git a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsxindex b1c614ed898..61e50041493 100644--- a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx@@ -4,6 +4,11 @@"use client";import { Button } from "@/components/ui/button";+import { AlertDialog } from "@/components/ui/alert-dialog";+import { getAuthSessionEpoch } from "@/features/auth";+import { useFullAccessAllowed } from "@/features/auth/account-session";+import { FullAccessConfirmContent } from "@/features/chat/permission-mode-select";+import { hasChatFullAccess, withChatFullAccess } from "@/features/chat/utils/chat-full-access";import {resolveToolConfirmation,ToolApprovalGoneError,@@ -39,6 +44,15 @@ export function ToolConfirmationControls({? s.toolConfirmations[toolCallId]: undefined,);+ const fullAccessAllowed = useFullAccessAllowed();+ const permissionMode = useChatRuntimeStore((s) =>+ withChatFullAccess(s, s.chatFullAccessGrants, confirmation?.threadId).permissionMode,+ );+ const grantChatFullAccess = useChatRuntimeStore((s) => s.grantChatFullAccess);+ const chatFullAccess = useChatRuntimeStore((s) =>+ fullAccessAllowed && confirmation && !confirmation.imageDisclosure &&+ hasChatFullAccess(s.chatFullAccessGrants, confirmation.threadId, confirmation.runId),+ );const allowToolAlways = useChatRuntimeStore((s) => s.allowToolAlways);const clearToolConfirmation = useChatRuntimeStore((s) => s.clearToolConfirmation,@@ -52,6 +66,7 @@ export function ToolConfirmationControls({(s.alwaysAllowToolsBySession.get(autoAllowKey)?.has(toolName) ?? false),);+ const [fullAccessOpen, setFullAccessOpen] = useState(false);const [decided, setDecided] = useState(false);const [pending, setPending] = useState<"allow" | "deny" | null>(null);// "retry" can succeed on another press; "gone" means the backend no longer holds the approval.@@ -65,8 +80,10 @@ export function ToolConfirmationControls({const showControls = awaiting && !decided;const resolve = useCallback(- async (decision: "allow" | "deny", alsoAlways = false) => {+ async (decision: "allow" | "deny", alsoAlways = false, fullAccess = false) => {if (!toolCallId || !confirmation) return;+ const epoch = getAuthSessionEpoch();+ const choiceVersion = useChatRuntimeStore.getState().chatPermissionChoiceVersion;setPending(decision);setFailure(null);try {@@ -74,8 +91,20 @@ export function ToolConfirmationControls({confirmation.sessionId,confirmation.approvalId,decision,+ fullAccess,);- if (ok) {+ if (ok && getAuthSessionEpoch() === epoch) {+ if (fullAccess && confirmation.runId &&+ useChatRuntimeStore.getState().chatPermissionChoiceVersion === choiceVersion) {+ // Autosave may adopt the first turn while the POST is in flight.+ const current = useChatRuntimeStore.getState().toolConfirmations[toolCallId];+ const target = current?.approvalId === confirmation.approvalId ? current : confirmation;+ grantChatFullAccess({+ runId: confirmation.runId,+ sessionId: confirmation.sessionId,+ threadId: target.threadId,+ });+ }// Record the session grant only after the backend accepted, or a failed press auto-approves.if (alsoAlways && autoAllowKey) allowToolAlways(autoAllowKey, toolName);// Hide only once the backend confirms, or the generation stays blocked with no retry.@@ -95,16 +124,18 @@ export function ToolConfirmationControls({confirmation,clearToolConfirmation,allowToolAlways,+ grantChatFullAccess,autoAllowKey,toolName,],);useEffect(() => {- if (showControls && autoAllowed && pending === null && !failed) {- void resolve("allow");+ if (showControls && (autoAllowed || chatFullAccess) && pending === null && !failed) {+ // A sibling loop in this chat needs its own backend policy upgrade.+ void resolve("allow", false, !!chatFullAccess);}- }, [showControls, autoAllowed, pending, failed, resolve]);+ }, [showControls, autoAllowed, chatFullAccess, pending, failed, resolve]);// Chords only while this card asks and the chat is visible; with a second request parked, both// cards fall back to buttons.@@ -117,11 +148,12 @@ export function ToolConfirmationControls({const keyboardReady =!disclosure &&chatActive &&+ !fullAccessOpen &&soleRequest &&!selectionActive &&showControls &&pending === null &&- !(autoAllowed && !failed);+ !((autoAllowed || chatFullAccess) && !failed);// The Chat route stays mounted under a dialog, so `keyboardReady` still says// yes while the request is hidden behind one. Answering a tool call the user// cannot see must not be reachable by accident, so both chords ask here, before the key is taken.@@ -141,7 +173,7 @@ export function ToolConfirmationControls({if (!showControls) return null;// Auto-approved tools resolve silently unless the post fails.- if (autoAllowed && !failed) return null;+ if ((autoAllowed || chatFullAccess) && !failed) return null;return (<div className="flex flex-wrap items-center gap-2 pt-1">@@ -177,6 +209,27 @@ export function ToolConfirmationControls({>Deny</Button>+ {!disclosure && fullAccessAllowed && permissionMode !== "full" && confirmation?.sessionId && confirmation?.runId ? (+ <>+ <Button+ size="xs"+ variant="destructive"+ disabled={pending !== null || failure === "gone"}+ onClick={() => setFullAccessOpen(true)}+ >+ Full Access+ </Button>+ <AlertDialog open={fullAccessOpen} onOpenChange={setFullAccessOpen}>+ <FullAccessConfirmContent+ onConfirm={() => {+ setFullAccessOpen(false);+ void resolve("allow", false, true);+ }}+ onClose={() => setFullAccessOpen(false)}+ />+ </AlertDialog>+ </>+ ) : null}{failure !== null ? (<span className="text-xs text-destructive">{failure === "gone"diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 368ef980689..849d4dc9e7c 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -1,6 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { hasChatFullAccess, withChatFullAccess } from "../utils/chat-full-access";+import { attachedMediaUnavailableReason } from "../lib/attached-media-gate";import { readGenerationProgress } from "../lib/generation-progress";import { externalModelLabel } from "../lib/external-model-label";@@ -4970,6 +4972,7 @@ export function createOpenAIStreamAdapter(),}: liveRuntime;+ runtime = withChatFullAccess(runtime, liveRuntime.chatFullAccessGrants, resolvedThreadId);const { params } = runtime;const sandboxSessionId = await resolveSandboxSessionId(resolvedThreadId,@@ -5482,10 +5485,11 @@ export function createOpenAIStreamAdapter(? shownBrowserChat(): undefined;// A first turn files its handles under "__default" and autosave re-keys them mid-run, so resolve per use.- const liveThreadKey = (owner: () => void) =>- threadKey === "__default"- ? useChatRuntimeStore.getState().runKeyForOwner(threadKey, owner)- : threadKey;+ const liveThreadKey = (owner: () => void) => {+ const key = threadKey === "__default" ? useChatRuntimeStore.getState().runKeyForOwner(threadKey, owner) : threadKey;+ if (key !== "__default") useChatRuntimeStore.getState().adoptChatFullAccessRun(cancelId, key);+ return key;+ };// Per-run token so a delayed stop POST can't match the next run.const cancelId =@@ -7384,7 +7388,9 @@ export function createOpenAIStreamAdapter(// Resolved per action: a first turn is re-keyed from "__default" to its id.scope: liveThreadKey(serverCancel),userText,- fullAccess: bypassPermissions,+ fullAccess: (bypassPermissions && runtime.chatFullAccessPreviousMode === null) || hasChatFullAccess(+ useChatRuntimeStore.getState().chatFullAccessGrants, liveThreadKey(serverCancel), cancelId,+ ),temporary: browserTemporary,signal: runSignal,});@@ -7583,6 +7589,7 @@ export function createOpenAIStreamAdapter(toolConfirmationScopeId,confirmationThreadKey === "__default" ? "" : confirmationThreadKey,toolEvent.image_disclosure as ImageDisclosure | undefined,+ cancelId,);}} else if (toolEvent.type === "tool_end") {@@ -8952,6 +8959,7 @@ export function createOpenAIStreamAdapter(abortSignal.removeEventListener("abort", forwardAbort);// Resolve once: the clears below drop the owner the lookup keys on.const cleanupKey = liveThreadKey(serverCancel);+ useChatRuntimeStore.getState().clearUnadoptedChatFullAccessRun(cancelId);const confirmStore = useChatRuntimeStore.getState();for (const part of toolCallParts) {confirmStore.clearToolConfirmation(part.toolCallId);diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 9b6163ea2b9..c6770d74e09 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -555,7 +555,9 @@ export async function resolveToolConfirmation(sessionId: string,approvalId: string,decision: "allow" | "deny",+ fullAccess = false,): Promise<boolean> {+ const epoch = getAuthSessionEpoch();const response = await authFetch("/api/inference/tool-confirm", {method: "POST",headers: { "Content-Type": "application/json" },@@ -563,12 +565,15 @@ export async function resolveToolConfirmation(session_id: sessionId,approval_id: approvalId,decision,+ ...(fullAccess ? { permission_mode: "full" } : {}),}),});// Ahead of parseJsonOrThrow, which folds every non-ok status into one bare Error.if (response.status === 404) throw new ToolApprovalGoneError();- const parsed = await parseJsonOrThrow<{ resolved?: boolean }>(response);- return parsed.resolved === true;+ const parsed = await parseJsonOrThrow<{ resolved?: boolean; full_access_granted?: boolean }>(response);+ // An older server may allow this call while ignoring the requested upgrade.+ return getAuthSessionEpoch() === epoch && parsed.resolved === true &&+ (!fullAccess || parsed.full_access_granted === true);}export interface CachedGgufRepo {diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 0d33e72f7c5..b6729c4e146 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -1502,6 +1502,8 @@ function scheduleGenerationRecovery(sessionId,`${sessionId || "_default"}:${threadId}`,threadId,+ undefined,+ runId,),resolve: (partId) =>useChatRuntimeStore.getState().clearToolConfirmation(partId),diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex c3a5891134a..418993b55dc 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -2,6 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";+import { AUTH_SESSION_CLEARED_EVENT, AUTH_SESSION_STORED_EVENT } from "@/features/auth/session-events";+import {+ revokeChatFullAccess,+ withChatFullAccess,+ type ChatFullAccessGrant,+ type ChatFullAccessGrants,+} from "../utils/chat-full-access.ts";import { forgetThreadReads } from "../api/thread-read-cache.ts";import type { ImageDisclosure } from "../api/mcp-image";import {@@ -1983,6 +1990,22 @@ export function codeToolsOn();}+function chatFullAccessPermissionPatch(+ state: ChatRuntimeStore,+ grants: ChatFullAccessGrants,+ threadId: string | null,+) {+ const permissions = withChatFullAccess(state, grants, threadId);+ return {+ permissionMode: permissions.permissionMode,+ bypassPermissions: permissions.bypassPermissions,+ confirmToolCalls: permissions.confirmToolCalls,+ chatFullAccessPreviousMode: permissions.chatFullAccessPreviousMode,+ deepResearchEnabled: permissions.deepResearchEnabled,+ };+}++function loadString(key: string, fallback: string): string {return readStorageValue(key) ?? fallback;}@@ -2411,6 +2434,13 @@ type ChatRuntimeStore = {bypassPermissions: boolean;/** Source of truth; bypassPermissions and confirmToolCalls mirror it. */permissionMode: PermissionMode;+ /** A newer explicit permission choice wins over a delayed approval response. */+ chatPermissionChoiceVersion: number;+ chatFullAccessPreviousMode: Exclude<PermissionMode, "full"> | null;+ /** In-memory grants only: never saved in defaults, thread snapshots or browser storage. */+ chatFullAccessGrants: ChatFullAccessGrants;+ chatFullAccessPendingRunId: string | null;+ chatFullAccessThreadByRunId: Record<string, string>;sandboxLevel: SandboxLevel;/** Whether the bypass warning dialog is open. Lifted out of the composer menu so confirming* it does not leave the menu frozen. */@@ -2428,6 +2458,7 @@ type ChatRuntimeStore = {autoAllowKey: string;threadId: string;imageDisclosure?: ImageDisclosure;+ runId?: string;}>;webFetchToolsEnabled: boolean;@@ -2644,6 +2675,10 @@ type ChatRuntimeStore = {setConfirmToolCalls: (enabled: boolean) => void;setBypassPermissions: (enabled: boolean) => void;setPermissionMode: (mode: PermissionMode) => void;+ grantChatFullAccess: (grant: ChatFullAccessGrant) => void;+ adoptChatFullAccessRun: (runId: string, threadId: string) => void;+ clearUnadoptedChatFullAccessRun: (runId: string) => void;+ clearChatFullAccessGrants: () => void;setSandboxLevel: (level: SandboxLevel) => void;setBypassConfirmOpen: (open: boolean) => void;allowToolAlways: (sessionId: string, toolName: string) => void;@@ -2654,6 +2689,7 @@ type ChatRuntimeStore = {autoAllowKey: string,threadId: string,imageDisclosure?: ImageDisclosure,+ runId?: string,) => void;clearToolConfirmation: (toolCallId: string) => void;setWebFetchToolsEnabled: (enabled: boolean) => void;@@ -4185,6 +4221,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({// no stored bypass: sandbox and gate removal needs a warning each session.bypassPermissions: false,permissionMode: INITIAL_PERMISSION_MODE,+ chatPermissionChoiceVersion: 0,+ chatFullAccessPreviousMode: null,+ chatFullAccessGrants: {},+ chatFullAccessPendingRunId: null,+ chatFullAccessThreadByRunId: {},sandboxLevel: loadSandboxLevel(),bypassConfirmOpen: false,alwaysAllowToolsBySession: new Map<string, Set<string>>(),@@ -4907,7 +4948,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({? (state.contextUsageByThreadId[activeThreadId] ?? null): null;return {+ ...chatFullAccessPermissionPatch(state, state.chatFullAccessGrants, activeThreadId),activeThreadId,+ chatFullAccessPendingRunId: null,activeThreadEpoch: state.activeThreadEpoch + 1,contextUsage:own && own.modelId && own.modelId !== state.params.checkpoint ? null : own,@@ -5021,7 +5064,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({stored?.permissionMode ??globalThreadScopedDefaults?.permissionMode ??loadPermissionMode();- if (underneath !== "full") applied[key] = underneath;+ if (underneath !== "full") {+ applied[key] = underneath;+ if (state.chatFullAccessPreviousMode !== null) nextState.chatFullAccessPreviousMode = underneath;+ }continue;}// A key the snapshot omits falls back to the defaults, not to the outgoing chat's value.@@ -5393,6 +5439,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({webFetchToolsEnabled: false,bypassPermissions: false,permissionMode,+ chatFullAccessPreviousMode: null,+ chatPermissionChoiceVersion: state.chatPermissionChoiceVersion + 1,+ chatFullAccessPendingRunId: null,+ chatFullAccessGrants: revokeChatFullAccess(state.chatFullAccessGrants, state.activeThreadId, state.chatFullAccessPendingRunId),confirmToolCalls:permissionMode === "ask" || permissionMode === "auto",queuedSettingsEpoch: state.queuedSettingsEpoch + 1,@@ -5470,6 +5520,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({if (state.permissionMode === "full") {return {confirmToolCalls,+ chatPermissionChoiceVersion: state.chatPermissionChoiceVersion + 1,queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}@@ -5478,6 +5529,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({return {confirmToolCalls,permissionMode,+ chatPermissionChoiceVersion: state.chatPermissionChoiceVersion + 1,queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}),@@ -5494,10 +5546,12 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);return {permissionMode,+ chatFullAccessPreviousMode: null,bypassPermissions: true,confirmToolCalls: false,deepResearchEnabled: false,codeToolsDeclinedUnderFullAccess: codeDeclinedOnEnteringFullAccess(state),+ chatPermissionChoiceVersion: state.chatPermissionChoiceVersion + 1,queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}@@ -5506,9 +5560,13 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({saveBool(CHAT_CONFIRM_TOOL_CALLS_KEY, confirmToolCalls);return {permissionMode,+ chatFullAccessPreviousMode: null,+ chatFullAccessPendingRunId: null,+ chatFullAccessGrants: revokeChatFullAccess(state.chatFullAccessGrants, state.activeThreadId, state.chatFullAccessPendingRunId),bypassPermissions: false,confirmToolCalls,codeToolsDeclinedUnderFullAccess: false,+ chatPermissionChoiceVersion: state.chatPermissionChoiceVersion + 1,queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}),@@ -5520,9 +5578,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({return {bypassPermissions,permissionMode: "full" as PermissionMode,+ chatFullAccessPreviousMode: null,confirmToolCalls: false,deepResearchEnabled: false,codeToolsDeclinedUnderFullAccess: codeDeclinedOnEnteringFullAccess(state),+ chatPermissionChoiceVersion: state.chatPermissionChoiceVersion + 1,queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}@@ -5531,8 +5591,77 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({return {bypassPermissions,permissionMode,+ chatFullAccessPreviousMode: null,+ chatFullAccessPendingRunId: null,+ chatFullAccessGrants: revokeChatFullAccess(state.chatFullAccessGrants, state.activeThreadId, state.chatFullAccessPendingRunId),confirmToolCalls: permissionMode === "ask" || permissionMode === "auto",codeToolsDeclinedUnderFullAccess: false,+ chatPermissionChoiceVersion: state.chatPermissionChoiceVersion + 1,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),+ grantChatFullAccess: (grant) =>+ set((state) => {+ if (!grant.runId || !grant.sessionId) return state;+ grant = {+ ...grant,+ threadId: grant.threadId || state.chatFullAccessThreadByRunId[grant.runId] || "",+ choiceVersion: state.chatPermissionChoiceVersion,+ };+ const grants = { ...state.chatFullAccessGrants, [grant.runId]: grant };+ return {+ chatFullAccessGrants: grants,+ chatFullAccessPendingRunId: !grant.threadId && state.activeThreadId === null+ ? grant.runId : state.chatFullAccessPendingRunId,+ ...chatFullAccessPermissionPatch(state, grants, state.activeThreadId),+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),+ adoptChatFullAccessRun: (runId, threadId) =>+ set((state) => {+ if (!runId || !threadId || threadId === "__default") return state;+ const grant = state.chatFullAccessGrants[runId];+ const recorded = state.chatFullAccessThreadByRunId[runId];+ if (recorded && recorded !== threadId) return state;+ const runThreads = recorded+ ? state.chatFullAccessThreadByRunId+ : { ...state.chatFullAccessThreadByRunId, [runId]: threadId };+ if (!grant || grant.threadId) return recorded ? state : { chatFullAccessThreadByRunId: runThreads };+ const grants = { ...state.chatFullAccessGrants };+ if (grant.choiceVersion === state.chatPermissionChoiceVersion) grants[runId] = { ...grant, threadId };+ else delete grants[runId];+ return {+ chatFullAccessGrants: grants,+ chatFullAccessThreadByRunId: runThreads,+ chatFullAccessPendingRunId: state.chatFullAccessPendingRunId === runId ? null : state.chatFullAccessPendingRunId,+ ...chatFullAccessPermissionPatch(state, grants, state.activeThreadId),+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),+ clearUnadoptedChatFullAccessRun: (runId) =>+ set((state) => {+ // The run's thread mapping stays: a first-turn upgrade acknowledged after the run ended binds through it.+ const grant = state.chatFullAccessGrants[runId];+ if (!grant || grant.threadId) return state;+ const grants = { ...state.chatFullAccessGrants };+ delete grants[runId];+ return {+ chatFullAccessGrants: grants,+ chatFullAccessPendingRunId: state.chatFullAccessPendingRunId === runId+ ? null : state.chatFullAccessPendingRunId,+ };+ }),+ clearChatFullAccessGrants: () =>+ set((state) => {+ const permissions = withChatFullAccess(state, {}, state.activeThreadId);+ return {+ chatFullAccessGrants: {},+ chatFullAccessPendingRunId: null,+ chatFullAccessThreadByRunId: {},+ permissionMode: permissions.permissionMode,+ bypassPermissions: permissions.bypassPermissions,+ confirmToolCalls: permissions.confirmToolCalls,+ chatFullAccessPreviousMode: null,queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}),@@ -5553,6 +5682,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({autoAllowKey,threadId,imageDisclosure,+ runId,) =>set((state) => ({toolConfirmations: {@@ -5563,6 +5693,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({autoAllowKey,threadId,imageDisclosure,+ runId,},},})),@@ -6010,9 +6141,19 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({}),}));+const clearChatFullAccessOnAuthChange = () => useChatRuntimeStore.getState().clearChatFullAccessGrants();+if (typeof window !== "undefined" && typeof window.addEventListener === "function") {+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, clearChatFullAccessOnAuthChange);+ window.addEventListener(AUTH_SESSION_STORED_EVENT, clearChatFullAccessOnAuthChange);+}+const unsubscribeHfTokenMirror = mirrorHfTokenInto(useChatRuntimeStore);if (import.meta.hot) {import.meta.hot.dispose(unsubscribeHfTokenMirror);+ import.meta.hot.dispose(() => {+ window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, clearChatFullAccessOnAuthChange);+ window.removeEventListener(AUTH_SESSION_STORED_EVENT, clearChatFullAccessOnAuthChange);+ });}export function resolveSpeculativeSettingsForLoad({diff --git a/studio/frontend/src/features/chat/utils/chat-full-access.ts b/studio/frontend/src/features/chat/utils/chat-full-access.tsnew file mode 100644index 00000000000..b797a316c6b--- /dev/null+++ b/studio/frontend/src/features/chat/utils/chat-full-access.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export interface ChatFullAccessGrant {+ runId: string;+ threadId: string;+ sessionId: string;+ /** chatPermissionChoiceVersion when granted: a later explicit choice voids an unadopted grant. */+ choiceVersion?: number;+}++export type ChatFullAccessGrants = Readonly<Record<string, ChatFullAccessGrant>>;++/** Workspace sessions can be shared by multiple chats; they never identify a grant by themselves. */+export function hasChatFullAccess(+ grants: ChatFullAccessGrants,+ threadId: string | null | undefined,+ runId?: string,+): boolean {+ const ownRun = runId && Object.hasOwn(grants, runId) ? grants[runId] : undefined;+ return !!(+ (ownRun && (!ownRun.threadId || ownRun.threadId === threadId)) ||+ (threadId && Object.values(grants).some((grant) => grant.threadId === threadId))+ );+}++type BasePermissionMode = "auto" | "ask" | "off";+interface PermissionState {+ permissionMode: BasePermissionMode | "full";+ bypassPermissions: boolean;+ confirmToolCalls: boolean;+ deepResearchEnabled: boolean;+ /** Base mode displaced by this chat shortcut; null means no active chat overlay. */+ chatFullAccessPreviousMode: BasePermissionMode | null;+}++/** Overlay a live chat grant on queued or current settings without inheriting another chat's bypass. */+export function withChatFullAccess<T extends PermissionState>(+ state: T,+ grants: ChatFullAccessGrants,+ threadId: string | null | undefined,+): T {+ if (state.permissionMode === "full" && state.chatFullAccessPreviousMode === null) return state;+ if (hasChatFullAccess(grants, threadId)) {+ return {+ ...state,+ chatFullAccessPreviousMode: state.permissionMode === "full"+ ? state.chatFullAccessPreviousMode+ : state.permissionMode,+ permissionMode: "full",+ bypassPermissions: true,+ confirmToolCalls: false,+ deepResearchEnabled: false,+ };+ }+ if (state.chatFullAccessPreviousMode !== null) {+ const mode = state.permissionMode === "full" ? state.chatFullAccessPreviousMode : state.permissionMode;+ return {+ ...state,+ chatFullAccessPreviousMode: null,+ permissionMode: mode,+ bypassPermissions: false,+ confirmToolCalls: mode === "ask" || mode === "auto",+ };+ }+ return state;+}++export function revokeChatFullAccess(+ grants: ChatFullAccessGrants,+ threadId: string | null,+ runId?: string | null,+): ChatFullAccessGrants {+ return Object.fromEntries(Object.entries(grants).filter(([key, grant]) =>+ threadId ? grant.threadId !== threadId : !runId || key !== runId,+ ));+}diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.tsindex 8ba491533b1..3989b33ce2d 100644--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts@@ -23,6 +23,7 @@ const QUEUED_SETTING_KEYS = ["confirmToolCalls","bypassPermissions","permissionMode",+ "chatFullAccessPreviousMode","sandboxLevel","webFetchToolsEnabled","deepResearchEnabled",diff --git a/studio/frontend/tests/approval-waiting.test.ts b/studio/frontend/tests/approval-waiting.test.tsindex 2eb35da9c76..0ef624f935b 100644--- a/studio/frontend/tests/approval-waiting.test.ts+++ b/studio/frontend/tests/approval-waiting.test.ts@@ -186,7 +186,7 @@ test("both writers record which chat a parked call belongs to", () => {const provider = readSrc("features/chat/runtime-provider.tsx");assert.match(provider,- /\.setToolConfirmation\(\s*partId,\s*approvalId,\s*sessionId,\s*`\$\{sessionId \|\| "_default"\}:\$\{threadId\}`,\s*threadId,\s*\)/,+ /\.setToolConfirmation\(\s*partId,\s*approvalId,\s*sessionId,\s*`\$\{sessionId \|\| "_default"\}:\$\{threadId\}`,\s*threadId,\s*undefined,\s*runId,\s*\)/,);});diff --git a/studio/frontend/tests/chat-full-access-store.test.ts b/studio/frontend/tests/chat-full-access-store.test.tsnew file mode 100644index 00000000000..1ec5a286c42--- /dev/null+++ b/studio/frontend/tests/chat-full-access-store.test.ts@@ -0,0 +1,171 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+import { installLocalStorageFake } from "./helpers/kit.ts";++const browser = installLocalStorageFake();+browser.store.set("unsloth_chat_settings_imported_to_studio_db", "true");+register("./thread-sampling-resolver.mjs", import.meta.url);+const STORE = new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url).href;+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");+type Runtime = typeof import("../src/features/chat/stores/chat-runtime-store.ts");++async function boot(name: string) {+ settingsHttp.settings = {};+ settingsHttp.puts.length = 0;+ const module = await import(`${STORE}?scenario=${name}`) as Runtime;+ const state = () => module.useChatRuntimeStore.getState();+ state().setPermissionMode("auto");+ return { ...module, state };+}++const grant = { runId: "run-a", threadId: "chat-a", sessionId: "project-shared" };++test("a confirmed shortcut affects its chat, survives revisit, and never persists Full access", async () => {+ const { state } = await boot("chat-full-scope");+ state().setActiveThreadId("chat-a");+ state().applyThreadScopedSettings("chat-a", { permissionMode: "ask" });+ const before = new Map(browser.store);+ const writes = settingsHttp.puts.length;+ state().grantChatFullAccess(grant);+ assert.equal(state().permissionMode, "full");+ assert.equal(state().bypassPermissions, true);+ assert.equal(state().confirmToolCalls, false);+ assert.equal(state().chatFullAccessPreviousMode, "ask");+ assert.deepEqual(browser.store, before);+ assert.equal(settingsHttp.puts.length, writes);++ state().setActiveThreadId("chat-b");+ state().applyThreadScopedSettings("chat-b", { permissionMode: "off" });+ assert.equal(state().permissionMode, "off");+ assert.equal(state().bypassPermissions, false);+ state().setActiveThreadId("chat-a");+ state().applyThreadScopedSettings("chat-a", { permissionMode: "ask" });+ assert.equal(state().permissionMode, "full");+ state().setPermissionMode("ask");+ assert.equal(state().bypassPermissions, false);+ assert.equal(Object.keys(state().chatFullAccessGrants).length, 0);+ state().setActiveThreadId("chat-b");+ state().setActiveThreadId("chat-a");+ assert.equal(state().permissionMode, "ask");+});++test("an acknowledgment after navigation grants the original chat only", async () => {+ const { state } = await boot("chat-full-late-ack");+ state().setActiveThreadId("chat-b");+ state().grantChatFullAccess(grant);+ assert.equal(state().permissionMode, "auto");+ state().setActiveThreadId("chat-a");+ assert.equal(state().permissionMode, "full");+});++test("parallel unsaved runs are bound separately when their first turns are adopted", async () => {+ const { state } = await boot("chat-full-adoption");+ state().grantChatFullAccess({ ...grant, threadId: "" });+ state().grantChatFullAccess({ ...grant, threadId: "", runId: "run-b" });+ assert.equal(state().permissionMode, "auto", "an unknown thread cannot grant every new chat");+ state().adoptChatFullAccessRun("run-a", "chat-a");+ assert.equal(state().chatFullAccessGrants["run-a"]!.threadId, "chat-a");+ assert.equal(state().chatFullAccessGrants["run-b"]!.threadId, "");+ state().setActiveThreadId("chat-a");+ assert.equal(state().permissionMode, "full");+ state().clearUnadoptedChatFullAccessRun("run-a");+ assert.ok(state().chatFullAccessGrants["run-a"], "completed saved chats retain the grant for future turns");+ state().clearUnadoptedChatFullAccessRun("run-b");+ assert.equal(state().chatFullAccessGrants["run-b"], undefined);+ state().setActiveThreadId(null);+ assert.equal(state().permissionMode, "auto");+});++test("lowering an unsaved chat revokes its own active run only", async () => {+ const { state } = await boot("chat-full-revoke-unbound");+ state().grantChatFullAccess({ ...grant, threadId: "", runId: "background-run" });+ state().grantChatFullAccess({ ...grant, threadId: "", runId: "visible-run" });+ state().setPermissionMode("ask");+ assert.ok(state().chatFullAccessGrants["background-run"]);+ assert.equal(state().chatFullAccessGrants["visible-run"], undefined);+});++test("authentication changes and a reload discard ephemeral chat grants", async () => {+ const { state } = await boot("chat-full-account");+ state().setActiveThreadId("chat-a");+ state().grantChatFullAccess(grant);+ browser.fireWindowEvent("unsloth:auth-session-cleared", {});+ assert.deepEqual(state().chatFullAccessGrants, {});+ assert.notEqual(state().permissionMode, "full");+ const reload = await boot("chat-full-after-reload");+ assert.deepEqual(reload.state().chatFullAccessGrants, {});+ assert.notEqual(reload.state().permissionMode, "full");+});++test("the existing dropdown Full access remains session-wide", async () => {+ const { state } = await boot("chat-full-global-dropdown");+ state().setPermissionMode("full");+ state().setActiveThreadId("chat-a");+ state().setActiveThreadId("chat-b");+ assert.equal(state().permissionMode, "full");+ assert.equal(state().chatFullAccessPreviousMode, null);+});+++test("an acknowledgment after first-turn adoption still binds to the original chat", async () => {+ const { state } = await boot("chat-full-late-adoption-ack");+ state().adoptChatFullAccessRun("run-a", "chat-a");+ state().setActiveThreadId("chat-b");+ state().grantChatFullAccess({ ...grant, threadId: "" });+ assert.equal(state().chatFullAccessGrants["run-a"]!.threadId, "chat-a");+ assert.equal(state().permissionMode, "auto");+ state().setActiveThreadId("chat-a");+ assert.equal(state().permissionMode, "full");+});+++test("only explicit permission changes advance the version used by pending upgrades", async () => {+ const { state } = await boot("chat-full-choice-version");+ const first = state().chatPermissionChoiceVersion;+ state().setActiveThreadId("chat-a");+ state().grantChatFullAccess(grant);+ state().adoptChatFullAccessRun("run-a", "chat-a");+ assert.equal(state().chatPermissionChoiceVersion, first);+ state().setPermissionMode("off");+ assert.equal(state().chatPermissionChoiceVersion, first + 1);+ state().setBypassPermissions(false);+ assert.equal(state().chatPermissionChoiceVersion, first + 2);+});++test("a lower mode chosen before first-turn adoption is not undone by the adoption", async () => {+ const { state } = await boot("chat-full-revoke-before-adopt");+ state().grantChatFullAccess({ runId: "run-new", threadId: "", sessionId: "project-shared" });+ assert.ok(state().chatFullAccessGrants["run-new"]);+ state().setActiveThreadId("chat-a");+ state().setPermissionMode("off");+ state().adoptChatFullAccessRun("run-new", "chat-a");+ assert.equal(state().permissionMode, "off");+ assert.equal(state().bypassPermissions, false);+ assert.equal(Object.keys(state().chatFullAccessGrants).length, 0);+});++test("runs that never used the shortcut do not churn queued settings", async () => {+ const { state } = await boot("chat-full-run-cleanup");+ state().setActiveThreadId("chat-a");+ const epoch = state().queuedSettingsEpoch;+ for (let i = 0; i < 3; i++) {+ state().adoptChatFullAccessRun(`run-${i}`, "chat-a");+ state().clearUnadoptedChatFullAccessRun(`run-${i}`);+ }+ assert.equal(state().queuedSettingsEpoch, epoch);+ assert.deepEqual(state().chatFullAccessGrants, {});+});++test("a first-turn upgrade acknowledged after its run ended still binds to the adopted chat", async () => {+ const { state } = await boot("chat-full-late-ack-after-run");+ state().adoptChatFullAccessRun("run-late", "chat-a");+ state().clearUnadoptedChatFullAccessRun("run-late");+ state().grantChatFullAccess({ runId: "run-late", threadId: "", sessionId: "project-shared" });+ assert.equal(state().chatFullAccessGrants["run-late"]!.threadId, "chat-a");+ state().setActiveThreadId("chat-a");+ assert.equal(state().permissionMode, "full");+});diff --git a/studio/frontend/tests/chat-full-access.test.ts b/studio/frontend/tests/chat-full-access.test.tsnew file mode 100644index 00000000000..5fd97c7a41c--- /dev/null+++ b/studio/frontend/tests/chat-full-access.test.ts@@ -0,0 +1,121 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import {+ hasChatFullAccess,+ revokeChatFullAccess,+ withChatFullAccess,+ type ChatFullAccessGrants,+} from "../src/features/chat/utils/chat-full-access.ts";++const grants: ChatFullAccessGrants = {+ "run-a": { runId: "run-a", threadId: "chat-a", sessionId: "shared-project" },+};++function base(permissionMode: "auto" | "ask" | "off" = "auto") {+ return {+ permissionMode: permissionMode as "auto" | "ask" | "off" | "full",+ bypassPermissions: false,+ confirmToolCalls: permissionMode !== "off",+ deepResearchEnabled: false,+ chatFullAccessPreviousMode: null as "auto" | "ask" | "off" | null,+ };+}++test("a chat grant follows later turns without granting other chats in the same project", () => {+ assert.equal(hasChatFullAccess(grants, "chat-a", "later-run"), true);+ assert.equal(hasChatFullAccess(grants, "chat-b", "run-b"), false);+ assert.equal(hasChatFullAccess(grants, "chat-b", "run-a"), false);+ assert.equal(hasChatFullAccess(grants, null), false);+});++test("an unsaved chat grant belongs only to its unique run", () => {+ const pending = {+ "run-a": { runId: "run-a", threadId: "", sessionId: "shared-project" },+ };+ assert.equal(hasChatFullAccess(pending, null, "run-a"), true);+ assert.equal(hasChatFullAccess(pending, null, "run-b"), false);+ assert.equal(hasChatFullAccess(pending, null), false);+ assert.equal(hasChatFullAccess(pending, "chat-b"), false);+});++test("the confirmed grant updates all permission flags for its chat", () => {+ const before = base("ask");+ const full = withChatFullAccess(before, grants, "chat-a");+ assert.equal(full.permissionMode, "full");+ assert.equal(full.bypassPermissions, true);+ assert.equal(full.confirmToolCalls, false);+ assert.equal(full.chatFullAccessPreviousMode, "ask");+ assert.equal(full.deepResearchEnabled, false);+ assert.equal(before.permissionMode, "ask");+});++test("switching away restores the underlying mode without inheriting the bypass", () => {+ const full = withChatFullAccess(base("auto"), grants, "chat-a");+ const other = withChatFullAccess(full, grants, "chat-b");+ assert.equal(other.permissionMode, "auto");+ assert.equal(other.bypassPermissions, false);+ assert.equal(other.confirmToolCalls, true);+ assert.equal(other.chatFullAccessPreviousMode, null);+ assert.equal(withChatFullAccess(other, grants, "chat-a").permissionMode, "full");+});++test("an incoming queued chat keeps its own non-full permission mode", () => {+ const queued = {+ ...base("ask"),+ chatFullAccessPreviousMode: "auto" as const,+ };+ const other = withChatFullAccess(queued, grants, "chat-b");+ assert.equal(other.permissionMode, "ask");+ assert.equal(other.bypassPermissions, false);+ assert.equal(other.chatFullAccessPreviousMode, null);+});++test("a queued granted chat remembers its own underlying mode", () => {+ const queued = { ...base("off"), chatFullAccessPreviousMode: "auto" as const };+ const full = withChatFullAccess(queued, grants, "chat-a");+ assert.equal(full.permissionMode, "full");+ assert.equal(full.chatFullAccessPreviousMode, "off");+ assert.equal(withChatFullAccess(full, {}, "chat-a").permissionMode, "off");+});++test("revoking a chat removes all its runs and preserves other chat grants", () => {+ const both: ChatFullAccessGrants = {+ ...grants,+ "run-a2": { runId: "run-a2", threadId: "chat-a", sessionId: "shared-project" },+ "run-b": { runId: "run-b", threadId: "chat-b", sessionId: "shared-project" },+ };+ const revoked = revokeChatFullAccess(both, "chat-a");+ assert.equal(hasChatFullAccess(revoked, "chat-a"), false);+ assert.equal(hasChatFullAccess(revoked, "chat-b"), true);+ assert.equal(hasChatFullAccess(both, "chat-a"), true);+});++test("revoking an unsaved chat targets one run rather than every unsaved chat", () => {+ const pending: ChatFullAccessGrants = {+ "run-a": { runId: "run-a", threadId: "", sessionId: "shared-project" },+ "run-b": { runId: "run-b", threadId: "", sessionId: "shared-project" },+ };+ const revoked = revokeChatFullAccess(pending, null, "run-a");+ assert.equal(hasChatFullAccess(revoked, null, "run-a"), false);+ assert.equal(hasChatFullAccess(revoked, null, "run-b"), true);+});++test("an unrelated blank composer cannot revoke grants belonging to unsaved runs", () => {+ const pending: ChatFullAccessGrants = {+ "run-a": { runId: "run-a", threadId: "", sessionId: "shared-project" },+ };+ assert.deepEqual(revokeChatFullAccess(pending, null), pending);+});++test("the existing session-wide dropdown grant keeps its behavior", () => {+ const global = {+ ...base("ask"), permissionMode: "full" as const,+ bypassPermissions: true, confirmToolCalls: false,+ };+ assert.equal(withChatFullAccess(global, {}, "chat-b"), global);+ assert.equal(withChatFullAccess(global, grants, "chat-a"), global);+});diff --git a/studio/frontend/tests/generation-tool-recovery.test.ts b/studio/frontend/tests/generation-tool-recovery.test.tsindex 4abf9c41f14..80905ba5d92 100644--- a/studio/frontend/tests/generation-tool-recovery.test.ts+++ b/studio/frontend/tests/generation-tool-recovery.test.ts@@ -383,6 +383,7 @@ test("the live adapter saves identities for ordinary, approval and provider card: [];const confirmed: string[] = [];const confirmedThreads: string[] = [];+ const confirmedRuns: string[] = [];const context = vm.createContext({toolCallParts: parts,toolPartIdByBackendId: new Map(@@ -395,6 +396,7 @@ test("the live adapter saves identities for ordinary, approval and provider card// The run's key when the call parks, which can differ from the one captured at send.serverCancel: () => {},liveThreadKey: () => "thread-live",+ cancelId: "cancel-1",generationRunId,generationSeq: 7,cumulativeText: "",@@ -415,9 +417,12 @@ test("the live adapter saves identities for ordinary, approval and provider card_sessionId: string,_scopeId: string,threadId: string,+ _imageDisclosure: unknown,+ runId: string,) => {confirmed.push(id);confirmedThreads.push(threadId);+ confirmedRuns.push(runId);},}),},@@ -457,6 +462,7 @@ test("the live adapter saves identities for ordinary, approval and provider cardconfirmedThreads,kind === "approval" ? ["thread-live"] : [],);+ assert.deepEqual(confirmedRuns, kind === "approval" ? ["cancel-1"] : []);const carried = [{ at: 0, part: saved }];const replay = createGenerationToolRecovery(carried, "run", 7);assert.equal(replay.replayFrom, 7);diff --git a/studio/frontend/tests/shortcut-layout-and-recorder.test.ts b/studio/frontend/tests/shortcut-layout-and-recorder.test.tsindex 89936c843b3..552a31a7b55 100644--- a/studio/frontend/tests/shortcut-layout-and-recorder.test.ts+++ b/studio/frontend/tests/shortcut-layout-and-recorder.test.ts@@ -347,7 +347,7 @@ test("Escape in the composer is left to a mounted, keyboard-ready decline", () =);assert.match(controls,- /const keyboardReady =\n\s*!disclosure &&\n\s*chatActive &&\n\s*soleRequest &&/,+ /const keyboardReady =\n\s*!disclosure &&\n\s*chatActive &&\n\s*!fullAccessOpen &&\n\s*soleRequest &&/,);});diff --git a/studio/frontend/tests/tool-approval-gone.test.ts b/studio/frontend/tests/tool-approval-gone.test.tsindex 61c2005ca10..74aba729e13 100644--- a/studio/frontend/tests/tool-approval-gone.test.ts+++ b/studio/frontend/tests/tool-approval-gone.test.ts@@ -14,6 +14,7 @@ type Module = {sessionId: string,approvalId: string,decision: "allow" | "deny",+ fullAccess?: boolean,) => Promise<boolean>;ToolApprovalGoneError: new (message?: string) => Error;};@@ -29,7 +30,7 @@ function jsonResponse(status: number, body: unknown) {};}-function harness(response: ReturnType<typeof jsonResponse>) {+function harness(response: ReturnType<typeof jsonResponse>, epoch = { value: 0 }) {const requests: { url: string; init?: RequestInit }[] = [];const module = loadWithStubs<Module>(new URL("../src/features/chat/api/chat-api.ts", import.meta.url),@@ -40,6 +41,7 @@ function harness(response: ReturnType<typeof jsonResponse>) {{},),"@/features/auth": {+ getAuthSessionEpoch: () => epoch.value,authFetch: async (url: string, init?: RequestInit) => {requests.push({ url, init });return response;@@ -138,7 +140,7 @@ test("the gone case gets its own copy and does not tell the user to retry", () =test("a decision that is gone disables the buttons instead of inviting another 404", () => {const disabled = CONTROLS.match(/disabled=\{pending !== null[^}]*\}/g) ?? [];- assert.equal(disabled.length, 3, "all three buttons carry a disabled expression");+ assert.equal(disabled.length, 4, "approval buttons and the Full Access shortcut share the gone gate");for (const expr of disabled) {assert.match(expr,@@ -162,3 +164,24 @@ test("Always allow records its session grant only after the backend takes the de"Always allow must route through resolve so the grant follows the backend's answer",);});+++test("Full Access needs an explicit server acknowledgment, including on an older backend", async () => {+ for (const body of [{ resolved: true }, { resolved: false, full_access_granted: true }]) {+ const { module } = harness(jsonResponse(200, body));+ assert.equal(await module.resolveToolConfirmation("sess", "a1", "allow", true), false);+ }+ const { module, requests } = harness(jsonResponse(200, { resolved: true, full_access_granted: true }));+ assert.equal(await module.resolveToolConfirmation("sess", "a1", "allow", true), true);+ assert.deepEqual(JSON.parse(String(requests[0]!.init!.body)), {+ session_id: "sess", approval_id: "a1", decision: "allow", permission_mode: "full",+ });+});++test("a Full Access acknowledgment cannot cross an authentication session change", async () => {+ const epoch = { value: 0 };+ const response = jsonResponse(200, { resolved: true, full_access_granted: true });+ response.json = async () => { epoch.value += 1; return { resolved: true, full_access_granted: true }; };+ const { module } = harness(response, epoch);+ assert.equal(await module.resolveToolConfirmation("sess", "a1", "allow", true), false);+});diff --git a/studio/frontend/tests/tool-full-access-controls.test.ts b/studio/frontend/tests/tool-full-access-controls.test.tsnew file mode 100644index 00000000000..ed3f3a2db85--- /dev/null+++ b/studio/frontend/tests/tool-full-access-controls.test.ts@@ -0,0 +1,185 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { loadWithStubs, stubJsxRuntime, type StubElement } from "./helpers/module-stubs.ts";+import { hasChatFullAccess, withChatFullAccess, type ChatFullAccessGrant } from "../src/features/chat/utils/chat-full-access.ts";++type Node = StubElement;+function descendants(node: unknown): Node[] {+ if (Array.isArray(node)) return node.flatMap(descendants);+ if (!node || typeof node !== "object" || !("props" in node)) return [];+ const element = node as Node;+ return [element, ...descendants(element.props.children)];+}++function harness({ owner = true, disclosure = false, grantedThread = "", scopedFull = false } = {}) {+ const requests: unknown[][] = [], grants: ChatFullAccessGrant[] = [];+ const values: unknown[] = [];+ let index = 0, epoch = 0;+ let effects: Array<() => void> = [];+ let answer: () => Promise<boolean> = async () => true;+ const confirmation = {+ approvalId: "approval-a", sessionId: "project-shared", threadId: "chat-a",+ runId: "run-a", autoAllowKey: "project-shared:chat-a",+ ...(disclosure ? { imageDisclosure: { size_bytes: 1, server: "remote", tool: "view", destination: "outside" } } : {}),+ };+ const state = {+ toolConfirmations: { call: confirmation } as Record<string, typeof confirmation>,+ permissionMode: scopedFull ? "full" : "ask",+ chatFullAccessPreviousMode: scopedFull ? "ask" : null,+ bypassPermissions: scopedFull,+ confirmToolCalls: !scopedFull,+ deepResearchEnabled: false,+ chatPermissionChoiceVersion: 0,+ chatFullAccessGrants: grantedThread ? { other: { runId: "other", threadId: grantedThread, sessionId: "project-shared" } } : {},+ alwaysAllowToolsBySession: new Map(),+ allowToolAlways: () => {},+ grantChatFullAccess: (grant: ChatFullAccessGrant) => { grants.push(grant); },+ clearToolConfirmation: (id: string) => { delete state.toolConfirmations[id]; },+ };+ const store = Object.assign((selector: (s: typeof state) => unknown) => selector(state), { getState: () => state });+ const module = loadWithStubs<{ ToolConfirmationControls: (props: unknown) => Node }>(+ new URL("../src/components/assistant-ui/tool-confirmation-controls.tsx", import.meta.url), {+ "react/jsx-runtime": stubJsxRuntime(),+ react: {+ useCallback: (fn: unknown) => fn,+ useEffect: (effect: () => void) => { effects.push(effect); },+ useState: (initial: unknown) => {+ const slot = index++;+ if (!(slot in values)) values[slot] = initial;+ return [values[slot], (next: unknown) => { values[slot] = next; }];+ },+ },+ "@/components/ui/button": { Button: "Button" },+ "@/components/ui/alert-dialog": { AlertDialog: "Dialog" },+ "@/features/auth": { getAuthSessionEpoch: () => epoch },+ "@/features/auth/account-session": { useFullAccessAllowed: () => owner },+ "@/features/chat/permission-mode-select": { FullAccessConfirmContent: "FullAccessWarning" },+ "@/features/chat/utils/chat-full-access": { hasChatFullAccess, withChatFullAccess },+ "@/features/chat/api/chat-api": {+ resolveToolConfirmation: async (...args: unknown[]) => { requests.push(args); return answer(); },+ ToolApprovalGoneError: class Gone extends Error {},+ },+ "@/features/chat/stores/chat-runtime-store": { useChatRuntimeStore: store },+ "@/features/settings": {+ COMPOSER_INPUT_SELECTOR: "textarea", isSurfaceBackgrounded: () => false, useShortcut: () => {},+ },+ "@/features/chat": {+ useChatActive: () => true,+ useChatNavigationStore: (selector: (s: unknown) => unknown) => selector({ selectionActive: false }),+ },+ },+ );+ const render = () => {+ index = 0;+ effects = [];+ const tree = module.ToolConfirmationControls({ toolCallId: "call", toolName: "terminal", result: undefined, status: { type: "running" } });+ return descendants(tree);+ };+ const get = (nodes: Node[], type: string, label?: string) => {+ const element = nodes.find((node) => node.type === type && (label === undefined || node.props.children === label));+ assert.ok(element, `missing ${label ?? type}`);+ return element;+ };+ return {+ render, get, requests, grants, state,+ setAnswer: (next: () => Promise<boolean>) => { answer = next; },+ changeAccount: () => { epoch += 1; },+ runEffects: () => { for (const effect of effects) effect(); },+ };+}++async function settle() { await new Promise((resolve) => setTimeout(resolve, 0)); }+function click(node: Node, prop = "onClick") { (node.props[prop] as () => void)(); }++test("the shortcut opens the existing warning and cancel grants nothing", async () => {+ const h = harness();+ click(h.get(h.render(), "Button", "Full Access"));+ const nodes = h.render();+ assert.equal(h.get(nodes, "Dialog").props.open, true);+ assert.equal(h.requests.length, 0);+ click(h.get(nodes, "FullAccessWarning"), "onClose");+ await settle();+ assert.equal(h.get(h.render(), "Dialog").props.open, false);+ assert.deepEqual(h.requests, []);+ assert.deepEqual(h.grants, []);+});++test("Turn on upgrades the parked call before recording a grant for that chat", async () => {+ const h = harness();+ click(h.get(h.render(), "Button", "Full Access"));+ click(h.get(h.render(), "FullAccessWarning"), "onConfirm");+ assert.deepEqual(h.grants, [], "a pending POST is not a grant");+ await settle();+ assert.deepEqual(h.requests, [["project-shared", "approval-a", "allow", true]]);+ assert.deepEqual(h.grants, [{ runId: "run-a", sessionId: "project-shared", threadId: "chat-a" }]);+});++test("server failure or an unacknowledged legacy upgrade never records Full access", async () => {+ for (const answer of [async () => false, async () => { throw new Error("offline"); }]) {+ const h = harness();+ h.setAnswer(answer);+ click(h.get(h.render(), "Button", "Full Access"));+ click(h.get(h.render(), "FullAccessWarning"), "onConfirm");+ await settle();+ assert.deepEqual(h.grants, []);+ assert.ok(h.state.toolConfirmations.call);+ }+});++test("a delayed acknowledgment cannot grant the next signed-in account", async () => {+ const h = harness();+ let finish!: (ok: boolean) => void;+ h.setAnswer(() => new Promise((resolve) => { finish = resolve; }));+ click(h.get(h.render(), "Button", "Full Access"));+ click(h.get(h.render(), "FullAccessWarning"), "onConfirm");+ h.changeAccount();+ finish(true);+ await settle();+ assert.deepEqual(h.grants, []);+});++test("restricted accounts and explicit image disclosure never offer the shortcut", () => {+ for (const options of [{ owner: false }, { disclosure: true }]) {+ const h = harness(options);+ const nodes = h.render();+ assert.ok(!nodes.some((node) => node.type === "Button" && node.props.children === "Full Access"));+ }+});++test("already parked calls upgrade only within the confirmed chat", async () => {+ const own = harness({ grantedThread: "chat-a" });+ own.render(); own.runEffects(); await settle();+ assert.deepEqual(own.requests, [["project-shared", "approval-a", "allow", true]]);+ const other = harness({ grantedThread: "chat-b" });+ other.render(); other.runEffects(); await settle();+ assert.deepEqual(other.requests, []);+ const image = harness({ grantedThread: "chat-a", disclosure: true });+ image.render(); image.runEffects(); await settle();+ assert.deepEqual(image.requests, [], "Full access cannot auto-share an attached image");+});++test("a different chat's scoped Full Access does not hide this card's shortcut", () => {+ const h = harness({ grantedThread: "chat-b", scopedFull: true });+ assert.ok(h.get(h.render(), "Button", "Full Access"));+ assert.deepEqual(h.requests, []);+});+++test("a newer explicit permission choice wins over a delayed Full Access acknowledgment", async () => {+ for (const mode of ["ask", "off"]) {+ const h = harness();+ let finish!: (ok: boolean) => void;+ h.setAnswer(() => new Promise((resolve) => { finish = resolve; }));+ click(h.get(h.render(), "Button", "Full Access"));+ click(h.get(h.render(), "FullAccessWarning"), "onConfirm");+ h.state.chatPermissionChoiceVersion += 1;+ h.state.permissionMode = mode;+ finish(true);+ await settle();+ assert.deepEqual(h.grants, []);+ assert.equal(h.state.permissionMode, mode);+ }+});diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.pyindex 68c96832f46..00be23125a4 100644--- a/tests/studio/test_new_chat_context_recount.py+++ b/tests/studio/test_new_chat_context_recount.py@@ -183,6 +183,8 @@ const state: any = {loadedContextLength: null,modelLoading: false,runningByThreadId: {},+ chatFullAccessGrants: {},+ chatFullAccessPreviousMode: null,queuedSettingsEpoch: 0,// The subset decoding on the local llama-server: the recount must not share it with a decode.localRunByThreadId: {},diff --git a/tests/studio/test_project_chat_view_switch.py b/tests/studio/test_project_chat_view_switch.pyindex 1d6991e7769..4c3f62bba74 100644--- a/tests/studio/test_project_chat_view_switch.py+++ b/tests/studio/test_project_chat_view_switch.py@@ -184,6 +184,8 @@ const state: any = {loadedContextLength: null,modelLoading: false,runningByThreadId: {},+ chatFullAccessGrants: {},+ chatFullAccessPreviousMode: null,};function set(updater: any): void {