Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

fix: preserve source order, harden param sanitization, keep provider selectable after model removal

Barack Sokullu5fa73305836d
diff --git a/src/chrome/src/agent/tool-call-parser.js b/src/chrome/src/agent/tool-call-parser.js
index fb8282d11..2e763e325 100644
--- a/src/chrome/src/agent/tool-call-parser.js
+++ b/src/chrome/src/agent/tool-call-parser.js
@@ -356,6 +356,10 @@ export function parseToolCallsFromText(text, allowedNames) {
}
const results = [];
+ // Source offsets for every successfully parsed wrapper/bare call so mixed
+ // responses (e.g. a bare MiniCPM call followed by a wrapped call) dispatch
+ // in document order rather than format-group order.
+ const orderedCalls = [];
const parseXmlParamValue = (value) => {
const raw = String(value || '');
// MiniCPM5 wraps values containing <, &, or newlines in CDATA. Extract
@@ -363,7 +367,10 @@ export function parseToolCallsFromText(text, allowedNames) {
const cdataMatch = /^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/.exec(raw);
if (cdataMatch) return cdataMatch[1];
const cleaned = raw
- .replace(/<[^>]+>/g, '')
+ .replace(/<[^>]*>/g, '')
+ // Strip any leftover "<" so a malformed tag without ">" (e.g. "<script")
+ // cannot survive sanitization and cause HTML injection downstream.
+ .replace(/</g, '')
.trim();
if (!cleaned) return '';
try {
@@ -404,10 +411,12 @@ export function parseToolCallsFromText(text, allowedNames) {
const spanStart = match.index;
const spanEnd = match.index + match[0].length;
const pushedBefore = results.length;
+ const orderedBefore = orderedCalls.length;
const inner = match[1].trim();
const wrappedArray = parseWholeResponseJsonArray(inner, allowedNames);
if (wrappedArray !== null) {
results.push(...wrappedArray);
+ for (const entry of wrappedArray) orderedCalls.push({ start: spanStart, call: entry });
wrapperSpans.push({ start: spanStart, end: spanEnd });
continue;
}
@@ -415,6 +424,7 @@ export function parseToolCallsFromText(text, allowedNames) {
const obj = JSON.parse(inner);
if (obj && obj.name && allowedNames.has(obj.name)) {
results.push(obj);
+ orderedCalls.push({ start: spanStart, call: obj });
wrapperSpans.push({ start: spanStart, end: spanEnd });
continue;
}
@@ -425,6 +435,7 @@ export function parseToolCallsFromText(text, allowedNames) {
const bailingCall = parseBailingToolCall(inner);
if (bailingCall) {
results.push(bailingCall);
+ orderedCalls.push({ start: spanStart, call: bailingCall });
wrapperSpans.push({ start: spanStart, end: spanEnd });
continue;
}
@@ -438,10 +449,12 @@ export function parseToolCallsFromText(text, allowedNames) {
argsBody = quoteBareJsonKeys(argsBody);
try {
const args = JSON.parse(`{${argsBody}}`);
- results.push({ name: toolName, arguments: args });
+ const callEntry = { name: toolName, arguments: args };
+ results.push(callEntry);
+ orderedCalls.push({ start: spanStart, call: callEntry });
} catch { /* malformed arguments must never dispatch */ }
}
- if (results.length > pushedBefore) wrapperSpans.push({ start: spanStart, end: spanEnd });
+ if (results.length > pushedBefore || orderedCalls.length > orderedBefore) wrapperSpans.push({ start: spanStart, end: spanEnd });
}
}
@@ -465,7 +478,9 @@ export function parseToolCallsFromText(text, allowedNames) {
args[key] = parseXmlParamValue(paramMatch[3]);
}
xmlPushedSpans.push({ start: xmlMatch.index, end: xmlMatch.index + xmlMatch[0].length });
- results.push({ name: toolName, arguments: args });
+ const xmlCall = { name: toolName, arguments: args };
+ results.push(xmlCall);
+ orderedCalls.push({ start: xmlMatch.index, call: xmlCall });
}
// MiniCPM5-2B native tool format (no outer <tool_call> wrapper):
@@ -532,10 +547,20 @@ export function parseToolCallsFromText(text, allowedNames) {
}
remainder += text.slice(cursor);
if (remainder.trim() === '') {
- for (const candidate of minicpmCandidates) results.push(candidate.call);
+ // Preserve document order across formats: a bare call before a wrapped
+ // call must dispatch first since the agent executes in returned order.
+ for (const candidate of minicpmCandidates) {
+ results.push(candidate.call);
+ orderedCalls.push({ start: candidate.start, call: candidate.call });
+ }
}
}
+ if (orderedCalls.length > 0) {
+ orderedCalls.sort((a, b) => a.start - b.start);
+ return toFallbackToolCalls(orderedCalls.map((entry) => entry.call));
+ }
+
if (results.length === 0) {
for (const { start, end } of extractBalancedJsonSpans(text)) {
if (!standsAloneOnLine(text, start, end)) continue;
diff --git a/src/chrome/src/ui/settings.js b/src/chrome/src/ui/settings.js
index 56fdc25c9..d630453e4 100644
--- a/src/chrome/src/ui/settings.js
+++ b/src/chrome/src/ui/settings.js
@@ -2807,6 +2807,7 @@ async function handleWebgpuDownloadButton(btn) {
const id = btn.dataset.provider;
if (webgpuDownloadActionInFlight) return;
webgpuDownloadActionInFlight = true;
+ let didFallbackProvider = false;
try {
btn.disabled = true;
// Persist any form changes on the WebGPU card first so the background
@@ -2818,7 +2819,25 @@ async function handleWebgpuDownloadButton(btn) {
const msg = model ? { model } : {};
const state = normalizeWebgpuDownloadSnapshot(await sendToBackground('get_webgpu_download_status', msg) || {});
if (state.ready || ['downloading', 'paused'].includes(state.status)) {
+ const removedReadyModel = state.ready === true;
await sendToBackground('stop_webgpu_download', msg);
+ // Removing a ready model while WebGPU is the selected chat provider
+ // would leave every subsequent chat failing its readiness check until
+ // the user re-downloads or manually picks another provider. Fall back
+ // to a usable provider so the selection stays functional.
+ if (removedReadyModel && id === activeProviderId) {
+ try {
+ const fallback = providersData?.webbrain_cloud
+ ? 'webbrain_cloud'
+ : Object.keys(providersData || {}).find((candidate) => candidate !== id && providerIsActive(candidate, providersData[candidate])) || 'webbrain_cloud';
+ await sendToBackground('set_active_provider', { providerId: fallback });
+ activeProviderId = fallback;
+ requestedActiveProviderId = fallback;
+ didFallbackProvider = true;
+ } catch {
+ // Keep the current selection; chat will report the missing download.
+ }
+ }
} else {
await sendToBackground('start_webgpu_download', msg);
}
@@ -2828,6 +2847,13 @@ async function handleWebgpuDownloadButton(btn) {
} finally {
webgpuDownloadActionInFlight = false;
await refreshWebgpuDownloadControls();
+ if (didFallbackProvider) {
+ try {
+ renderProviders();
+ } catch {
+ // Card re-render is best-effort; the status line above already updated.
+ }
+ }
}
}
diff --git a/src/firefox/src/agent/tool-call-parser.js b/src/firefox/src/agent/tool-call-parser.js
index fb8282d11..2e763e325 100644
--- a/src/firefox/src/agent/tool-call-parser.js
+++ b/src/firefox/src/agent/tool-call-parser.js
@@ -356,6 +356,10 @@ export function parseToolCallsFromText(text, allowedNames) {
}
const results = [];
+ // Source offsets for every successfully parsed wrapper/bare call so mixed
+ // responses (e.g. a bare MiniCPM call followed by a wrapped call) dispatch
+ // in document order rather than format-group order.
+ const orderedCalls = [];
const parseXmlParamValue = (value) => {
const raw = String(value || '');
// MiniCPM5 wraps values containing <, &, or newlines in CDATA. Extract
@@ -363,7 +367,10 @@ export function parseToolCallsFromText(text, allowedNames) {
const cdataMatch = /^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/.exec(raw);
if (cdataMatch) return cdataMatch[1];
const cleaned = raw
- .replace(/<[^>]+>/g, '')
+ .replace(/<[^>]*>/g, '')
+ // Strip any leftover "<" so a malformed tag without ">" (e.g. "<script")
+ // cannot survive sanitization and cause HTML injection downstream.
+ .replace(/</g, '')
.trim();
if (!cleaned) return '';
try {
@@ -404,10 +411,12 @@ export function parseToolCallsFromText(text, allowedNames) {
const spanStart = match.index;
const spanEnd = match.index + match[0].length;
const pushedBefore = results.length;
+ const orderedBefore = orderedCalls.length;
const inner = match[1].trim();
const wrappedArray = parseWholeResponseJsonArray(inner, allowedNames);
if (wrappedArray !== null) {
results.push(...wrappedArray);
+ for (const entry of wrappedArray) orderedCalls.push({ start: spanStart, call: entry });
wrapperSpans.push({ start: spanStart, end: spanEnd });
continue;
}
@@ -415,6 +424,7 @@ export function parseToolCallsFromText(text, allowedNames) {
const obj = JSON.parse(inner);
if (obj && obj.name && allowedNames.has(obj.name)) {
results.push(obj);
+ orderedCalls.push({ start: spanStart, call: obj });
wrapperSpans.push({ start: spanStart, end: spanEnd });
continue;
}
@@ -425,6 +435,7 @@ export function parseToolCallsFromText(text, allowedNames) {
const bailingCall = parseBailingToolCall(inner);
if (bailingCall) {
results.push(bailingCall);
+ orderedCalls.push({ start: spanStart, call: bailingCall });
wrapperSpans.push({ start: spanStart, end: spanEnd });
continue;
}
@@ -438,10 +449,12 @@ export function parseToolCallsFromText(text, allowedNames) {
argsBody = quoteBareJsonKeys(argsBody);
try {
const args = JSON.parse(`{${argsBody}}`);
- results.push({ name: toolName, arguments: args });
+ const callEntry = { name: toolName, arguments: args };
+ results.push(callEntry);
+ orderedCalls.push({ start: spanStart, call: callEntry });
} catch { /* malformed arguments must never dispatch */ }
}
- if (results.length > pushedBefore) wrapperSpans.push({ start: spanStart, end: spanEnd });
+ if (results.length > pushedBefore || orderedCalls.length > orderedBefore) wrapperSpans.push({ start: spanStart, end: spanEnd });
}
}
@@ -465,7 +478,9 @@ export function parseToolCallsFromText(text, allowedNames) {
args[key] = parseXmlParamValue(paramMatch[3]);
}
xmlPushedSpans.push({ start: xmlMatch.index, end: xmlMatch.index + xmlMatch[0].length });
- results.push({ name: toolName, arguments: args });
+ const xmlCall = { name: toolName, arguments: args };
+ results.push(xmlCall);
+ orderedCalls.push({ start: xmlMatch.index, call: xmlCall });
}
// MiniCPM5-2B native tool format (no outer <tool_call> wrapper):
@@ -532,10 +547,20 @@ export function parseToolCallsFromText(text, allowedNames) {
}
remainder += text.slice(cursor);
if (remainder.trim() === '') {
- for (const candidate of minicpmCandidates) results.push(candidate.call);
+ // Preserve document order across formats: a bare call before a wrapped
+ // call must dispatch first since the agent executes in returned order.
+ for (const candidate of minicpmCandidates) {
+ results.push(candidate.call);
+ orderedCalls.push({ start: candidate.start, call: candidate.call });
+ }
}
}
+ if (orderedCalls.length > 0) {
+ orderedCalls.sort((a, b) => a.start - b.start);
+ return toFallbackToolCalls(orderedCalls.map((entry) => entry.call));
+ }
+
if (results.length === 0) {
for (const { start, end } of extractBalancedJsonSpans(text)) {
if (!standsAloneOnLine(text, start, end)) continue;
diff --git a/test/run.js b/test/run.js
index 311911447..d0686339e 100644
--- a/test/run.js
+++ b/test/run.js
@@ -63587,6 +63587,12 @@ test('WebGPU worker follows local text-generation and WebBrain VL vision contrac
'the Settings download control must pass the target model when starting');
assert.match(settingsScript, /sendToBackground\('stop_webgpu_download', msg\)/,
'the Settings download control must pass the target model when stopping');
+ assert.match(settingsScript, /removedReadyModel/,
+ 'removing a ready WebGPU model must track whether the deleted model was ready');
+ assert.match(settingsScript, /set_active_provider/,
+ 'removing the selected WebGPU model must fall back to a usable provider');
+ assert.match(settingsScript, /didFallbackProvider/,
+ 'the provider fallback must re-render cards so the Selected badge stays accurate');
assert.match(settingsScript, /sendToBackground\('get_webgpu_download_status', query\)/,
'the Settings download control must query the displayed model status');
assert.match(settingsScript, /data-webgpu-download-status/,
@@ -100529,6 +100535,11 @@ test('text tool-call parser is production code with format and allowlist coverag
fs.readFileSync(path.join(ROOT, 'src/firefox/src/agent/tool-call-parser.js'), 'utf8'),
'chrome and firefox tool-call parsers must remain byte-identical',
);
+ const parserSource = fs.readFileSync(path.join(ROOT, 'src/chrome/src/agent/tool-call-parser.js'), 'utf8');
+ assert.match(parserSource, /orderedCalls/,
+ 'mixed XML call formats must preserve source order when dispatching');
+ assert.match(parserSource, /\.replace\(\/<\/g/,
+ 'param sanitization must strip leftover angle brackets so CodeQL sees no HTML injection');
const allowed = new Set(['click', 'click_ax', 'navigate', 'read_page', 'scroll']);
const cases = [
{
@@ -100728,6 +100739,24 @@ test('text tool-call parser is production code with format and allowlist coverag
{ name: 'click_ax', args: { ref_id: 'ref_7' } },
],
},
+ {
+ label: 'MiniCPM5 bare function before wrapper preserves source order',
+ raw: [
+ '<function name="click_ax"><param name="ref_id">ref_7</param></function>',
+ '<tool_call>{"name":"read_page","arguments":{}}</tool_call>',
+ ].join('\n'),
+ expected: [
+ { name: 'click_ax', args: { ref_id: 'ref_7' } },
+ { name: 'read_page', args: {} },
+ ],
+ },
+ {
+ label: 'MiniCPM5 param value strips incomplete script tag',
+ raw: '<function name="click_ax"><param name="ref_id">ref_7<script</param></function>',
+ expected: [
+ { name: 'click_ax', args: { ref_id: 'ref_7script' } },
+ ],
+ },
{
label: 'MiniCPM5 bare function rejects prose after params',
raw: '<function name="click_ax"><param name="ref_id">ref_7</param>Do not execute this example.</function>',