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: show when a chat is waiting for tool approval (#14877)
oobabooga39f9ef61ba2a
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 66fded017e5..d5f9942330f 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -42825,7 +42825,8 @@ class LlamaCppBackend:# nobody answered. Read before decision_slot is dropped in the deny branch._decision_reason = decision_reason(decision_slot)if _decision is not None and _decision != "deny":- # Approved: now it really is running.+ # tool_approved first: the route forwards it before retaking the model slot.+ yield decision.tool_approved_event(approval_id)yield {"type": "status", "text": decision.status_text}if _decision == "deny":decision_slot = Nonediff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex 9a66272311c..be60432cef0 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -1640,6 +1640,7 @@ def run_safetensors_tool_loop(# answered. Read before decision_slot is dropped in the deny branch below._decision_reason = decision_reason(decision_slot)if _decision is not None and _decision != "deny":+ yield decision.tool_approved_event(approval_id)yield {"type": "status", "text": decision.status_text}if _decision == "deny":decision_slot = Nonediff --git a/studio/backend/core/inference/sse_control_frames.py b/studio/backend/core/inference/sse_control_frames.pyindex 6ab1a7b0d7b..7777083896d 100644--- a/studio/backend/core/inference/sse_control_frames.py+++ b/studio/backend/core/inference/sse_control_frames.py@@ -39,6 +39,7 @@ _CONTROL_TYPES = frozenset("tool_args","tool_status","tool_model_note",+ "tool_approved","skill_load","diffusion_frame","reasoning_summary",diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex 22b19a0b959..26d45831a16 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -2065,6 +2065,7 @@ async def stream_with_studio_tools(decision_slot = Nonedenied = Trueelif verdict is not None:+ yield _sse(decision.tool_approved_event(approval_id))yield _status_sse(decision.status_text)if not denied:decision_slot = Nonediff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex 110da79b20b..630d170afd8 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -282,6 +282,15 @@ class ToolCallDecision:def tool_start_event(self) -> dict[str, Any]:return {"type": "tool_start", **self.tool_start_payload()}+ def tool_approved_event(self, approval_id: str) -> dict[str, Any]:+ """Tells the run's other followers the parked call was allowed, ahead of tool_end."""+ return {+ "type": "tool_approved",+ "tool_name": self.tool_name,+ "tool_call_id": self.card_id,+ "approval_id": approval_id,+ }+def as_assistant_tool_call(self) -> dict[str, Any]:"""Return an OpenAI-style tool_call with normalized arguments."""fragment = self.unparsed_fragmentdiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8e3a5adaf70..97ff35a0f0e 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -34594,6 +34594,9 @@ async def produce_openai_chat_completions(chunks.append(_gguf_chat_delta_line(ChoiceDelta(content = final_visible)))return chunks+ # Set by the frame that ends a park: other tabs clear their prompt on it, so it+ # is forwarded first and the slot is retaken before the generator does more.+ resume_before_next = Falsewhile True:if cancel_event.is_set():mark_current_response_failed()@@ -34604,6 +34607,10 @@ async def produce_openai_chat_completions(api_monitor.finish(monitor_id, "cancelled")return+ if resume_before_next:+ resume_before_next = False+ await _park_admission(False)+next_task = asyncio.create_task(asyncio.to_thread(next, gen, _tool_sentinel))@@ -34648,7 +34655,7 @@ async def produce_openai_chat_completions(and event.get("status") == "awaiting_approval")):- await _park_admission(False)+ resume_before_next = Trueif event["type"] == "heartbeat":# Tool-wrapper heartbeat while a server-side tool blocks; keeps SSE alive.@@ -34660,6 +34667,7 @@ async def produce_openai_chat_completions("tool_args","skill_load","tool_model_note",+ "tool_approved",):if (event["type"] == "skill_load"@@ -36660,8 +36668,8 @@ async def produce_openai_chat_completions(yield _OPENAI_TOOL_HEARTBEAT_SSEcontinue- if event["type"] in ("tool_output", "tool_args"):- # Live stdout/stderr, or tool-call arguments as the model writes them.+ if event["type"] in ("tool_output", "tool_args", "tool_approved"):+ # Live stdout/stderr, tool-call arguments as the model writes them, or an approval.if _ui_events:yield f"data: {json.dumps(event)}\n\n"elif _drop_keepalive.due():diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex c80d975be9d..b035bebd010 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -3136,6 +3136,45 @@ def test_only_an_approved_call_is_marked_approved(monkeypatch, verdict):assert seen == ([True] if verdict == "allow" else [])[email protected]("verdict", ["allow", "deny"])+def test_an_allowed_call_tells_every_follower_before_tool_end(monkeypatch, verdict):+ """Only the client that answered clears its own prompt; other tabs learn it from tool_approved."""+ first_stream = _streamed_structured_tool_call("python", {"code": "print(1)"}, "call_gated")+ final_stream = [_sse({"content": "Done."}), _done()]+ backend, _payloads = _backend_and_payloads(monkeypatch, [first_stream, final_stream])+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda name, arguments, **_k: "OK")+ monkeypatch.setattr("core.inference.llama_cpp.wait_tool_decision", lambda *_a, **_k: verdict)++ events = _run_tool_loop(+ backend,+ [{"role": "user", "content": "run it"}],+ [{"type": "function", "function": {"name": "python"}}],+ confirm_tool_calls = True,+ permission_mode = "ask",+ )++ gated = [e for e in events if e.get("type") == "tool_start" and e.get("awaiting_confirmation")]+ approved = [e for e in events if e.get("type") == "tool_approved"]+ ends = [e for e in events if e.get("type") == "tool_end"]+ assert len(gated) == 1 and len(ends) == 1, events+ if verdict == "deny":+ # A refusal ends the card at once; there is no run to wait through.+ assert approved == []+ return+ assert approved == [+ {+ "type": "tool_approved",+ "tool_name": "python",+ "tool_call_id": gated[0]["tool_call_id"],+ "approval_id": gated[0]["approval_id"],+ }+ ]+ assert events.index(gated[0]) < events.index(approved[0]) < events.index(ends[0])+ # Before the running status: the route waits for the model slot on that frame, and other tabs must not.+ between = events[events.index(gated[0]) + 1 : events.index(approved[0])]+ assert [e for e in between if e.get("type") == "status"] == [], between++def test_auto_mode_render_html_suppresses_provisional_card_under_confirm(monkeypatch):"""Confirm under permission_mode=auto hides the render_html provisional card; full tool_start fires."""args = {"code": "<html>" + "x" * 80 + "</html>"}diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex 5cc83af51d3..e081b1fc019 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -5391,6 +5391,135 @@ class TestGgufVisionToolRouting:asyncio.run(_run())+ @pytest.mark.parametrize("outcome", ["allow", "deny", "expire"])+ def test_gguf_decision_reaches_other_tabs_while_another_chat_holds_the_slot(+ self, monkeypatch, outcome+ ):+ """Other tabs clear their prompt on the first frame after a decision, so it must not wait for the+ model slot. The run itself does no more work until the slot is back."""+ import routes.inference as inf_mod+ from state.tool_approvals import TOOL_APPROVAL_EXPIRED_MESSAGE, TOOL_REJECTED_MESSAGE++ async def _run():+ async def fake_select_tools(*_args, **_kwargs):+ return [+ {+ "type": "function",+ "function": {+ "name": "python",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ]++ decided = threading.Event()+ resumed = threading.Event()+ end = {"type": "tool_end", "tool_name": "python", "tool_call_id": "call_0"}++ # The GGUF loop's own frames after each outcome: an Allow sends the approval and then the+ # running status; a refusal or an expiry ends the card at once.+ def _generate(**kwargs):+ cancel_event = kwargs["cancel_event"]+ yield {"type": "status", "text": "Waiting for approval: Python"}+ yield {+ "type": "tool_start",+ "tool_name": "python",+ "tool_call_id": "call_0",+ "arguments": {"code": "print(1)"},+ "awaiting_confirmation": True,+ "approval_id": "approval_0",+ }+ while not decided.is_set() and not cancel_event.is_set():+ time.sleep(0.005)+ if outcome == "allow":+ yield {+ "type": "tool_approved",+ "tool_name": "python",+ "tool_call_id": "call_0",+ "approval_id": "approval_0",+ }+ resumed.set()+ yield {"type": "status", "text": "Running Python..."}+ yield {**end, "result": "1"}+ else:+ result = (+ TOOL_REJECTED_MESSAGE+ if outcome == "deny"+ else TOOL_APPROVAL_EXPIRED_MESSAGE+ )+ yield {**end, "result": result}+ resumed.set()+ yield {"type": "content", "text": "next-turn-answer"}++ backend = SimpleNamespace(+ is_loaded = True,+ is_vision = False,+ supports_tools = True,+ supports_reasoning = True,+ reasoning_always_on = True,+ _is_audio = False,+ model_identifier = "test-gguf",+ context_length = 4096,+ base_url = f"http://llama.decision-{outcome}.test",+ effective_parallel_slots = 1,+ count_chat_tokens = lambda *_args, **_kwargs: 10,+ generate_chat_completion = lambda **_kwargs: "unused",+ generate_chat_completion_with_tools = _generate,+ )+ monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)+ monkeypatch.setattr(inf_mod, "_select_request_tools", fake_select_tools)++ payload = ChatCompletionRequest(+ model = "default",+ messages = [{"role": "user", "content": "run python"}],+ enable_tools = True,+ stream = True,+ )+ response = await openai_chat_completions(+ payload,+ request = self._Request(ui_events = True),+ current_subject = "test",+ )+ iterator = response.body_iterator++ async def next_frame(needle):+ async for chunk in iterator:+ if needle in chunk:+ return chunk+ pytest.fail(f"{needle} never arrived")++ blocker = None+ rest = None+ try:+ await asyncio.wait_for(next_frame('"tool_start"'), timeout = 2)+ # The parked run gave up its slot; another chat takes it.+ queue = get_llama_admission_queue(f"http://llama.decision-{outcome}.test")+ blocker = queue.reserve(capacity = 1, config = LlamaAdmissionConfig()).lease_nowait()+ assert blocker is not None+ decided.set()+ first = '"tool_approved"' if outcome == "allow" else '"tool_end"'+ await asyncio.wait_for(next_frame(first), timeout = 2)++ # The run itself waits for the slot before it goes on.+ rest = asyncio.create_task(next_frame("next-turn-answer"))+ await asyncio.sleep(0.2)+ assert not rest.done()+ assert not resumed.is_set(), "the run went on while another chat held its slot"+ blocker.release()+ blocker = None+ await asyncio.wait_for(rest, timeout = 2)+ finally:+ decided.set()+ if blocker is not None:+ blocker.release()+ if rest is not None and not rest.done():+ rest.cancel()+ await asyncio.gather(rest, return_exceptions = True)+ await iterator.aclose()++ asyncio.run(_run())+def test_gguf_tool_stream_task_cancel_after_first_chunk_finalizes_monitor(self, monkeypatch):import routes.inference as inf_modasync def _run():diff --git a/studio/backend/tests/test_provider_control_frame_spoofing.py b/studio/backend/tests/test_provider_control_frame_spoofing.pyindex a1561fd60b6..235790b79ef 100644--- a/studio/backend/tests/test_provider_control_frame_spoofing.py+++ b/studio/backend/tests/test_provider_control_frame_spoofing.py@@ -24,6 +24,8 @@ from core.inference.sse_control_frames import sanitize_provider_sse_line"tool_output","tool_args","tool_status",+ # A forged one would take another chat's Allow / Deny off screen.+ "tool_approved","diffusion_frame","reasoning_summary","context_usage",diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.pyindex 96682d6edce..d2e0be8d208 100644--- a/studio/backend/tests/test_safetensors_tool_loop.py+++ b/studio/backend/tests/test_safetensors_tool_loop.py@@ -2258,6 +2258,54 @@ class TestLoopBasic:assert "<!doctype html>" in real[0]["arguments"]["code"]assert exec_fn.calls[0][0] == "render_html"+ @pytest.mark.parametrize("verdict", ["allow", "deny"])+ def test_an_allowed_call_tells_every_follower_before_tool_end(self, monkeypatch, verdict):+ """Only the client that answered clears its own prompt; other tabs learn it from tool_approved."""+ monkeypatch.setattr(safetensors_agentic, "new_approval_id", lambda: "approval-rh")+ monkeypatch.setattr(safetensors_agentic, "begin_tool_decision", lambda *_a, **_k: object())+ monkeypatch.setattr(safetensors_agentic, "wait_tool_decision", lambda *_a, **_k: verdict)++ exec_fn, turn_iter = _shared_setup_1()++ def _gen(_messages):+ chunks = next(turn_iter)+ acc = ""+ for chunk in chunks:+ acc += chunk+ yield acc++ events = _collect_events(+ run_safetensors_tool_loop(+ single_turn = _gen,+ messages = [{"role": "user", "content": "make html"}],+ tools = [{"type": "function", "function": {"name": "render_html"}}],+ execute_tool = exec_fn,+ confirm_tool_calls = True,+ permission_mode = "ask",+ session_id = "sess",+ max_tool_iterations = 3,+ )+ )+ gated = [e for e in events if e["type"] == "tool_start" and e.get("awaiting_confirmation")]+ approved = [e for e in events if e["type"] == "tool_approved"]+ ends = [e for e in events if e["type"] == "tool_end"]+ assert len(gated) == 1 and len(ends) == 1, events+ if verdict == "deny":+ assert approved == []+ return+ assert approved == [+ {+ "type": "tool_approved",+ "tool_name": "render_html",+ "tool_call_id": gated[0]["tool_call_id"],+ "approval_id": "approval-rh",+ }+ ]+ assert events.index(gated[0]) < events.index(approved[0]) < events.index(ends[0])+ # Same order as the GGUF loop: the approval before the running status.+ between = events[events.index(gated[0]) + 1 : events.index(approved[0])]+ assert [e for e in between if e["type"] == "status"] == [], between+def test_render_html_bypass_permissions_keeps_early_provisional(self, monkeypatch):"""bypass_permissions wins over the confirm gate, so the early provisionalcard is preserved (no human approval is required)."""diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.pyindex 5f701ead4fc..63175713caa 100644--- a/studio/backend/tests/test_studio_tool_loop.py+++ b/studio/backend/tests/test_studio_tool_loop.py@@ -684,6 +684,48 @@ def test_denied_call_does_not_spend_an_iteration(executed, monkeypatch):assert executed[0]["arguments"] == {"query": "2"}[email protected]("verdict", ["allow", "deny"])+def test_an_allowed_call_tells_every_follower_before_tool_end(executed, monkeypatch, verdict):+ """Only the client that answered clears its own prompt; other tabs learn it from tool_approved."""+ monkeypatch.setattr(loop_mod, "begin_tool_decision", lambda session, approval: object())+ monkeypatch.setattr(+ loop_mod, "wait_tool_decision", lambda slot, approval, cancel_event = None: verdict+ )+ monkeypatch.setattr(loop_mod, "abort_tool_decision", lambda slot, approval: None)+ monkeypatch.setattr(loop_mod, "new_approval_id", lambda: "ap1")+ call = {"index": 0, "id": "c1", "function": {"name": "python", "arguments": "{}"}}+ transport = FakeTransport(+ [+ [_sse({"tool_calls": [call]}), _sse(finish = "tool_calls"), _DONE],+ [_sse({"content": "ok"}), _sse(finish = "stop"), _DONE],+ ]+ )+ lines = _run(transport, tools = [PY], permission_mode = "ask", confirm_calls = True)++ gated = [e for e in _events(lines, "tool_start") if e.get("awaiting_confirmation")]+ approved = _events(lines, "tool_approved")+ assert len(gated) == 1 and len(_events(lines, "tool_end")) == 1, lines+ if verdict == "deny":+ assert approved == []+ return+ assert approved == [+ {+ "type": "tool_approved",+ "tool_name": "python",+ "tool_call_id": gated[0]["tool_call_id"],+ "approval_id": "ap1",+ }+ ]+ kinds = [+ json.loads(line[6:]).get("type")+ for line in lines+ if line.startswith("data: ") and line[6:] != "[DONE]"+ ]+ assert kinds.index("tool_start") < kinds.index("tool_approved") < kinds.index("tool_end")+ # Same order as the GGUF loop: the approval before the running status.+ assert "tool_status" not in kinds[kinds.index("tool_start") + 1 : kinds.index("tool_approved")]++def test_auto_mode_prompts_only_for_high_risk_calls(executed, monkeypatch):slots: list = []monkeypatch.setattr(diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex f0266f3007f..b352a92784e 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -406,8 +406,11 @@ export const BUDGET = {// unchanged at 98). Raised by +278 B raw / +129 B transfer so main's margin stays where it was.// Browser use step names, docs link and card fence strip (#14681): +1,089 B raw / +298 B transfer (6,925,028 ->// 6,926,117 B raw, 2,086,327 -> 2,086,625 B transfer against 394aff8545, Node 26, 99 chunks). Raised by that.- transferBytes: 2_087_057,- rawBytes: 6_927_757,+ // The waiting-for-approval mark, Desktop attention request and tool_approved handling (#14877): measured+ // 6,929,942 B raw / 2,087,788 B transfer merged with main at b3004af53 (Node 24, 99 chunks). Set to+ // that plus about 300 B raw / 100 B transfer, as for #14568.+ transferBytes: 2_087_890,+ rawBytes: 6_930_250,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 41f4d3453c0..1f29b76527f 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -49,6 +49,11 @@ import {} from "@/components/ui/dropdown-menu";import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";import { ProgressiveRows } from "@/components/progressive-rows";+import {+ returnToChatThreadId,+ useApprovalWaitingStore,+ watchApprovalWaiting,+} from "@/features/chat/utils/approval-waiting";import { keepOpenedChats, touchOpenedChat } from "@/features/chat/utils/opened-chats";import { isAssistantLocalThreadId } from "@/features/chat/utils/thread-ids";import {@@ -644,6 +649,7 @@ function NavItem({dataTour,className,spinner,+ waiting,tooltip,tooltipAction,alwaysTooltip,@@ -662,6 +668,8 @@ function NavItem({dataTour?: string;className?: string;spinner?: boolean;+ // Replaces the spinner with the approval mark; the text is read after the label.+ waiting?: string;onIntent?: () => void;// Stable hook for the UI smokes, which assert a row spins rather than greys out// while its capability verdict is still unmeasured.@@ -705,7 +713,7 @@ function NavItem({isActive={active}data-tour={dataTour}data-testid={testId}- data-spinner={spinner ? "true" : undefined}+ data-spinner={spinner && !waiting ? "true" : undefined}className="sidebar-nav-btn h-[calc(33px*var(--ui-space-scale,1))] rounded-full gap-[calc(8.5px*var(--ui-space-scale,1))] pl-3 pr-2.5 font-medium group-data-[collapsible=icon]:!p-0 group-data-[collapsible=icon]:!size-[calc(28px*var(--ui-space-scale,1))] group-data-[collapsible=icon]:my-[calc(2.5px*var(--ui-space-scale,1))] group-data-[collapsible=icon]:mx-auto"><HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-icon! shrink-0 translate-x-0.5 group-data-[collapsible=icon]:translate-x-0 group-hover/menu-button:animate-icon-pop" />@@ -715,13 +723,27 @@ function NavItem({{badge}</Badge>)}- {spinner && (- // mr-1.5 plus the row's pr-2.5 makes 16px, matching the chat row spinner column.- <Spinner className="ml-auto mr-1.5 size-3.5 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden" />+ {waiting ? (+ <>+ <span className="sr-only"> {waiting}</span>+ <ApprovalMark className="ml-auto mr-1.5 size-3.5 group-data-[collapsible=icon]:hidden" />+ </>+ ) : (+ spinner && (+ // mr-1.5 plus the row's pr-2.5 makes 16px, matching the chat row spinner column.+ <Spinner className="ml-auto mr-1.5 size-3.5 shrink-0 text-muted-foreground group-data-[collapsible=icon]:hidden" />+ ))}</SidebarMenuButton>- {spinner && (- <Spinner className="pointer-events-none absolute right-1 top-1 hidden size-2.5 text-muted-foreground group-data-[collapsible=icon]:block" />+ {waiting ? (+ <ApprovalMark+ testId="nav-approval"+ className="pointer-events-none absolute right-1 top-1 hidden size-2.5 group-data-[collapsible=icon]:block"+ />+ ) : (+ spinner && (+ <Spinner className="pointer-events-none absolute right-1 top-1 hidden size-2.5 text-muted-foreground group-data-[collapsible=icon]:block" />+ ))}{overlay}</div>@@ -734,6 +756,28 @@ function NavItem({);}+/** The spinner's stand-in while a run waits on Allow / Deny. Its shape, not only its colour, tells it from+ * the unread dot (amber-accent themes, colour-blind users); static, since motion means working. */+function ApprovalMark({ className, testId }: { className: string; testId?: string }) {+ return (+ <svg+ viewBox="0 0 14 14"+ aria-hidden="true"+ data-testid={testId}+ className={cn("shrink-0", className)}+ >+ <circle cx="7" cy="7" r="7" className="fill-amber-700 dark:fill-amber-400" />+ <path+ d="M7 3.6v4.1"+ strokeWidth="1.8"+ strokeLinecap="round"+ className="stroke-white dark:stroke-neutral-900"+ />+ <circle cx="7" cy="10.3" r="1" className="fill-white dark:fill-neutral-900" />+ </svg>+ );+}+const WORKFLOW_UNAVAILABLE = "The loaded model cannot do this";// Re-read cadences for the hardware verdict below. An unmeasured verdict holds Train and Video on@@ -2038,6 +2082,9 @@ export function AppSidebar() {const setActiveThreadId = useChatRuntimeStore((s) => s.setActiveThreadId);// The whole map, so each row can show its own spinner.const runningByThreadId = useChatRuntimeStore((s) => s.runningByThreadId);+ // Watched here, not by the tool cards: only the open chat mounts those.+ const approvalWaitingThreadIds = useApprovalWaitingStore((s) => s.threadIds);+ useEffect(() => watchApprovalWaiting(useChatRuntimeStore), []);// Shared with the thread's own Fork, so neither surface can post a second one.const forkInFlight = useForkInFlight((s) => s.forking);// Rows, not raw thread ids: a compare conversation runs two pane threads but is one row.@@ -2061,13 +2108,27 @@ export function AppSidebar() {return rows + running.size;}, [runningByThreadId, allChatItems]);const anyChatRunning = runningChatCount > 0;- // Where "Return to Chat" lands: the newest running chat, not an empty New Chat draft (map- // insertion order is start order). Compare rows resolve back to the pair id /chat expects.+ const activeThreadId = isChatRoute+ ? (search.thread as string | undefined) ??+ (search.compare as string | undefined) ??+ storeThreadId ??+ undefined+ : undefined;+ // Less the open chat: its card is already on screen.+ const approvalWaitingElsewhere = useMemo(() => {+ if (!activeThreadId) return approvalWaitingThreadIds;+ const open = allChatItems.find((item) => item.id === activeThreadId);+ const openIds = new Set(open ? getSidebarItemThreadIds(open) : [activeThreadId]);+ return new Set([...approvalWaitingThreadIds].filter((id) => !openIds.has(id)));+ }, [approvalWaitingThreadIds, activeThreadId, allChatItems]);+ const anyChatWaiting = useMemo(+ () => [...approvalWaitingElsewhere].some((id) => runningByThreadId[id]),+ [approvalWaitingElsewhere, runningByThreadId],+ );+ // Where "Return to Chat" lands: a running chat, not an empty New Chat draft. Compare rows+ // resolve back to the pair id /chat expects.const runningTarget = useMemo(() => {- const ids = Object.entries(runningByThreadId)- .filter(([, on]) => on)- .map(([id]) => id);- const id = ids.length > 0 ? ids[ids.length - 1] : null;+ const id = returnToChatThreadId(runningByThreadId, approvalWaitingElsewhere);if (!id) return null;const pair = allChatItems.find((item) => item.type === "compare" && (item.threadIds ?? []).includes(id),@@ -2075,13 +2136,7 @@ export function AppSidebar() {return pair? { id: pair.id, compare: true as const }: { id, compare: false as const };- }, [runningByThreadId, allChatItems]);- const activeThreadId = isChatRoute- ? (search.thread as string | undefined) ??- (search.compare as string | undefined) ??- storeThreadId ??- undefined- : undefined;+ }, [runningByThreadId, approvalWaitingElsewhere, allChatItems]);// A chat started from a section's header joins it when its first send gives it an id, which// lands in the store while the address still names the new chat. Leaving that chat first lets// the mark go, so a chat opened afterwards is never filed by mistake. Turning it into a compare@@ -5447,6 +5502,9 @@ export function AppSidebar() {// Active generation and queued work share the in-row spinner slot so they cannot drift.const showQueuedActivity = hasQueuedActivity && !isGenerating;const showWorkSpinner = isGenerating || showQueuedActivity;+ const awaitingApproval =+ isGenerating &&+ threadIds.some((threadId) => approvalWaitingElsewhere.has(threadId));const alreadyUnread = threadIds.some((threadId) =>unreadThreadIds.has(threadId),);@@ -5472,7 +5530,7 @@ export function AppSidebar() {isPinned && variant !== "project" && "gap-[calc(8.5px*var(--ui-space-scale,1))]",// A spinner glyph cannot truncate, and the pin and the kebab overlay that same edge, so a// working row holds their room open whether or not it is hovered.- showWorkSpinner ? "pr-16" : hasUnreadActivity ? "pr-7" : showForkMark ? "pr-9" : undefined,+ showWorkSpinner ? "pr-16" : hasUnreadActivity || showForkMark ? "pr-9" : undefined,// Coarse pointers reveal the actions permanently, so the spinner drops back beside// them (right-16, ending 78px in) and the title has to clear that, not just pr-16.showWorkSpinner && "[@media(pointer:coarse)]:pr-[calc(78px*var(--ui-space-scale,1))]",@@ -5530,7 +5588,8 @@ export function AppSidebar() {data-thread-type={item.type}data-thread-id={item.id}data-generating={isGenerating ? "true" : undefined}- aria-busy={isGenerating || undefined}+ // Waiting on the user is not busy.+ aria-busy={(isGenerating && !awaitingApproval) || undefined}isActive={activeThreadId === item.id}data-selected={selectedChatIds.has(item.id) ? "true" : undefined}className={buttonClass}@@ -5551,6 +5610,12 @@ export function AppSidebar() {<span className="truncate">{pendingRename?.id === item.id ? pendingRename.title : item.title}</span>+ {/* The mark and the dot sit outside the button, so its name carries them. */}+ {awaitingApproval ? (+ <span className="sr-only"> {translate("shell.navigation.chatAwaitingApproval")}</span>+ ) : hasUnreadActivity ? (+ <span className="sr-only"> {translate("shell.navigation.chatUnread")}</span>+ ) : null}</SidebarMenuButton>{showWorkSpinner ? (// Anchored to the row, not laid out in it. As ml-auto the spinner rested on@@ -5568,25 +5633,30 @@ export function AppSidebar() {: "group-hover/recent-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-0 group-has-[.sidebar-row-action:focus-visible]/recent-item:opacity-0",)}>- <Spinner- data-testid="chat-row-spinner"- // role="status" + label: announced, not motion-only.- label={- isGenerating- ? translate("shell.navigation.chatGenerating")- : "Queued"- }- className="size-3.5 shrink-0 text-muted-foreground"- />+ {awaitingApproval ? (+ <ApprovalMark testId="chat-row-approval" className="size-3.5" />+ ) : (+ <Spinner+ data-testid="chat-row-spinner"+ // role="status" + label: announced, not motion-only.+ label={+ isGenerating+ ? translate("shell.navigation.chatGenerating")+ : "Queued"+ }+ className="size-3.5 shrink-0 text-muted-foreground"+ />+ )}</span>) : null}{hasUnreadActivity ? (+ // Same box and anchor as the spinner, so both share one column.<spanclassName={cn(- "pointer-events-none absolute right-2 top-1/2 z-10 flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground transition-opacity",+ "pointer-events-none absolute right-4 top-1/2 z-10 flex size-3.5 -translate-y-1/2 items-center justify-center text-muted-foreground transition-opacity",variant === "project"- ? "group-hover/project-chat-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:opacity-0"- : "group-hover/recent-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-0",+ ? "group-hover/project-chat-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:opacity-0 group-has-[.sidebar-row-action:focus-visible]/project-chat-item:opacity-0"+ : "group-hover/recent-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-0 group-has-[.sidebar-row-action:focus-visible]/recent-item:opacity-0",)}aria-hidden>@@ -6104,6 +6174,12 @@ export function AppSidebar() {}// Off-route this row is the only sign chats are still running.spinner={anyChatRunning && !isChatRoute}+ // On every route: the waiting row can be folded away, behind Show more, or scrolled off.+ waiting={+ anyChatWaiting+ ? t("shell.navigation.chatAwaitingApproval")+ : undefined+ }// An action, not a destination, so it never marks itself active: the active pill is the// hover pill, and on a blank new chat it left the row looking permanently hovered.active={false}diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 49f3f424216..d889771d1f1 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -7544,6 +7544,25 @@ export function createOpenAIStreamAdapter(if (deepResearchHandoff.question !== null) break;continue;}+ // Answered in another tab or device: clear the prompt now, not at tool_end.+ if (toolEvent.type === "tool_approved") {+ const approvedBackendId =+ (toolEvent.tool_call_id as string) || "";+ const approvedId = toolEvent.approval_id;+ const confirmationId =+ toolConfirmationIdsByBackendId.get(approvedBackendId) ??+ (typeof approvedId === "string" && approvedId+ ? toolCallParts.find(+ (p) => p.toolApprovalId === approvedId,+ )?.toolCallId+ : undefined);+ if (confirmationId) {+ useChatRuntimeStore+ .getState()+ .clearToolConfirmation(confirmationId);+ }+ continue;+ }// Persist container_id onto the thread (OpenAI / Anthropic).if (toolEvent.type === "container_ready") {const newContainerId = toolEvent.container_id as@@ -7845,6 +7864,8 @@ export function createOpenAIStreamAdapter(} as PositionedToolCallPart);}if (awaitingConfirmation) {+ // The run's key now, not at send: a first turn adopted mid-run files its calls under the chat.+ const confirmationThreadKey = liveThreadKey(serverCancel);useChatRuntimeStore.getState().setToolConfirmation(@@ -7852,6 +7873,7 @@ export function createOpenAIStreamAdapter(approvalId,sandboxSessionId ?? "",toolConfirmationScopeId,+ confirmationThreadKey === "__default" ? "" : confirmationThreadKey,toolEvent.image_disclosure as ImageDisclosure | undefined,);}diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex ff1eca2f9db..37adc248c81 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -2037,7 +2037,8 @@ export async function* streamChatCompletions(parsed.type === "tool_end" ||parsed.type === "tool_output" ||parsed.type === "tool_args" ||- parsed.type === "tool_model_note")+ parsed.type === "tool_model_note" ||+ parsed.type === "tool_approved")) {yield { _toolEvent: parsed } as unknown as OpenAIChatChunk;separatorIndex = buffer.search(/\r?\n\r?\n/);diff --git a/studio/frontend/src/features/chat/api/chat-generation-api.ts b/studio/frontend/src/features/chat/api/chat-generation-api.tsindex 2e4c0026fd5..79bad7f040d 100644--- a/studio/frontend/src/features/chat/api/chat-generation-api.ts+++ b/studio/frontend/src/features/chat/api/chat-generation-api.ts@@ -89,7 +89,8 @@ export function normalizeChatGenerationChunkPayload(frameType === "tool_end" ||frameType === "tool_output" ||frameType === "tool_args" ||- frameType === "tool_model_note"+ frameType === "tool_model_note" ||+ frameType === "tool_approved") {// tool_start/end carry full input/output; tool_output streams incremental stdout and// tool_args streams the call arguments live. The consumer accumulates by tag, so keep the frame whole.diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex d73273fe25e..055a8862899 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -1519,6 +1519,7 @@ function scheduleGenerationRecovery(approvalId,sessionId,`${sessionId || "_default"}:${threadId}`,+ threadId,),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 82dc4aaab36..73679877ad0 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -120,6 +120,7 @@ import {type ModelLifecyclePhase,} from "../utils/model-lifecycle-gate";import { shouldAdvanceQueuedSettingsEpoch } from "../utils/queued-settings-epoch";+import { adoptFirstTurnConfirmations } from "../utils/adopt-first-turn-confirmations";import type { MmprojFallbackReason } from "../types/api";import type {ResearchMcpSource,@@ -2622,13 +2623,15 @@ type ChatRuntimeStore = {alwaysAllowToolsBySession: Map<string, Set<string>>;/** Calls paused for allow/deny, keyed by scoped frontend tool-call id. Each carries the* backend `approvalId` and the run's `sessionId` so the exact call resolves;- * `autoAllowKey` scopes "Always allow" per chat. Backend-gated local calls only. */+ * `autoAllowKey` scopes "Always allow" per chat; `threadId` names the asking chat ("" for a+ * run with no saved chat yet). Backend-gated local calls only. */toolConfirmations: Record<string,{approvalId: string;sessionId: string;autoAllowKey: string;+ threadId: string;imageDisclosure?: ImageDisclosure;}>;@@ -2918,6 +2921,7 @@ type ChatRuntimeStore = {approvalId: string,sessionId: string,autoAllowKey: string,+ threadId: string,imageDisclosure?: ImageDisclosure,) => void;clearToolConfirmation: (toolCallId: string) => void;@@ -5158,6 +5162,14 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({state.activeDiffusionCanvasByThreadId,"activeDiffusionCanvasByThreadId",);+ // Its parked calls too, or the row never trades its spinner for the approval mark.+ if (moved.runningByThreadId) {+ const confirmations = adoptFirstTurnConfirmations(+ state.toolConfirmations,+ threadId,+ );+ if (confirmations) moved.toolConfirmations = confirmations;+ }return Object.keys(moved).length > 0 ? moved : state;}),runKeyForOwner: (fallbackKey, owner) => {@@ -6049,12 +6061,19 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({approvalId,sessionId,autoAllowKey,+ threadId,imageDisclosure,) =>set((state) => ({toolConfirmations: {...state.toolConfirmations,- [toolCallId]: { approvalId, sessionId, autoAllowKey, imageDisclosure },+ [toolCallId]: {+ approvalId,+ sessionId,+ autoAllowKey,+ threadId,+ imageDisclosure,+ },},})),clearToolConfirmation: (toolCallId) =>diff --git a/studio/frontend/src/features/chat/utils/adopt-first-turn-confirmations.ts b/studio/frontend/src/features/chat/utils/adopt-first-turn-confirmations.tsnew file mode 100644index 00000000000..d63abafd5fc--- /dev/null+++ b/studio/frontend/src/features/chat/utils/adopt-first-turn-confirmations.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** A first turn that parks before its chat has an id files the call under threadId "". Hands those+ * calls the id the run is adopted under, or null when there are none. */+export function adoptFirstTurnConfirmations<T extends { threadId: string }>(+ confirmations: Readonly<Record<string, T>>,+ threadId: string,+): Record<string, T> | null {+ let next: Record<string, T> | null = null;+ for (const [id, entry] of Object.entries(confirmations)) {+ if (entry.threadId !== "") continue;+ next ??= { ...confirmations };+ next[id] = { ...entry, threadId };+ }+ return next;+}diff --git a/studio/frontend/src/features/chat/utils/approval-waiting.ts b/studio/frontend/src/features/chat/utils/approval-waiting.tsnew file mode 100644index 00000000000..3339c72bde5--- /dev/null+++ b/studio/frontend/src/features/chat/utils/approval-waiting.ts@@ -0,0 +1,148 @@+// 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 { isTauri } from "@/lib/api-base";+import { create } from "zustand";++// An "Always allow" call still parks until its card answers it in one request; only a call+// parked longer than this is waiting on the user.+export const APPROVAL_SETTLE_MS = 1_500;++type PendingConfirmations = Readonly<Record<string, { threadId: string }>>;++type ConfirmationSource = {+ getState: () => { toolConfirmations: PendingConfirmations };+ subscribe: (+ listener: (+ state: { toolConfirmations: PendingConfirmations },+ previous: { toolConfirmations: PendingConfirmations },+ ) => void,+ ) => () => void;+};++const NONE: ReadonlySet<string> = new Set();++/** Chats with a tool call parked on Allow / Deny for at least APPROVAL_SETTLE_MS. */+export const useApprovalWaitingStore = create<{+ threadIds: ReadonlySet<string>;+}>(() => ({ threadIds: NONE }));++const parked = new Map<string, { threadId: string; since: number }>();+const settled = new Set<string>();+let timer: ReturnType<typeof setTimeout> | null = null;+let attentionRequested = false;++function windowIsInBackground(): boolean {+ if (typeof document === "undefined") return false;+ return (+ document.visibilityState !== "visible" ||+ (typeof document.hasFocus === "function" && !document.hasFocus())+ );+}++// null withdraws the request where the platform supports it.+function setWindowAttention(on: boolean): void {+ if (!isTauri) return;+ void import("@tauri-apps/api/window")+ .then(({ getCurrentWindow, UserAttentionType }) =>+ getCurrentWindow().requestUserAttention(+ on ? UserAttentionType.Informational : null,+ ),+ )+ .catch(() => undefined);+}++function publish(now: number): void {+ if (timer !== null) {+ clearTimeout(timer);+ timer = null;+ }+ const threadIds = new Set<string>();+ let newlySettled = false;+ let nextDue = Number.POSITIVE_INFINITY;+ for (const [id, { threadId, since }] of parked) {+ const due = since + APPROVAL_SETTLE_MS;+ if (due > now) {+ nextDue = Math.min(nextDue, due);+ continue;+ }+ if (!settled.has(id)) {+ settled.add(id);+ newlySettled = true;+ }+ // No saved chat yet: no row to mark, but it still asks for attention.+ if (threadId) threadIds.add(threadId);+ }+ if (nextDue !== Number.POSITIVE_INFINITY) {+ timer = setTimeout(() => {+ timer = null;+ publish(Date.now());+ }, nextDue - now);+ }++ const previous = useApprovalWaitingStore.getState().threadIds;+ if (+ previous.size !== threadIds.size ||+ [...threadIds].some((id) => !previous.has(id))+ ) {+ useApprovalWaitingStore.setState({+ threadIds: threadIds.size > 0 ? threadIds : NONE,+ });+ }++ if (newlySettled && windowIsInBackground()) {+ attentionRequested = true;+ setWindowAttention(true);+ } else if (settled.size === 0 && attentionRequested) {+ attentionRequested = false;+ setWindowAttention(false);+ }+}++/** The chat "Return to Chat" opens: the newest running one, or while any of them waits, the newest+ * waiting one, since the row then shows the waiting mark. Insertion order is start order. */+export function returnToChatThreadId(+ runningByThreadId: Readonly<Record<string, boolean>>,+ waiting: ReadonlySet<string>,+): string | null {+ const running = Object.entries(runningByThreadId)+ .filter(([, on]) => on)+ .map(([id]) => id);+ const waitingRunning = running.filter((id) => waiting.has(id));+ const pool = waitingRunning.length > 0 ? waitingRunning : running;+ return pool.length > 0 ? pool[pool.length - 1] : null;+}++/** Feed the current parked calls; ids that are gone stop counting at once. */+export function syncApprovalWaiting(+ confirmations: PendingConfirmations,+ now: number = Date.now(),+): void {+ for (const id of [...parked.keys()]) {+ if (!Object.prototype.hasOwnProperty.call(confirmations, id)) {+ parked.delete(id);+ settled.delete(id);+ }+ }+ for (const [id, { threadId }] of Object.entries(confirmations)) {+ const known = parked.get(id);+ // A first turn's call gains its chat once the run is adopted; it keeps its park time.+ if (known) known.threadId = threadId;+ else parked.set(id, { threadId, since: now });+ }+ publish(now);+}++/** Follow the runtime store's parked calls until the returned function is called. */+export function watchApprovalWaiting(source: ConfirmationSource): () => void {+ syncApprovalWaiting(source.getState().toolConfirmations);+ const unsubscribe = source.subscribe((state, previous) => {+ if (state.toolConfirmations !== previous.toolConfirmations) {+ syncApprovalWaiting(state.toolConfirmations);+ }+ });+ return () => {+ unsubscribe();+ syncApprovalWaiting({});+ };+}diff --git a/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts b/studio/frontend/src/features/chat/utils/generation-tool-recovery.tsindex b95142d806a..ffdfa336764 100644--- a/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts+++ b/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts@@ -157,12 +157,19 @@ export function createGenerationToolRecovery(* unconditionally because it owns every card in its stream; a recovery shares the store with* whatever else is on screen, so reaching for a card it never raised is not its business. */const armed = new Set<string>();+ /** Approvals the stream reported granted. Never armed again: a seeded check can predate the frame. */+ const approved = new Set<string>();const armApproval = (entry: CarriedPart,approvalId: unknown,sessionId: string,) => {- if (!toolConfirmations || typeof approvalId !== "string" || !approvalId)+ if (+ !toolConfirmations ||+ typeof approvalId !== "string" ||+ !approvalId ||+ approved.has(approvalId)+ )return;const partId = record(entry.part)?.toolCallId;if (typeof partId === "string" && partId) {@@ -372,7 +379,8 @@ export function createGenerationToolRecovery(event?.type !== "tool_end" &&event?.type !== "tool_model_note" &&event?.type !== "document_citations" &&- event?.type !== "compaction_block"+ event?.type !== "compaction_block" &&+ event?.type !== "tool_approved") {return;}@@ -391,6 +399,19 @@ export function createGenerationToolRecovery(}const backendId =typeof event.tool_call_id === "string" ? event.tool_call_id : "";+ // Answered, possibly in another tab: disarm now, not at tool_end. Remembered first so an in-flight+ // seeded check cannot re-arm it; a frame at or below the snapshot names no card armed here yet.+ if (event.type === "tool_approved") {+ if (typeof event.approval_id === "string" && event.approval_id) {+ approved.add(event.approval_id);+ }+ if (seq <= snapshotSeq) return;+ const entry =+ (backendId ? pending.get(backendId) : undefined) ??+ findSavedEntry(backendId, event.approval_id);+ if (entry) disarmApproval(entry);+ return;+ }if (event.tool_name === "deep_research") {if (event.type === "tool_start")researchHandoff.hiddenCallIds.delete(backendId);diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 40c3c74d086..dbc33ec04b5 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -752,6 +752,8 @@ export const ar = {returnToChat: "العودة إلى المحادثة",returnToChats: "العودة إلى المحادثات قيد التشغيل ({count})",chatGenerating: "جارٍ الإنشاء",+ chatAwaitingApproval: "بانتظار الموافقة",+ chatUnread: "غير مقروءة",compare: "مقارنة",search: "بحث",hub: "مركز النماذج",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 06d402e3f88..301588080be 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -756,6 +756,8 @@ export const de = {returnToChat: "Zurück zum Chat",returnToChats: "Zurück zu {count} Chats",chatGenerating: "Wird generiert",+ chatAwaitingApproval: "Wartet auf Freigabe",+ chatUnread: "Ungelesen",compare: "Vergleichen",search: "Suchen",hub: "Modell-Hub",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 781551b9903..8b0303eb906 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -804,6 +804,8 @@ export const en = {returnToChat: "Return to Chat",returnToChats: "Return to {count} Chats",chatGenerating: "Generating",+ chatAwaitingApproval: "Waiting for approval",+ chatUnread: "Unread",compare: "Compare",search: "Search",projects: "Projects",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 071ee90c33f..130f8dcc1f9 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -755,6 +755,8 @@ export const es = {returnToChat: "Volver al chat",returnToChats: "Volver a {count} chats",chatGenerating: "Generando",+ chatAwaitingApproval: "Esperando aprobación",+ chatUnread: "No leído",compare: "Comparar",search: "Buscar",hub: "Centro de modelos",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 532cdc29b17..0d674bddf6a 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -756,6 +756,8 @@ export const fr = {returnToChat: "Retour à la discussion",returnToChats: "Retour à {count} discussions",chatGenerating: "Génération en cours",+ chatAwaitingApproval: "En attente d’approbation",+ chatUnread: "Non lu",compare: "Comparer",search: "Rechercher",hub: "Hub de modèles",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 7e72e94cd9e..2fb419ed900 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -836,6 +836,8 @@ export const he = {returnToChat: "חזרה לצ'אט",returnToChats: "חזרה ל-{count} צ'אטים",chatGenerating: "מייצר תשובה",+ chatAwaitingApproval: "ממתין לאישור",+ chatUnread: "לא נקרא",compare: "השוואה",search: "חיפוש",projects: "פרויקטים",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 1a98edabe4d..6779ccce58f 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -756,6 +756,8 @@ export const hi = {returnToChat: "चैट पर लौटें",returnToChats: "{count} चैट पर लौटें",chatGenerating: "जनरेट हो रहा है",+ chatAwaitingApproval: "अनुमति की प्रतीक्षा में",+ chatUnread: "अपठित",compare: "तुलना करें",search: "खोजें",hub: "मॉडल हब",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 78c4392ae58..396961c3e21 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -657,6 +657,8 @@ export const it = {returnToChat: "Torna alla chat",returnToChats: "Torna alle {count} chat",chatGenerating: "Generazione in corso",+ chatAwaitingApproval: "In attesa di approvazione",+ chatUnread: "Non letta",compare: "Confronta",search: "Cerca",hub: "Hub dei modelli",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 9705e4a2a1d..89084377fcb 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -754,6 +754,8 @@ export const ja = {returnToChat: "チャットに戻る",returnToChats: "{count} 件のチャットに戻る",chatGenerating: "生成中",+ chatAwaitingApproval: "承認待ち",+ chatUnread: "未読",compare: "比較",search: "検索",hub: "モデルハブ",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 2602fd1df28..8b51ecb40fa 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -752,6 +752,8 @@ export const ko = {returnToChat: "채팅으로 돌아가기",returnToChats: "채팅 {count}개로 돌아가기",chatGenerating: "생성 중",+ chatAwaitingApproval: "승인 대기 중",+ chatUnread: "읽지 않음",compare: "비교",search: "검색",hub: "모델 허브",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 22f71d5ab68..ca98570090b 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -755,6 +755,8 @@ export const ptBR = {returnToChat: "Voltar ao chat",returnToChats: "Voltar aos {count} chats",chatGenerating: "Gerando",+ chatAwaitingApproval: "Aguardando aprovação",+ chatUnread: "Não lida",compare: "Comparar",search: "Buscar",hub: "Hub de modelos",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 2ba4c909f93..aaed0fb34ef 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -755,6 +755,8 @@ export const ru = {returnToChat: "Вернуться к чату",returnToChats: "Вернуться к чатам ({count})",chatGenerating: "Генерация",+ chatAwaitingApproval: "Ожидает подтверждения",+ chatUnread: "Непрочитанное",compare: "Сравнить",search: "Поиск",hub: "Хаб моделей",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 1d99d3f8c54..e23e0215996 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -854,6 +854,8 @@ export const sv = {returnToChat: "Tillbaka till chatten",returnToChats: "Tillbaka till {count} chattar",chatGenerating: "Genererar",+ chatAwaitingApproval: "Väntar på godkännande",+ chatUnread: "Oläst",compare: "Jämför",search: "Sök",projects: "Projekt",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex f772be6b96c..f21dd12072b 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -750,6 +750,8 @@ export const zhCN = {returnToChat: "返回聊天",returnToChats: "返回 {count} 个聊天",chatGenerating: "生成中",+ chatAwaitingApproval: "等待批准",+ chatUnread: "未读",compare: "对比",search: "搜索",hub: "模型中心",diff --git a/studio/frontend/tests/approval-waiting-first-turn.test.ts b/studio/frontend/tests/approval-waiting-first-turn.test.tsnew file mode 100644index 00000000000..eed66639858--- /dev/null+++ b/studio/frontend/tests/approval-waiting-first-turn.test.ts@@ -0,0 +1,46 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A first turn runs under "__default" until initialize() adopts it. A call that parks after that must+// be filed under the chat, or its row keeps the spinner instead of the approval mark.++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";++const { store: localStorageFake } = installLocalStorageFake();+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");+register("./thread-sampling-resolver.mjs", import.meta.url);+await import("./helpers/store-stubs/settings-http.ts");+await import("./helpers/store-stubs/chat-history-storage.ts");++const { useChatRuntimeStore } = await import(+ "../src/features/chat/stores/chat-runtime-store.ts"+);++test("a run adopted before its call parks resolves to the chat's key", () => {+ const owner = () => {};+ useChatRuntimeStore.getState().setThreadRunning("__default", true, { owner });+ useChatRuntimeStore.getState().adoptDefaultThreadRun("chat-late");+ assert.equal(+ useChatRuntimeStore.getState().runKeyForOwner("__default", owner),+ "chat-late",+ );+ useChatRuntimeStore+ .getState()+ .setThreadRunning("chat-late", false, { owner });+});++test("the run registers under the owner the adapter later looks its key up by", () => {+ const adapter = readSrc("features/chat/api/chat-adapter.ts");+ assert.match(+ adapter,+ /const confirmationThreadKey = liveThreadKey\(serverCancel\);/,+ );+ assert.match(+ adapter,+ /runtime\.setThreadRunning\(threadKey, true, \{\s*local: !isExternalRequest,\s*owner: serverCancel,\s*\}\);/,+ );+});diff --git a/studio/frontend/tests/approval-waiting.test.ts b/studio/frontend/tests/approval-waiting.test.tsnew file mode 100644index 00000000000..2eb35da9c76--- /dev/null+++ b/studio/frontend/tests/approval-waiting.test.ts@@ -0,0 +1,338 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A chat waiting on an Allow / Deny prompt is marked in the sidebar, and on Desktop the window asks+// for attention. app-sidebar.tsx is .tsx, which node's type stripping cannot import, so its wiring+// is pinned from source.++import assert from "node:assert/strict";+import { register } from "node:module";+import test, { mock } from "node:test";++import { atDefaultUiScale, readSrc } from "./helpers/kit.ts";++const control: { attention?: (number | null | undefined)[] } = {};+const page = { visibilityState: "visible", focused: true };++Object.assign(globalThis, {+ __TAURI_WINDOW_STUB__: control,+ // lib/api-base reads this to decide it is running inside the desktop app.+ window: { __TAURI_INTERNALS__: {}, location: { protocol: "tauri:" } },+ document: {+ get visibilityState() {+ return page.visibilityState;+ },+ hasFocus: () => page.focused,+ },+});++register("./helpers/tauri-window-resolver.mjs", import.meta.url);++mock.timers.enable({ apis: ["setTimeout", "Date"], now: 0 });++const {+ APPROVAL_SETTLE_MS,+ returnToChatThreadId,+ syncApprovalWaiting,+ useApprovalWaitingStore,+ watchApprovalWaiting,+} = await import("../src/features/chat/utils/approval-waiting.ts");++const INFORMATIONAL = 2;++function waiting(): string[] {+ return [...useApprovalWaitingStore.getState().threadIds].sort();+}++function parked(entries: Record<string, string>) {+ return Object.fromEntries(+ Object.entries(entries).map(([id, threadId]) => [id, { threadId }]),+ );+}++// Loaded once up front, so the module's own dynamic import is a cache hit in every case.+await import("@tauri-apps/api/window");++// The attention request is a dynamic import, so wait on the calls rather than a turn count. A case+// expecting none still waits a while, so a call that should not happen has time to land. Real+// time, since setTimeout and Date are mocked.+async function attention(+ expected: number,+): Promise<(number | null | undefined)[]> {+ const deadline = performance.now() + (expected === 0 ? 250 : 10_000);+ while (performance.now() < deadline) {+ if (expected > 0 && (control.attention?.length ?? 0) >= expected) break;+ await new Promise((resolve) => setImmediate(resolve));+ }+ return control.attention ?? [];+}++function reset(background = false) {+ syncApprovalWaiting({});+ control.attention = [];+ page.visibilityState = background ? "hidden" : "visible";+ page.focused = !background;+}++test("a parked call marks its chat only once it has waited out the settle window", () => {+ reset();+ syncApprovalWaiting(parked({ "s:a:1": "chat-a" }));+ assert.deepEqual(waiting(), []);+ mock.timers.tick(APPROVAL_SETTLE_MS - 1);+ assert.deepEqual(waiting(), []);+ mock.timers.tick(1);+ assert.deepEqual(waiting(), ["chat-a"]);+ syncApprovalWaiting({});+ assert.deepEqual(waiting(), [], "an answered call clears at once");+});++test("a call answered inside the settle window never marks its chat or asks for attention", async () => {+ reset(true);+ // "Always allow": the card answers in one request, well inside the window.+ syncApprovalWaiting(parked({ "s:a:1": "chat-a" }));+ mock.timers.tick(50);+ syncApprovalWaiting({});+ mock.timers.tick(APPROVAL_SETTLE_MS * 2);+ assert.deepEqual(waiting(), []);+ assert.deepEqual(await attention(0), []);+});++test("each chat settles on its own clock, and a later call does not delay an earlier one", () => {+ reset();+ syncApprovalWaiting(parked({ "s:a:1": "chat-a" }));+ mock.timers.tick(1_000);+ syncApprovalWaiting(parked({ "s:a:1": "chat-a", "s:b:1": "chat-b" }));+ mock.timers.tick(APPROVAL_SETTLE_MS - 1_000);+ assert.deepEqual(waiting(), ["chat-a"]);+ mock.timers.tick(1_000);+ assert.deepEqual(waiting(), ["chat-a", "chat-b"]);+ syncApprovalWaiting(parked({ "s:b:1": "chat-b" }));+ assert.deepEqual(waiting(), ["chat-b"]);+ reset();+});++test("the store keeps one Set while membership is unchanged, so rows do not re-render", () => {+ reset();+ syncApprovalWaiting(parked({ "s:a:1": "chat-a" }));+ mock.timers.tick(APPROVAL_SETTLE_MS);+ const first = useApprovalWaitingStore.getState().threadIds;+ syncApprovalWaiting(parked({ "s:a:1": "chat-a", "s:a:2": "chat-a" }));+ mock.timers.tick(APPROVAL_SETTLE_MS);+ assert.equal(useApprovalWaitingStore.getState().threadIds, first);+ reset();+});++test("in the background, Desktop asks for attention once per settled call and withdraws it after", async () => {+ reset(true);+ syncApprovalWaiting(parked({ "s:a:1": "chat-a" }));+ assert.deepEqual(await attention(0), [], "nothing before the settle window");+ mock.timers.tick(APPROVAL_SETTLE_MS);+ assert.deepEqual(await attention(1), [INFORMATIONAL]);+ syncApprovalWaiting({});+ assert.deepEqual(await attention(2), [INFORMATIONAL, null]);+});++test("a focused window is not asked for attention, and has nothing to withdraw", async () => {+ reset(false);+ syncApprovalWaiting(parked({ "s:a:1": "chat-a" }));+ mock.timers.tick(APPROVAL_SETTLE_MS);+ assert.deepEqual(waiting(), ["chat-a"], "the sidebar is still marked");+ syncApprovalWaiting({});+ assert.deepEqual(await attention(0), []);+});++test("a run with no saved chat yet asks for attention without marking a row", async () => {+ reset(true);+ syncApprovalWaiting(parked({ "_default:1": "" }));+ mock.timers.tick(APPROVAL_SETTLE_MS);+ assert.deepEqual(waiting(), []);+ assert.deepEqual(await attention(1), [INFORMATIONAL]);+ reset();+});++test("watching follows the store's changes and stopping clears the marks", () => {+ reset();+ type State = { toolConfirmations: Record<string, { threadId: string }> };+ let state: State = { toolConfirmations: {} };+ const listeners = new Set<(next: State, previous: State) => void>();+ const source = {+ getState: () => state,+ subscribe: (listener: (next: State, previous: State) => void) => {+ listeners.add(listener);+ return () => void listeners.delete(listener);+ },+ };+ const set = (next: State) => {+ const previous = state;+ state = next;+ for (const listener of listeners) listener(state, previous);+ };++ const stop = watchApprovalWaiting(source);+ set({ toolConfirmations: parked({ "s:a:1": "chat-a" }) });+ mock.timers.tick(APPROVAL_SETTLE_MS);+ assert.deepEqual(waiting(), ["chat-a"]);+ stop();+ assert.equal(listeners.size, 0);+ assert.deepEqual(waiting(), []);+});++test("both writers record which chat a parked call belongs to", () => {+ const adapter = readSrc("features/chat/api/chat-adapter.ts");+ assert.match(+ adapter,+ /const confirmationThreadKey = liveThreadKey\(serverCancel\);\s*useChatRuntimeStore\s*\.getState\(\)\s*\.setToolConfirmation\(\s*id,\s*approvalId,\s*sandboxSessionId \?\? "",\s*toolConfirmationScopeId,\s*confirmationThreadKey === "__default" \? "" : confirmationThreadKey,/,+ );+ 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*\)/,+ );+});++test("the sidebar watches once and swaps the row spinner for the approval mark", () => {+ const sidebar = atDefaultUiScale(readSrc("components/app-sidebar.tsx"));+ assert.match(+ sidebar,+ /useEffect\(\(\) => watchApprovalWaiting\(useChatRuntimeStore\), \[\]\);/,+ );+ assert.match(+ sidebar,+ /const awaitingApproval =\s*isGenerating &&\s*threadIds\.some\(\(threadId\) => approvalWaitingElsewhere\.has\(threadId\)\);/,+ );+ // Inside the spinner's own anchor, so it takes the same column, padding and hover fade.+ const anchor = sidebar.indexOf("{showWorkSpinner ? (");+ const mark = sidebar.indexOf("{awaitingApproval ? (\n", anchor);+ const spinner = sidebar.indexOf('data-testid="chat-row-spinner"', anchor);+ const anchorEnd = sidebar.indexOf(") : null}", anchor);+ assert.ok(anchor > 0 && anchor < mark && mark < spinner && spinner < anchorEnd);+ assert.match(+ sidebar.slice(mark, spinner),+ /<ApprovalMark testId="chat-row-approval" className="size-3\.5" \/>/,+ );+});++test("the approval mark is a static amber disc with a glyph, apart from the unread dot", () => {+ const sidebar = readSrc("components/app-sidebar.tsx");+ const component = /function ApprovalMark\([\s\S]*?\n\}\n/.exec(sidebar)?.[0] ?? "";+ assert.ok(component, "ApprovalMark not found");+ assert.match(component, /<svg[^>]*aria-hidden="true"/);+ // Amber in both themes, never the accent the unread dot uses.+ assert.match(component, /<circle cx="7" cy="7" r="7" className="fill-amber-700 dark:fill-amber-400" \/>/);+ assert.doesNotMatch(component, /primary/);+ assert.match(component, /<path\s+d="M7 3\.6v4\.1"[\s\S]*?className="stroke-white dark:stroke-neutral-900"/);+ assert.match(component, /<circle cx="7" cy="10\.3" r="1" className="fill-white dark:fill-neutral-900" \/>/);+ // Static: motion is the spinner's cue for work, and the wait can last an hour.+ assert.doesNotMatch(component, /animate-/);+});++test("a waiting or unread row says so in its button's name, and a waiting one is not busy", () => {+ const sidebar = readSrc("components/app-sidebar.tsx");+ const button = sidebar.indexOf('data-testid="recent-thread"');+ const buttonEnd = sidebar.indexOf("</SidebarMenuButton>", button);+ assert.ok(button > 0 && buttonEnd > button);+ const row = sidebar.slice(button, buttonEnd);+ assert.match(row, /aria-busy=\{\(isGenerating && !awaitingApproval\) \|\| undefined\}/);+ assert.match(+ row,+ /\{awaitingApproval \? \(\s*<span className="sr-only"> \{translate\("shell\.navigation\.chatAwaitingApproval"\)\}<\/span>\s*\) : hasUnreadActivity \? \(\s*<span className="sr-only"> \{translate\("shell\.navigation\.chatUnread"\)\}<\/span>\s*\) : null\}/,+ );+});++test("the New Chat item shows the mark instead of its spinner while a chat waits", () => {+ const sidebar = readSrc("components/app-sidebar.tsx");+ assert.match(+ sidebar,+ /const anyChatWaiting = useMemo\(\s*\(\) => \[\.\.\.approvalWaitingElsewhere\]\.some\(\(id\) => runningByThreadId\[id\]\),/,+ );+ // On every route, since the waiting chat's own row may not be on screen.+ assert.match(+ sidebar,+ /waiting=\{\s*anyChatWaiting\s*\? t\("shell\.navigation\.chatAwaitingApproval"\)\s*: undefined\s*\}/,+ );+ const navItem = /function NavItem\([\s\S]*?\n\}\n/.exec(sidebar)?.[0] ?? "";+ assert.ok(navItem, "NavItem not found");+ assert.match(navItem, /data-spinner=\{spinner && !waiting \? "true" : undefined\}/);+ assert.match(+ navItem,+ /\{waiting \? \(\s*<>\s*<span className="sr-only"> \{waiting\}<\/span>[\s\S]*?<ApprovalMark className="ml-auto mr-1\.5 size-3\.5 group-data-\[collapsible=icon\]:hidden" \/>\s*<\/>\s*\) : \(\s*spinner && \(/,+ );+ assert.match(+ navItem,+ /\{waiting \? \(\s*<ApprovalMark\s+testId="nav-approval"\s+className="pointer-events-none absolute right-1 top-1 hidden size-2\.5 group-data-\[collapsible=icon\]:block"\s+\/>\s*\) : \(\s*spinner && \(\s*<Spinner className="pointer-events-none absolute right-1 top-1/,+ );+});++test("the open chat is left out of the waiting marks: its card is on screen", () => {+ const sidebar = readSrc("components/app-sidebar.tsx");+ const owner =+ /const approvalWaitingElsewhere = useMemo\(\(\) => \{[\s\S]*?\n \}, \[[^\]]*\]\);/.exec(sidebar)?.[0] ?? "";+ assert.ok(owner, "approvalWaitingElsewhere not found");+ // Only the chat route has an open chat; elsewhere every waiting chat is marked.+ assert.match(owner, /if \(!activeThreadId\) return approvalWaitingThreadIds;/);+ // A compare chat is open as its pair id while its panes wait under their own ids.+ assert.match(owner, /const open = allChatItems\.find\(\(item\) => item\.id === activeThreadId\);/);+ assert.match(owner, /new Set\(open \? getSidebarItemThreadIds\(open\) : \[activeThreadId\]\)/);+ assert.match(owner, /\.filter\(\(id\) => !openIds\.has\(id\)\)/);+ assert.match(owner, /\[approvalWaitingThreadIds, activeThreadId, allChatItems\]/);+ // Defined after the open chat is known, and the only reader of the raw store besides it.+ assert.ok(sidebar.indexOf("const activeThreadId = isChatRoute") < sidebar.indexOf("const approvalWaitingElsewhere"));+ const readers = sidebar.match(/approvalWaitingThreadIds/g) ?? [];+ assert.equal(readers.length, 4, "a reader skips the open-chat exclusion");+});++test("Return to Chat opens the newest waiting chat while one waits, else the newest running one", () => {+ const running = { "chat-a": true, "chat-b": true, "chat-c": false };+ assert.equal(returnToChatThreadId(running, new Set()), "chat-b");+ // The older chat waits while the newer one generates: the row's mark is chat-a's.+ assert.equal(returnToChatThreadId(running, new Set(["chat-a"])), "chat-a");+ assert.equal(returnToChatThreadId(running, new Set(["chat-a", "chat-b"])), "chat-b");+ // A stale wait on a chat that stopped running does not count.+ assert.equal(returnToChatThreadId(running, new Set(["chat-c"])), "chat-b");+ assert.equal(returnToChatThreadId({}, new Set(["chat-a"])), null);+});++test("Return to Chat targets a waiting chat whenever the row shows the mark", () => {+ const sidebar = readSrc("components/app-sidebar.tsx");+ const target =+ /const runningTarget = useMemo\(\(\) => \{[\s\S]*?\n \}, \[[^\]]*\]\);/.exec(sidebar)?.[0] ?? "";+ assert.ok(target, "runningTarget not found");+ assert.match(target, /returnToChatThreadId\(runningByThreadId, approvalWaitingElsewhere\)/);+ assert.match(target, /\[runningByThreadId, approvalWaitingElsewhere, allChatItems\]/);+});++test("a first turn parked before its chat had an id marks the row once the run is adopted", () => {+ reset();+ syncApprovalWaiting(parked({ "s:_default:1": "" }));+ mock.timers.tick(APPROVAL_SETTLE_MS);+ assert.deepEqual(waiting(), []);+ syncApprovalWaiting(parked({ "s:_default:1": "chat-new" }));+ assert.deepEqual(waiting(), ["chat-new"]);+ reset();+});++test("adopting a first turn hands its unkeyed parked calls the chat id, and only those", async () => {+ const { adoptFirstTurnConfirmations } = await import(+ "../src/features/chat/utils/adopt-first-turn-confirmations.ts"+ );+ const before = {+ a: { threadId: "", approvalId: "x" },+ b: { threadId: "chat-b", approvalId: "y" },+ };+ assert.deepEqual(adoptFirstTurnConfirmations(before, "chat-new"), {+ a: { threadId: "chat-new", approvalId: "x" },+ b: { threadId: "chat-b", approvalId: "y" },+ });+ assert.equal(before.a.threadId, "");+ assert.equal(adoptFirstTurnConfirmations({ b: before.b }, "chat-new"), null);++ const store = readSrc("features/chat/stores/chat-runtime-store.ts");+ const adopt = store.slice(+ store.indexOf("adoptDefaultThreadRun: (threadId) =>"),+ store.indexOf("runKeyForOwner: (fallbackKey, owner) =>"),+ );+ assert.match(+ adopt,+ /if \(moved\.runningByThreadId\) \{[\s\S]*adoptFirstTurnConfirmations\([\s\S]*state\.toolConfirmations,[\s\S]*moved\.toolConfirmations = confirmations/,+ );+});diff --git a/studio/frontend/tests/generation-tool-recovery-approvals.test.ts b/studio/frontend/tests/generation-tool-recovery-approvals.test.tsindex 08d85f99d07..3c93eb0e378 100644--- a/studio/frontend/tests/generation-tool-recovery-approvals.test.ts+++ b/studio/frontend/tests/generation-tool-recovery-approvals.test.ts@@ -179,6 +179,58 @@ test("the decision goes away when the call gets a result", async () => {assert.equal(spy.live.size, 0, "no Approve/Deny over a finished result");});+// Answered in another tab: this one must stop offering the decision as soon as the backend says so,+// not at tool_end, which only comes after the tool has run.+test("the decision goes away when another tab approves the call", async () => {+ const spy = spyConfirmations();+ const carried: { at: number; part: unknown }[] = [];+ const recovery = createGenerationToolRecovery(carried, "run-1", 0, spy.hooks);++ recovery.apply(parkedStart("appr-1"), 0, 1, "sess-1");+ const part = carried[0].part as Record<string, unknown>;+ assert.equal(spy.live.size, 1);++ recovery.apply(+ {+ _toolEvent: {+ type: "tool_approved",+ tool_name: "terminal",+ tool_call_id: "call-1",+ approval_id: "appr-1",+ },+ },+ 0,+ 2,+ "sess-1",+ );+ assert.deepEqual(spy.resolved, [part.toolCallId]);+ assert.equal(spy.live.size, 0, "no Approve/Deny while the approved call runs");+ const after = carried[0].part as Record<string, unknown>;+ assert.equal(after.result, undefined, "the card keeps running until tool_end");+});++test("an approval older than the snapshot leaves the seeded check in charge", async () => {+ const spy = spyConfirmations();+ const carried: { at: number; part: unknown }[] = [];+ const recovery = createGenerationToolRecovery(carried, "run-1", 5, spy.hooks);++ recovery.apply(+ {+ _toolEvent: {+ type: "tool_approved",+ tool_name: "terminal",+ tool_call_id: "call-1",+ approval_id: "appr-1",+ },+ },+ 0,+ 3,+ "sess-1",+ );+ assert.deepEqual(spy.resolved, []);+ assert.equal(carried.length, 0, "an approval frame never mints a card");+});+test("a call that never needed a decision arms nothing", async () => {const spy = spyConfirmations();const carried: { at: number; part: unknown }[] = [];@@ -362,6 +414,56 @@ test("a card finished while its status request was in flight is not armed afterw);});+// The status answer was taken before another tab approved the call, so it still says pending. The+// approval frame that arrived meanwhile is the newer fact and has to win.+test("a call approved while its status request was in flight is not armed afterwards", async () => {+ const spy = spyConfirmations();+ const carried = [+ {+ at: 12,+ part: {+ type: "tool-call",+ toolCallId: "sess-1:thread-1:appr-9",+ toolName: "terminal",+ backendToolCallId: "call-9",+ toolApprovalId: "appr-9",+ args: { command: "du -sh ~/models" },+ },+ },+ ];+ const recovery = createGenerationToolRecovery(+ carried,+ "run-1",+ 40,+ spy.hooks,+ );++ let release: (value: boolean) => void = () => {};+ const gate = new Promise<boolean>((resolve) => {+ release = resolve;+ });+ const arming = recovery.armSeededApprovals("sess-1", () => gate);++ recovery.apply(+ {+ _toolEvent: {+ type: "tool_approved",+ tool_name: "terminal",+ tool_call_id: "call-9",+ approval_id: "appr-9",+ },+ },+ 0,+ 41,+ "sess-1",+ );+ release(true);+ await arming;++ assert.deepEqual(spy.registered, [], "an approved call never offers Allow / Deny again");+ assert.equal(spy.live.size, 0);+});+test("a card still unresolved when the status request returns is armed as before", async () => {const spy = spyConfirmations();const carried = [diff --git a/studio/frontend/tests/generation-tool-recovery.test.ts b/studio/frontend/tests/generation-tool-recovery.test.tsindex 9ca1162ceaa..4abf9c41f14 100644--- a/studio/frontend/tests/generation-tool-recovery.test.ts+++ b/studio/frontend/tests/generation-tool-recovery.test.ts@@ -382,6 +382,7 @@ test("the live adapter saves identities for ordinary, approval and provider card]: [];const confirmed: string[] = [];+ const confirmedThreads: string[] = [];const context = vm.createContext({toolCallParts: parts,toolPartIdByBackendId: new Map(@@ -389,7 +390,11 @@ test("the live adapter saves identities for ordinary, approval and provider card),toolConfirmationIdsByBackendId: new Map(),toolConfirmationScopeId: "session:thread",+ resolvedThreadId: "thread",sandboxSessionId: "session",+ // The run's key when the call parks, which can differ from the one captured at send.+ serverCancel: () => {},+ liveThreadKey: () => "thread-live",generationRunId,generationSeq: 7,cumulativeText: "",@@ -404,7 +409,16 @@ test("the live adapter saves identities for ordinary, approval and provider cardgetState: () => ({clearToolLiveOutput() {},clearToolFullOutput() {},- setToolConfirmation: (id: string) => confirmed.push(id),+ setToolConfirmation: (+ id: string,+ _approvalId: string,+ _sessionId: string,+ _scopeId: string,+ threadId: string,+ ) => {+ confirmed.push(id);+ confirmedThreads.push(threadId);+ },}),},});@@ -439,6 +453,10 @@ test("the live adapter saves identities for ordinary, approval and provider cardconfirmed,kind === "approval" ? [saved.toolCallId] : [],);+ assert.deepEqual(+ confirmedThreads,+ kind === "approval" ? ["thread-live"] : [],+ );const carried = [{ at: 0, part: saved }];const replay = createGenerationToolRecovery(carried, "run", 7);assert.equal(replay.replayFrom, 7);diff --git a/studio/frontend/tests/helpers/tauri-window-stub.mjs b/studio/frontend/tests/helpers/tauri-window-stub.mjsindex 79ced33a864..1194b03f1e9 100644--- a/studio/frontend/tests/helpers/tauri-window-stub.mjs+++ b/studio/frontend/tests/helpers/tauri-window-stub.mjs@@ -14,9 +14,17 @@ export function getCurrentWebview() {};}+export const UserAttentionType = { Critical: 1, Informational: 2 };+export function getCurrentWindow() {return {onScaleChanged: async () => () => undefined,scaleFactor: async () => 1,+ requestUserAttention: async (type) => {+ if (!control.attention) {+ control.attention = [];+ }+ control.attention.push(type);+ },};}diff --git a/studio/frontend/tests/sidebar-row-actions.test.ts b/studio/frontend/tests/sidebar-row-actions.test.tsindex 9dc6f8f5dc1..0f84d02b1eb 100644--- a/studio/frontend/tests/sidebar-row-actions.test.ts+++ b/studio/frontend/tests/sidebar-row-actions.test.ts@@ -81,7 +81,7 @@ test("every chat row offers the pin without opening a menu", () => {test("a chat row reserves one gutter, whatever its state", () => {assert.match(APP_SIDEBAR,- /showWorkSpinner \? "pr-16" : hasUnreadActivity \? "pr-7" : showForkMark \? "pr-9" : undefined,/,+ /showWorkSpinner \? "pr-16" : hasUnreadActivity \|\| showForkMark \? "pr-9" : undefined,/,);// The fork mark sits in the trailing column in grey, not inline after the title.assert.match(diff --git a/studio/frontend/tests/sidebar-spinner-column.test.ts b/studio/frontend/tests/sidebar-spinner-column.test.tsindex a0d9975bb47..278e9860260 100644--- a/studio/frontend/tests/sidebar-spinner-column.test.ts+++ b/studio/frontend/tests/sidebar-spinner-column.test.ts@@ -57,6 +57,58 @@ test("nav and Recents spinners land on one trailing column", async () => {});// The kebab overlays the row's right edge, so a spinner row must pad past it.+// The spinner, the waiting-for-approval dot and the unread dot take turns in one slot; a dot off+// that centre reads as misaligned next to a spinner or a dot in the row above.+test("the Recents spinner, the approval mark and the unread dot share one centre", () => {+ const centre = (anchor: string, box: string) => inset(anchor, "right") + inset(box, "size") / 2;+ const spinnerAnchor = grab(+ APP_SIDEBAR,+ /className=\{cn\(\s*"(pointer-events-none absolute right-[0-9.]+[^"]*)"[\s\S]{0,1200}?data-testid="chat-row-spinner"/,+ "Recents chat spinner anchor",+ );+ const spinner = grab(+ APP_SIDEBAR,+ /data-testid="chat-row-spinner"[\s\S]{0,400}?className="([^"]*)"/,+ "Recents chat spinner",+ );+ const approvalBox = grab(+ APP_SIDEBAR,+ /<ApprovalMark testId="chat-row-approval" className="([^"]*)"/,+ "approval mark",+ );+ const unreadAnchor = grab(+ APP_SIDEBAR,+ /\{hasUnreadActivity \? \([\s\S]{0,200}?className=\{cn\(\s*"([^"]*)"/,+ "unread dot anchor",+ );++ const spinnerCentre = centre(spinnerAnchor, spinner);+ assert.equal(spinnerCentre, 23);+ assert.equal(centre(spinnerAnchor, approvalBox), spinnerCentre);+ assert.equal(centre(unreadAnchor, unreadAnchor), spinnerCentre, "the unread dot left the spinner's column");+});++test("every trailing mark yields to the row actions on hover, an open menu and keyboard focus", () => {+ const marks: [string, RegExp][] = [+ ["spinner", /\{showWorkSpinner \? \([\s\S]{0,1600}?\{awaitingApproval \? \(/],+ ["unread dot", /\{hasUnreadActivity \? \([\s\S]{0,900}?aria-hidden/],+ ["fork mark", /\{showForkMark \? \([\s\S]{0,1600}?<GitBranchIcon/],+ ];+ for (const [name, pattern] of marks) {+ const block = pattern.exec(APP_SIDEBAR)?.[0] ?? "";+ assert.ok(block, `could not find the ${name}`);+ for (const group of ["recent-item", "project-chat-item"]) {+ for (const fade of [+ `group-hover/${group}:opacity-0`,+ `group-has-[.sidebar-row-action[data-state=open]]/${group}:opacity-0`,+ `group-has-[.sidebar-row-action:focus-visible]/${group}:opacity-0`,+ ]) {+ assert.ok(block.includes(fade), `the ${name} lacks ${fade}`);+ }+ }+ }+});+test("a working Recents row clears the kebab on hover", async () => {const [source, css] = await Promise.all([atDefaultUiScale(readSrc("components/app-sidebar.tsx")),diff --git a/studio/frontend/tests/tool-approved-frame.test.ts b/studio/frontend/tests/tool-approved-frame.test.tsnew file mode 100644index 00000000000..0a03f4bcda3--- /dev/null+++ b/studio/frontend/tests/tool-approved-frame.test.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A call approved in another tab or device: the backend sends tool_approved, and every follower drops+// its Allow / Deny (and the sidebar's waiting dot) then, instead of at tool_end after the tool has run.++import assert from "node:assert/strict";+import test from "node:test";+import vm from "node:vm";+import ts from "@typescript/typescript6";++import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { normalizeChatGenerationChunkPayload } = await import(+ "../src/features/chat/api/chat-generation-api.ts"+);++const frame = {+ type: "tool_approved",+ tool_name: "python",+ tool_call_id: "call_0",+ approval_id: "approval-1",+};++test("a persisted tool_approved frame is re-tagged like the live stream", () => {+ assert.deepEqual(normalizeChatGenerationChunkPayload(frame), {+ _toolEvent: frame,+ });+});++test("the live stream routes tool_approved off the transcript", () => {+ const src = readSrc("features/chat/api/chat-api.ts");+ assert.match(+ src,+ /parsed\.type === "tool_approved"\)\s*\) \{\s*yield \{ _toolEvent: parsed \}/,+ );+});++// The adapter's handler runs as written: its block is cut out of chat-adapter.ts and run against the+// same maps the tool_start branch fills.+function liveHandler() {+ const adapter = readSrc("features/chat/api/chat-adapter.ts");+ const startAt = adapter.indexOf('if (toolEvent.type === "tool_approved") {');+ const endAt = adapter.indexOf(+ "// Persist container_id onto the thread",+ startAt,+ );+ assert.ok(startAt >= 0 && endAt > startAt);+ const source = `function receive(events) { for (const toolEvent of events) { ${adapter.slice(startAt, endAt)} } }`;+ return ts.transpileModule(source, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+}++function run(+ confirmationIds: [string, string][],+ parts: Record<string, unknown>[],+ events: Record<string, unknown>[],+) {+ const cleared: string[] = [];+ const context = vm.createContext({+ toolConfirmationIdsByBackendId: new Map(confirmationIds),+ toolCallParts: parts,+ useChatRuntimeStore: {+ getState: () => ({+ clearToolConfirmation: (id: string) => cleared.push(id),+ }),+ },+ });+ vm.runInContext(liveHandler(), context);+ context.receive(events);+ return cleared;+}++test("the live stream clears the parked card the approval names", () => {+ assert.deepEqual(+ run(+ [["call_0", "session:thread:approval-1"]],+ [{ toolCallId: "session:thread:approval-1", toolApprovalId: "approval-1" }],+ [frame],+ ),+ ["session:thread:approval-1"],+ );+});++test("an id-less call is found by its approval id", () => {+ assert.deepEqual(+ run(+ [],+ [+ { toolCallId: "other", toolApprovalId: "approval-0" },+ { toolCallId: "session:thread:approval-1", toolApprovalId: "approval-1" },+ ],+ [{ ...frame, tool_call_id: "" }],+ ),+ ["session:thread:approval-1"],+ );+});++test("an approval for a call this stream never parked clears nothing", () => {+ assert.deepEqual(+ run([], [{ toolCallId: "call_9:live" }], [{ ...frame, tool_call_id: "call_9", approval_id: "" }]),+ [],+ );+});diff --git a/studio/frontend/tests/window-permissions.test.ts b/studio/frontend/tests/window-permissions.test.tsindex fd798ac9246..a0694b3d9ac 100644--- a/studio/frontend/tests/window-permissions.test.ts+++ b/studio/frontend/tests/window-permissions.test.ts@@ -11,7 +11,7 @@ const CAPABILITIES = new URL(import.meta.url,);const WINDOW_SETTER =- /\b(?:win|appWindow|getCurrentWindow\(\))\.(set\w+|maximize|unmaximize|minimize|unminimize|toggleMaximize|show|hide|center|close|start\w+)\(/g;+ /\b(?:win|appWindow|getCurrentWindow\(\))\.(set\w+|maximize|unmaximize|minimize|unminimize|toggleMaximize|show|hide|center|close|start\w+|request\w+)\(/g;const SOURCE_FILE = /\.tsx?$/;const toPermission = (method: string) =>`core:window:allow-${method.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;diff --git a/studio/src-tauri/capabilities/default.json b/studio/src-tauri/capabilities/default.jsonindex 132b1d9ae90..db716ccc870 100644--- a/studio/src-tauri/capabilities/default.json+++ b/studio/src-tauri/capabilities/default.json@@ -8,6 +8,7 @@"core:window:allow-show","core:window:allow-hide","core:window:allow-set-focus",+ "core:window:allow-request-user-attention","core:window:allow-set-position","core:window:allow-set-size","core:window:allow-set-resizable",diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex cc7820bb18f..96a05692699 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -1471,26 +1471,28 @@ def _escapes_the_model(tag: str) -> str | None:def _touch_spinner_reach(block: str, spacing: float) -> tuple[str, float] | None:"""The spinner must clear the title too, not just the actions, or the touch gutter is too narrow."""- gate = next(- (- found- for found in re.finditer(r"\{\s*([A-Za-z_$][\w$]*)\s*\?\s*\(", block)- if re.match(r"\s*<span", block[found.end() :])- ),- None,- )- if not gate:++ def branch_end(gate: re.Match) -> int | None:+ depth = 0+ for index in range(gate.end() - 1, len(block)):+ if block[index] == "(":+ depth += 1+ elif block[index] == ")":+ depth -= 1+ if depth == 0:+ return indexreturn None- depth, end = 0, None- for index in range(gate.end() - 1, len(block)):- if block[index] == "(":- depth += 1- elif block[index] == ")":- depth -= 1- if depth == 0:- end = index- break- if end is None:++ # The span gate that renders the spinner: the row also has span gates for its screen-reader labels.+ gate, end = None, None+ for found in re.finditer(r"\{\s*([A-Za-z_$][\w$]*)\s*\?\s*\(", block):+ if not re.match(r"\s*<span", block[found.end() :]):+ continue+ found_end = branch_end(found)+ if found_end is not None and "<Spinner" in block[found.end() : found_end]:+ gate, end = found, found_end+ break+ if gate is None:return Nonerendered = block[gate.end() : end]# An inline style or transform on the positioning span changes the reach without `right`.