Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: browser use follow-ups (safetensors nudge, date fields, disabled dropdowns, moved pages) (#13429)

Daniel Han6a01c5559a8e
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 7e7e7285d69..5858d12ce82 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -786,6 +786,10 @@ def run_safetensors_tool_loop(
final_attempt_done = False
next_call_id = 0
reprompt_count = 0
+ # A browser task is many steps, each a chance to announce the next one and stop: there one
+ # nudge per tool turn, as in the GGUF and external loops; other requests never nudge after a tool.
+ browser_turns = any(name in BROWSER_TOOL_NAMES for name in _active_tool_names(tools or []))
+ post_tool_reprompts = 0
# Text that triggered the last nudge; if the retry restates it, stop (GGUF parity).
last_reprompt_text = ""
# A denied tool confirmation must not be answered with a plan-without-action
@@ -813,7 +817,11 @@ def run_safetensors_tool_loop(
_state_draining = 2
# Reserve re-prompt slots so they don't eat the caller's tool budget.
- _extra_iters = MAX_ACT_REPROMPTS if max_tool_iterations > 0 else 0
+ _extra_iters = (
+ MAX_ACT_REPROMPTS + (max_tool_iterations if browser_turns else 0)
+ if max_tool_iterations > 0
+ else 0
+ )
for iteration in range(max_tool_iterations + _extra_iters + 1):
if cancel_event is not None and cancel_event.is_set():
return
@@ -1283,14 +1291,20 @@ def run_safetensors_tool_loop(
content_accum,
reasoning_prefilled = reasoning_prefilled,
)
+ already_acted = any(record.executed for record in tool_controller.history)
if (
auto_heal_tool_calls
and nudge_enabled(nudge_tool_calls)
and active_tools
- and reprompt_count < MAX_ACT_REPROMPTS
- and not rag_autoinjected
+ and (
+ post_tool_reprompts < 1
+ if already_acted
+ else reprompt_count < MAX_ACT_REPROMPTS
+ )
+ # Retrieval injected up front is no reason to stop a browser task mid-way.
+ and (not rag_autoinjected or (browser_turns and already_acted))
and not tool_denied
- and not any(record.executed for record in tool_controller.history)
+ and (browser_turns or not already_acted)
and not is_reprompt_repeat(intent_text, last_reprompt_text)
and is_short_intent_without_action(intent_text)
# Markup stripped first: a call fenced inside <tool_call> is not an answer.
@@ -1306,13 +1320,16 @@ def run_safetensors_tool_loop(
)
)
):
- reprompt_count += 1
+ if already_acted:
+ post_tool_reprompts += 1
+ else:
+ reprompt_count += 1
last_reprompt_text = intent_text
logger.info(
"Safetensors re-prompt %d/%d: model responded without "
"calling tools (%d chars)",
- reprompt_count,
- MAX_ACT_REPROMPTS,
+ post_tool_reprompts if already_acted else reprompt_count,
+ 1 if already_acted else MAX_ACT_REPROMPTS,
len(intent_text),
)
# Merges into a resumed partial: the nudge that follows is a user
@@ -1854,6 +1871,10 @@ def run_safetensors_tool_loop(
# consume budget so the model gets its nudge and another tool-enabled turn (GGUF parity).
if _turn_executed_real_tool:
_executed_tool_iters += 1
+ post_tool_reprompts = 0
+ if browser_turns:
+ # A new step may stall in the same words as the last one (external loop parity).
+ last_reprompt_text = ""
if _executed_tool_iters >= max_tool_iterations and not final_attempt_done:
final_attempt_done = True
if over_cap:
diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.py
index c4d598d88bd..fe96399cbb9 100644
--- a/studio/backend/tests/test_safetensors_tool_loop.py
+++ b/studio/backend/tests/test_safetensors_tool_loop.py
@@ -5895,3 +5895,118 @@ def test_every_independent_edit_gets_its_own_verification_rerun():
"edit_file",
"terminal",
]
+
+
+def _post_tool_stall(
+ tool_name,
+ arguments,
+ replies,
+ also = (),
+):
+ """One tool call, then the scripted replies, recording every prompt the model saw."""
+ captured: list[list] = []
+ call = '<tool_call>{"name":"%s","arguments":%s}</tool_call>' % (tool_name, arguments)
+ script = [call, *replies]
+
+ def fake_single_turn(messages, active_tools = None):
+ captured.append(list(messages))
+ yield script[len(captured) - 1] if len(captured) <= len(script) else "Done."
+
+ exec_fn = FakeExecuteTool([])
+ _collect_events(
+ run_safetensors_tool_loop(
+ single_turn = fake_single_turn,
+ messages = [{"role": "user", "content": "go"}],
+ tools = [{"type": "function", "function": {"name": name}} for name in (tool_name, *also)],
+ execute_tool = exec_fn,
+ auto_heal_tool_calls = True,
+ nudge_tool_calls = True,
+ max_tool_iterations = 5,
+ )
+ )
+ return captured, exec_fn
+
+
+def test_browser_turns_get_a_post_tool_nudge():
+ # A browser step announced and not taken would end the task: GGUF and external parity.
+ call = '<tool_call>{"name":"browser_click","arguments":{"ref":"r2"}}</tool_call>'
+ captured, exec_fn = _post_tool_stall(
+ "browser_snapshot",
+ "{}",
+ ["I'll click the first result.", call, "The title is X."],
+ also = ("browser_click",),
+ )
+ assert [name for name, _ in exec_fn.calls] == ["browser_snapshot", "browser_click"]
+ assert captured[2][-1]["role"] == "user"
+
+
+def test_other_tools_still_never_nudge_after_a_tool():
+ captured, exec_fn = _post_tool_stall("web_search", '{"query":"x"}', ["I'll search again."])
+ assert [name for name, _ in exec_fn.calls] == ["web_search"]
+ assert len(captured) == 2, captured
+
+
+def test_a_browser_tool_turn_allows_one_nudge():
+ captured, exec_fn = _post_tool_stall(
+ "browser_snapshot", "{}", ["I'll click the first result.", "Let me click it now."]
+ )
+ assert [name for name, _ in exec_fn.calls] == ["browser_snapshot"]
+ # The call, the stall, one nudged retry: the second stall in the same tool turn is the answer.
+ assert len(captured) == 3, captured
+
+
+def test_the_same_stall_words_in_a_later_browser_turn_are_nudged_again():
+ stall = "I'll click it now."
+ click = '<tool_call>{"name":"browser_click","arguments":{"ref":"r2"}}</tool_call>'
+ captured, exec_fn = _post_tool_stall(
+ "browser_snapshot", "{}", [stall, click, stall, click, "Done."], also = ("browser_click",)
+ )
+ assert [name for name, _ in exec_fn.calls] == [
+ "browser_snapshot",
+ "browser_click",
+ "browser_click",
+ ]
+
+
+def test_a_browser_turn_is_nudged_after_retrieval_was_injected(monkeypatch):
+ import core.inference.tools as tools_module
+
+ monkeypatch.setattr(
+ tools_module,
+ "build_rag_autoinject",
+ lambda *a, **k: {
+ "events": [],
+ "messages": [{"role": "user", "content": "Notes: background."}],
+ },
+ )
+ click = '<tool_call>{"name":"browser_click","arguments":{"ref":"r2"}}</tool_call>'
+ captured: list[list] = []
+ script = [
+ '<tool_call>{"name":"browser_snapshot","arguments":{}}</tool_call>',
+ "I'll click it now.",
+ click,
+ "Done.",
+ ]
+
+ def fake_single_turn(messages, active_tools = None):
+ captured.append(list(messages))
+ yield script[len(captured) - 1] if len(captured) <= len(script) else "Done."
+
+ exec_fn = FakeExecuteTool([])
+ _collect_events(
+ run_safetensors_tool_loop(
+ single_turn = fake_single_turn,
+ messages = [{"role": "user", "content": "go"}],
+ tools = [
+ {"type": "function", "function": {"name": "browser_snapshot"}},
+ {"type": "function", "function": {"name": "browser_click"}},
+ {"type": "function", "function": {"name": "search_knowledge_base"}},
+ ],
+ execute_tool = exec_fn,
+ auto_heal_tool_calls = True,
+ nudge_tool_calls = True,
+ max_tool_iterations = 5,
+ rag_scope = {"kind": "thread", "thread_id": "t"},
+ )
+ )
+ assert [name for name, _ in exec_fn.calls] == ["browser_snapshot", "browser_click"]
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index a52bd83ab3d..d0282e85547 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -356,7 +356,7 @@ import { MicIcon } from "@/lib/mic-icon";
import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { Tick02Icon } from "@/lib/tick-icon";
-import { BrowserAgentMenuItem, BrowserAgentPill } from "@/features/browser/agent/composer-toggle";
+import { BrowserAgentMenuItem, BrowserAgentPill } from "@/features/browser/agent/lazy-composer-toggle";
import {
BranchNextIcon,
BranchPrevIcon,
diff --git a/studio/frontend/src/features/browser/agent/executor.ts b/studio/frontend/src/features/browser/agent/executor.ts
index 1e53ace7e3a..923845da8dd 100644
--- a/studio/frontend/src/features/browser/agent/executor.ts
+++ b/studio/frontend/src/features/browser/agent/executor.ts
@@ -224,6 +224,7 @@ const AGENT_ERRORS = [
/^r\d{1,9} is covered by an overlay; snapshot to find its close button, or scroll first\.$/,
/^r\d{1,9} is not a text field\.$/,
/^r\d{1,9} is disabled or read-only\.$/,
+ /^r\d{1,9} takes a value like (2026-03-14|09:30|2026-03-14T09:30|2026-03|2026-W11)\.$/,
/^r\d{1,9} is a radio button; select another option in its group instead\.$/,
/^that key does nothing in this field; click or type instead\.$/,
/^r\d{1,9} has no such option; snapshot it to see its options\.$/,
@@ -269,6 +270,7 @@ function checkedAnswer(value: unknown): AgentAnswer | null {
formHasPassword: info.formHasPassword === true,
submits: info.submits === true,
...(typeof info.option === "string" ? { option: info.option.slice(0, 200) } : {}),
+ ...(typeof info.submitter === "string" ? { submitter: info.submitter.slice(0, 200) } : {}),
}
: undefined,
};
@@ -366,8 +368,12 @@ async function observe(tab: BrowserTab, note?: string, op: Record<string, unknow
}
const answer = await pageCall(tab, op);
if (!answer.ok) return { ok: false, error: answer.error ?? "the page could not be read." };
- if (op.op === "snapshot" || op.op === "find") pageLinks = new Set(answer.links ?? []);
const fresh = useBrowserStore.getState().tabs.find((candidate) => candidate.id === tab.id) ?? tab;
+ // A page that moved during the read is one nobody checked: its words and links stay out.
+ if (fresh.loading || tabUrl(fresh) !== tabUrl(tab)) {
+ return { ok: false, error: "the page changed while it was being read; take a snapshot again." };
+ }
+ if (op.op === "snapshot" || op.op === "find") pageLinks = new Set(answer.links ?? []);
return {
ok: true,
url: tabUrl(fresh),
@@ -515,6 +521,8 @@ async function perform(action: BrowserAction, context: ActionContext): Promise<R
if (action.op === "select") {
// The option the page will select: its value can differ from the label the user sees.
const chosen = info.role === "combobox" ? { ...info, name: info.option || action.value || "" } : info;
+ // A card-expiry or other secret dropdown is the user's to fill, as its text field would be.
+ if (info.tag === "select" || info.role === "combobox") gates.push(gateElement("type", info, before, action.policy, permissions()));
gates.push(gateElement("select", chosen, before, action.policy, permissions()));
}
// Enter or Space on a focused button or link is a click on it, so it asks what a click would.
diff --git a/studio/frontend/src/features/browser/agent/gate.ts b/studio/frontend/src/features/browser/agent/gate.ts
index 35b833e08b0..acded278451 100644
--- a/studio/frontend/src/features/browser/agent/gate.ts
+++ b/studio/frontend/src/features/browser/agent/gate.ts
@@ -213,13 +213,15 @@ export function gateElement(
return { kind: "ask", ask: "submit", host, name: "", prompt: `Submit this form on ${host}?`, detail: describe(info) };
}
// A link mostly just opens a page ("Sign in" goes to the sign-in form), so fewer words count there.
- const consequential = (info.role === "link" ? CONSEQUENTIAL_LINK : CONSEQUENTIAL).test(info.name) || LOCALIZED.test(info.name);
+ // Enter in a field presses the form's default button: its words count as a click on it would.
+ const label = action === "submit" && info.submitter ? info.submitter : info.name;
+ const consequential = (info.role === "link" ? CONSEQUENTIAL_LINK : CONSEQUENTIAL).test(label) || LOCALIZED.test(label);
// Selecting a checkbox, radio or switch is a click on it.
// A select is a click: on a checkbox, its name; on a dropdown, the option chosen (the executor
// passes it as the name), since a page can act on the change event.
const clicks = action === "click" || submits || action === "select";
if (clicks && consequential) {
- return { kind: "ask", ask: "click", host, name: clip(info.name), prompt: `Click “${clip(info.name)}” on ${host}?`, detail: describe(info) };
+ return { kind: "ask", ask: "click", host, name: clip(label), prompt: `Click “${clip(label)}” on ${host}?`, detail: describe(info) };
}
return ALLOW;
}
diff --git a/studio/frontend/src/features/browser/agent/lazy-composer-toggle.tsx b/studio/frontend/src/features/browser/agent/lazy-composer-toggle.tsx
new file mode 100644
index 00000000000..f42dd16e2f4
--- /dev/null
+++ b/studio/frontend/src/features/browser/agent/lazy-composer-toggle.tsx
@@ -0,0 +1,32 @@
+// 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 { lazy, Suspense, type ComponentProps } from "react";
+import type { BrowserAgentPill as Pill } from "./composer-toggle";
+import { useBrowserAgentStore } from "./agent-store";
+
+// Off the startup bundle: the item loads with the + menu, the pill only once browser use is on.
+const MenuItem = lazy(() =>
+ import("./composer-toggle").then((module) => ({ default: module.BrowserAgentMenuItem })),
+);
+const PillComponent = lazy(() =>
+ import("./composer-toggle").then((module) => ({ default: module.BrowserAgentPill })),
+);
+
+export function BrowserAgentMenuItem() {
+ return (
+ <Suspense fallback={null}>
+ <MenuItem />
+ </Suspense>
+ );
+}
+
+export function BrowserAgentPill(props: ComponentProps<typeof Pill>) {
+ const enabled = useBrowserAgentStore((state) => state.enabled);
+ if (!enabled) return null;
+ return (
+ <Suspense fallback={null}>
+ <PillComponent {...props} />
+ </Suspense>
+ );
+}
diff --git a/studio/frontend/src/features/browser/agent/page-agent.ts b/studio/frontend/src/features/browser/agent/page-agent.ts
index 353d5f694ee..a97eaac69f6 100644
--- a/studio/frontend/src/features/browser/agent/page-agent.ts
+++ b/studio/frontend/src/features/browser/agent/page-agent.ts
@@ -29,6 +29,8 @@ export type ElementInfo = {
formHasPassword: boolean;
/** For a dropdown described with a value: the label of the option that value selects. */
option?: string;
+ /** For Enter in a field: the label of the button that will submit its form. */
+ submitter?: string;
submits: boolean;
};
@@ -77,7 +79,14 @@ export function installPageAgent(): PageAgent {
// Mirrors gate.ts, which can't be imported here (this function ships as source).
const SECRET = /\b(current-password|new-password|one-time-code|cc-[a-z-]+)\b/i;
const SECRET_NAME = /\b(password|passcode|card ?number|cvc|cvv|security code|ssn|social security)\b/i;
- const TEXT_INPUTS = new Set(["text", "search", "email", "url", "tel", "number", "password", ""]);
+ // Date and time fields are textboxes to the model too; they take their ISO-like value as typed.
+ const TEXT_INPUTS = new Set([
+ "text", "search", "email", "url", "tel", "number", "password", "",
+ "date", "time", "datetime-local", "month", "week",
+ ]);
+ const DATE_FORMATS: Record<string, string> = {
+ date: "2026-03-14", time: "09:30", "datetime-local": "2026-03-14T09:30", month: "2026-03", week: "2026-W11",
+ };
const BUTTON_INPUTS = new Set(["button", "submit", "reset", "image"]);
const NOT_TEXT = new Set([...BUTTON_INPUTS, "checkbox", "radio", "range", "file", "color", "hidden"]);
const EDITABLE_TAGS = new Set(["input", "textarea"]);
@@ -198,6 +207,7 @@ export function installPageAgent(): PageAgent {
}
const tag = el.tagName.toLowerCase();
if (tag === "input" && ["button", "submit", "reset"].includes(field.type) && field.value) return clean(field.value);
+ if (tag === "input" && field.type === "image" && el.getAttribute("alt")) return clean(el.getAttribute("alt"));
if (tag === "input" || tag === "textarea") {
const hint = el.getAttribute("placeholder") || el.getAttribute("title") || el.getAttribute("name");
return clean(hint);
@@ -480,9 +490,14 @@ export function installPageAgent(): PageAgent {
node instanceof HTMLButtonElement
? node.type === "submit"
: node instanceof HTMLInputElement && (node.type === "submit" || node.type === "image");
- /** The button Enter in a field submits with, as a browser picks it: the form's first submit button. */
+ /** The button Enter in a field submits with, as a browser picks it: the form's first submit button
+ * in tree order (form.elements leaves out <input type=image>). */
const defaultButton = (form: HTMLFormElement | null) =>
- Array.from(form?.elements ?? []).find(isSubmitter) as HTMLButtonElement | HTMLInputElement | undefined;
+ form
+ ? (Array.from(document.querySelectorAll("button, input")).find(
+ (node) => (node as HTMLInputElement).form === form && isSubmitter(node),
+ ) as HTMLButtonElement | HTMLInputElement | undefined)
+ : undefined;
/** No ref: the focused element, which a key press would act on. */
const describe = (ref: string, value?: unknown): Record<string, unknown> => {
@@ -520,6 +535,7 @@ export function installPageAgent(): PageAgent {
...(el instanceof HTMLSelectElement && typeof value === "string"
? { option: clean(findOption(el, value)?.text ?? "", 200) }
: {}),
+ ...(!submits && submitter ? { submitter: clean(nameOf(submitter), 200) } : {}),
};
return { ok: true, info };
};
@@ -712,10 +728,19 @@ export function installPageAgent(): PageAgent {
(el as HTMLElement).focus?.({ preventScroll: true });
const tag = el.tagName.toLowerCase();
const field = el as HTMLInputElement;
- if ((tag === "textarea" || tag === "input") && (field.disabled || field.readOnly)) {
+ if ((tag === "textarea" || tag === "input") && (field.matches(":disabled") || field.readOnly)) {
return { ok: false, error: `${ref} is disabled or read-only.` };
}
if (tag === "textarea" || (tag === "input" && TEXT_INPUTS.has(field.type.toLowerCase()))) {
+ // A date or time field drops a value it can't parse: tried on a detached field of the same
+ // type first, so a bad value never blanks the page's field or fires its change handlers.
+ const format = DATE_FORMATS[field.type.toLowerCase()];
+ if (format && text) {
+ const probe = document.createElement("input");
+ probe.type = field.type;
+ probe.value = text;
+ if (!probe.value) return { ok: false, error: `${ref} takes a value like ${format}.` };
+ }
setValue(field, text);
} else if ((el as HTMLElement).isContentEditable) {
const selection = window.getSelection();
@@ -743,6 +768,8 @@ export function installPageAgent(): PageAgent {
const choose = (ref: string, value: string): Record<string, unknown> => {
const el = lookup(ref);
if (el instanceof HTMLSelectElement) {
+ // :disabled, not .disabled: a disabled fieldset disables what is inside it.
+ if (el.matches(":disabled")) return { ok: false, error: `${ref} is disabled or read-only.` };
const option = findOption(el, value);
if (!option) return { ok: false, error: `${ref} has no such option; snapshot it to see its options.` };
el.value = option.value;
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 6739f4746d3..da5eb3f9f2e 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -29,7 +29,7 @@ import { BulbIcon } from "@/lib/bulb-icon";
import { InternetGlyph } from "@/lib/internet-icon";
import { MicIcon } from "@/lib/mic-icon";
import { MenuTickIcon, Tick02Icon } from "@/lib/tick-icon";
-import { BrowserAgentMenuItem, BrowserAgentPill } from "@/features/browser/agent/composer-toggle";
+import { BrowserAgentMenuItem, BrowserAgentPill } from "@/features/browser/agent/lazy-composer-toggle";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
diff --git a/studio/frontend/tests/browser-agent-gate.test.ts b/studio/frontend/tests/browser-agent-gate.test.ts
index 25cc45bcb8f..7837ee82006 100644
--- a/studio/frontend/tests/browser-agent-gate.test.ts
+++ b/studio/frontend/tests/browser-agent-gate.test.ts
@@ -135,6 +135,12 @@ test("buying, posting, signing in and POST forms ask; ordinary clicks and search
assert.equal(gateElement("select", element({ role: "checkbox", tag: "input", type: "checkbox", name: "Subscribe" }), page, open, NONE).kind, "ask");
assert.equal(gateElement("select", element({ role: "combobox", tag: "select", name: "Large" }), page, open, NONE).kind, "allow");
assert.equal(gateElement("select", element({ role: "combobox", tag: "select", name: "Delete my account" }), page, open, NONE).kind, "ask");
+ // Enter in a field presses the form's default button, so that button's words decide.
+ const quantity = element({ role: "textbox", tag: "input", type: "number", name: "Quantity", formAction: "https://shop.example/c" });
+ assert.equal(gateElement("submit", { ...quantity, submitter: "Buy now" }, page, open, NONE).kind, "ask");
+ assert.equal(gateElement("submit", { ...search, submitter: "Search" }, page, open, NONE).kind, "allow");
+ const expiry = element({ role: "combobox", tag: "select", name: "Month", autocomplete: "cc-exp-month" });
+ assert.equal(gateElement("type", expiry, page, open, NONE).kind, "block");
// The executor's name for Delete pressed outside a text field.
assert.equal(gateElement("click", element({ role: "row", name: "delete key on Invoice 42" }), page, open, NONE).kind, "ask");
});
diff --git a/tests/studio/test_token_count_prompt_parity.py b/tests/studio/test_token_count_prompt_parity.py
index a3d2eb453c5..e380aa38448 100644
--- a/tests/studio/test_token_count_prompt_parity.py
+++ b/tests/studio/test_token_count_prompt_parity.py
@@ -124,6 +124,11 @@ const state: any = {
const useChatRuntimeStore: any = { getState: () => state };
const useBrowserAgentStore: any = { getState: () => state.browserAgent };
+// Browser use off: the count must match a turn that offers no browser tools.
+function browserAgentToolsForTurn(): string[] {
+ return [];
+}
+
export function seed(patch: any): void {
Object.assign(state, patch);
}