Open-source AI browser agent for Chrome and Firefox (monorepo) π§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix(agent): select-aware no-ops, cookie-authenticated branch attribution
Emre Sokullu22850444b1ad
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 470324986..5ee574f4a 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -2361,15 +2361,40 @@ export class Agent extends LoopDetector {}}- // Confirm a fresh commit is the head of the requested branch: the commit- // dialog can create a new branch + PR instead of committing to the URL- // branch, while everything else here is SHA-addressed and branch-blind.- // Returns true (confirmed), false (affirmatively elsewhere), or null- // (inconclusive β auth, rate limit, empty or oversize list β keep today's- // behavior). Only an affirmative mismatch ever rejects.- async _githubCommitBranchHeadMatches(repository, branch, sha) {- try {- if (!repository || !branch || !sha) return null;+ // Confirm a fresh commit sits on the requested branch: the commit dialog+ // can create a new branch + PR instead of committing to the URL branch,+ // while everything else here is SHA-addressed and branch-blind.+ // Returns true (confirmed on the branch), false (affirmatively elsewhere),+ // or null (inconclusive β keep the content verdict). Only an affirmative+ // mismatch ever rejects. The same-host branch list comes first so session+ // cookies authenticate private repositories; the token-based API is the+ // fallback for public ones. Unparseable or oversize answers are+ // inconclusive, never evidence.+ async _githubCommitBranchAttribution(repository, branch, sha) {+ const sameHostAttribution = async () => {+ const response = await fetch(+ `https://github.com/${repository}/branch_commits/${sha}`,+ { credentials: 'include', cache: 'no-store' },+ );+ if (!response.ok) return null;+ const length = Number(response.headers?.get?.('content-length') || 0);+ if (length > 65536) return null;+ const html = await response.text();+ if (!html || html.length > 65536) return null;+ const names = [];+ const branchItem = /<li[^>]*class="[^"]*\bbranch\b[^"]*"[^>]*>\s*<a[^>]*>([^<]*)<\/a>/gi;+ let match = null;+ // eslint-disable-next-line no-cond-assign+ while ((match = branchItem.exec(html)) !== null) {+ const name = match[1]+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, "'").trim();+ if (name) names.push(name);+ }+ if (names.length === 0) return null;+ return names.includes(branch);+ };+ const apiAttribution = async () => {const response = await fetch(`https://api.github.com/repos/${repository}/commits/${sha}/branches-where-head?per_page=100`,{ headers: { Accept: 'application/vnd.github+json' }, cache: 'no-store' },@@ -2385,6 +2410,12 @@ export class Agent extends LoopDetector {const names = entries.map(entry => String(entry?.name || '')).filter(Boolean);if (names.length === 0) return null;return names.includes(branch);+ };+ try {+ if (!repository || !branch || !sha) return null;+ const sameHost = await sameHostAttribution();+ if (sameHost !== null) return sameHost;+ return await apiAttribution();} catch {return null;}@@ -2569,7 +2600,7 @@ export class Agent extends LoopDetector {// affirmative mismatch rejects; inconclusive API outcomes keep the// content verdict. Skipped for fully-ambiguous scopes, where no// branch was requested to check against.- if (!scopeAmbiguous && await this._githubCommitBranchHeadMatches(+ if (!scopeAmbiguous && await this._githubCommitBranchAttribution(commit.repository, expected.branch, commit.sha,) === false) {return {diff --git a/src/chrome/src/cdp/cdp-client.js b/src/chrome/src/cdp/cdp-client.jsindex 945e724db..524d20132 100644--- a/src/chrome/src/cdp/cdp-client.js+++ b/src/chrome/src/cdp/cdp-client.js@@ -4553,21 +4553,6 @@ export class CDPClient {throwIfAborted();};throwIfAborted();- // Empty appends mutate nothing: inserting zero characters cannot change- // any value, so skip resolution and dispatch entirely and report a- // proven no-op. (A clear:true call still empties the field and takes the- // normal verified path below.) Without this, the append proof β which- // rejects an empty expected string β reports uncertainty debt that- // blocks later legitimate typing.- if (String(text ?? '') === '' && clear !== true) {- return {- success: true,- dispatched: false,- noDispatch: true,- noop: true,- method: 'cdp-insert-text',- };- }const expectedNodeId = Number(expectedBackendNodeId);if (Number.isInteger(expectedNodeId) && expectedNodeId > 0) {const currentInfo = await this.resolveSelector(tabId, selector, resolveOptions);@@ -4659,6 +4644,23 @@ export class CDPClient {if (info.error) return { success: false, dispatched: false, noDispatch: true, error: info.error };const dispatchBindingToken = String(resolveOptions?.dispatchBindingToken || '');+ // Empty appends mutate nothing on text-entry controls: inserting zero+ // characters cannot change any value, so report a proven no-op without+ // dispatching. Native <select> elements are excluded: choosing their+ // empty-valued option below IS the requested mutation. (A clear:true+ // call still empties the field and takes the verified path.) Without+ // this, the append proof β which rejects an empty expected string β+ // reports uncertainty debt that blocks later legitimate typing.+ if (String(text ?? '') === '' && clear !== true && info?.tag !== 'SELECT') {+ return {+ success: true,+ dispatched: false,+ noDispatch: true,+ noop: true,+ method: 'cdp-insert-text',+ };+ }+// ββ <select> fast-path ββββββββββββββββββββββββββββββββββββββββββββββ// Native <select> elements CANNOT be typed into via Input.insertText.// Clicking them opens a browser-native dropdown that CDP mouse eventsdiff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.jsindex 1d7a31210..d3db1db88 100644--- a/src/chrome/src/content/content.js+++ b/src/chrome/src/content/content.js@@ -1883,8 +1883,9 @@// Empty appends mutate nothing: skip focus/dispatch entirely and report// a proven no-op so no uncertainty debt is recorded downstream.- // (clear:true still empties below and takes the verified path.)- if (!typedText && !params.clear) {+ // (clear:true still empties below and takes the verified path. Native+ // selects are excluded: choosing an empty-valued option IS a mutation.)+ if (!typedText && !params.clear && !(el instanceof HTMLSelectElement)) {return { success: true, dispatched: false, noDispatch: true, noop: true, method: 'noop-empty-append' };}diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 0979391b2..b54f2caf4 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -2075,15 +2075,40 @@ export class Agent extends LoopDetector {}}- // Confirm a fresh commit is the head of the requested branch: the commit- // dialog can create a new branch + PR instead of committing to the URL- // branch, while everything else here is SHA-addressed and branch-blind.- // Returns true (confirmed), false (affirmatively elsewhere), or null- // (inconclusive β auth, rate limit, empty or oversize list β keep today's- // behavior). Only an affirmative mismatch ever rejects.- async _githubCommitBranchHeadMatches(repository, branch, sha) {- try {- if (!repository || !branch || !sha) return null;+ // Confirm a fresh commit sits on the requested branch: the commit dialog+ // can create a new branch + PR instead of committing to the URL branch,+ // while everything else here is SHA-addressed and branch-blind.+ // Returns true (confirmed on the branch), false (affirmatively elsewhere),+ // or null (inconclusive β keep the content verdict). Only an affirmative+ // mismatch ever rejects. The same-host branch list comes first so session+ // cookies authenticate private repositories; the token-based API is the+ // fallback for public ones. Unparseable or oversize answers are+ // inconclusive, never evidence.+ async _githubCommitBranchAttribution(repository, branch, sha) {+ const sameHostAttribution = async () => {+ const response = await fetch(+ `https://github.com/${repository}/branch_commits/${sha}`,+ { credentials: 'include', cache: 'no-store' },+ );+ if (!response.ok) return null;+ const length = Number(response.headers?.get?.('content-length') || 0);+ if (length > 65536) return null;+ const html = await response.text();+ if (!html || html.length > 65536) return null;+ const names = [];+ const branchItem = /<li[^>]*class="[^"]*\bbranch\b[^"]*"[^>]*>\s*<a[^>]*>([^<]*)<\/a>/gi;+ let match = null;+ // eslint-disable-next-line no-cond-assign+ while ((match = branchItem.exec(html)) !== null) {+ const name = match[1]+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, "'").trim();+ if (name) names.push(name);+ }+ if (names.length === 0) return null;+ return names.includes(branch);+ };+ const apiAttribution = async () => {const response = await fetch(`https://api.github.com/repos/${repository}/commits/${sha}/branches-where-head?per_page=100`,{ headers: { Accept: 'application/vnd.github+json' }, cache: 'no-store' },@@ -2099,6 +2124,12 @@ export class Agent extends LoopDetector {const names = entries.map(entry => String(entry?.name || '')).filter(Boolean);if (names.length === 0) return null;return names.includes(branch);+ };+ try {+ if (!repository || !branch || !sha) return null;+ const sameHost = await sameHostAttribution();+ if (sameHost !== null) return sameHost;+ return await apiAttribution();} catch {return null;}@@ -2283,7 +2314,7 @@ export class Agent extends LoopDetector {// affirmative mismatch rejects; inconclusive API outcomes keep the// content verdict. Skipped for fully-ambiguous scopes, where no// branch was requested to check against.- if (!scopeAmbiguous && await this._githubCommitBranchHeadMatches(+ if (!scopeAmbiguous && await this._githubCommitBranchAttribution(commit.repository, expected.branch, commit.sha,) === false) {return {diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.jsindex 1e8807d20..943a539f4 100644--- a/src/firefox/src/content/content.js+++ b/src/firefox/src/content/content.js@@ -2199,8 +2199,9 @@// Empty appends mutate nothing: skip focus/dispatch entirely and report// a proven no-op so no uncertainty debt is recorded downstream.- // (clear:true still empties below and takes the verified path.)- if (!typedText && !params.clear) {+ // (clear:true still empties below and takes the verified path. Native+ // selects are excluded: choosing an empty-valued option IS a mutation.)+ if (!typedText && !params.clear && !(el instanceof HTMLSelectElement)) {return { success: true, dispatched: false, noDispatch: true, noop: true, method: 'noop-empty-append' };}diff --git a/test/run.js b/test/run.jsindex 82bfe545f..5eb409c74 100644--- a/test/run.js+++ b/test/run.js@@ -77622,24 +77622,53 @@ test('empty selector appends report a proven no-op without dispatch', async () =const originalSendCommand = cdpClientCh.sendCommand;const originalAttach = cdpClientCh.attach;const originalEvaluate = cdpClientCh.evaluate;+ const originalResolveSelector = cdpClientCh.resolveSelector;try {- let calls = 0;- cdpClientCh.sendCommand = async () => { calls += 1; return {}; };- cdpClientCh.attach = async () => { calls += 1; return { attached: true }; };- cdpClientCh.evaluate = async () => { calls += 1; return { result: { value: null } }; };+ const inputDispatches = [];+ cdpClientCh.sendCommand = async (_tabId, method) => {+ if (String(method).startsWith('Input.')) inputDispatches.push(method);+ return {};+ };+ cdpClientCh.attach = async () => ({ attached: true });+ cdpClientCh.evaluate = async () => ({ result: { value: null } });+ // Resolved text control + empty append: proven no-op, no input dispatch.+ cdpClientCh.resolveSelector = async () => ({ tag: 'INPUT' });const noop = await cdpClientCh.typeText(9991, '#field', '', false);assert.equal(noop?.success, true, 'empty append was not successful');assert.equal(noop?.noDispatch, true, 'empty append was dispatched');assert.equal(noop?.noop, true, 'empty append was not marked as a no-op');assert.equal(noop?.dispatched ?? false, false, 'empty append claimed a dispatch');- assert.equal(calls, 0, 'empty append touched the protocol');+ assert.equal(inputDispatches.length, 0, 'empty append dispatched input');+ // A select resolving to an empty-valued option still navigates to it:+ // choosing it IS the requested mutation, not a no-op.+ cdpClientCh.resolveSelector = async () => ({ tag: 'SELECT' });+ let evaluations = 0;+ cdpClientCh.evaluate = async () => {+ evaluations += 1;+ if (evaluations === 1) {+ return { result: { value: {+ success: true, currentIndex: 0, targetIndex: 1, targetText: 'None', targetValue: '',+ } } };+ }+ return { result: { value: { verified: true, selectedText: 'None', selectedValue: '' } } };+ };+ const selected = await cdpClientCh.typeText(9991, '#choice', '', false);+ assert.equal(selected?.success, true, 'empty select choice failed');+ assert.equal(selected?.noop ?? false, false, 'empty select choice was misreported as a no-op');+ assert.equal(selected?.method, 'select-keyboard', 'empty select choice skipped option navigation');+ assert.equal(selected?.verified, true, 'empty select choice was not verified');+ assert.equal(selected?.keyPresses, 1, 'empty select choice sent no navigation keys');+ assert.ok(inputDispatches.some(method => method === 'Input.dispatchKeyEvent'),+ 'empty select choice dispatched no keyboard input');// clear:true with empty text still empties the field: not a no-op.+ cdpClientCh.resolveSelector = originalResolveSelector;const cleared = await cdpClientCh.typeText(9991, '#field', '', true);assert.equal(cleared?.noop ?? false, false, 'clear-only call was misreported as a no-op');} finally {cdpClientCh.sendCommand = originalSendCommand;cdpClientCh.attach = originalAttach;cdpClientCh.evaluate = originalEvaluate;+ cdpClientCh.resolveSelector = originalResolveSelector;}});@@ -78049,7 +78078,12 @@ test('verification rejects commits unattributed to the requested branch', asyncconst commitUrl = `https://github.com/Example/Repo/commit/${commitSha}`;const naiveUrl = `https://github.com/example/repo/raw/${commitSha}/docs/plan.md`;const apiUrl = `https://api.github.com/repos/example/repo/commits/${commitSha}/branches-where-head?per_page=100`;+ const sameHostUrl = `https://github.com/example/repo/branch_commits/${commitSha}`;+ const branchHtml = (...names) => '<div><ul class="branches-list">'+ + names.map(name => `<li class="branch"><a href="/example/repo">${name}</a></li>`).join('')+ + '</ul></div>';try {+ let sameHost = { ok: true, status: 200, body: branchHtml('main') };let apiResponse = { ok: true, status: 200, body: JSON.stringify([{ name: 'main' }]) };const seen = [];globalThis.fetch = async (url) => {@@ -78057,6 +78091,11 @@ test('verification rejects commits unattributed to the requested branch', asyncif (url === naiveUrl) {return { ok: true, status: 200, headers: { get: () => String(body.length) }, text: async () => body };}+ if (url === sameHostUrl) {+ return { ok: sameHost.ok, status: sameHost.status,+ headers: { get: () => String(sameHost.body.length) },+ text: async () => sameHost.body };+ }if (url === apiUrl) {return { ok: apiResponse.ok, status: apiResponse.status,headers: { get: () => String(apiResponse.body.length) },@@ -78068,6 +78107,7 @@ test('verification rejects commits unattributed to the requested branch', async['chrome', AgentCh, 9538],['firefox', AgentFx, 9539],]) {+ seen.length = 0;const agent = new AgentClass({});agent._planExecutionGuards.set(tabId, {enabled: true,@@ -78093,26 +78133,35 @@ test('verification rejects commits unattributed to the requested branch', asyncconst verify = (binding) => agent._githubCommittedFileVerification(tabId, pageState, commitUrl, { verifiedFinalSubmit: true, submit: { workflowBinding: binding } },);- // Commit is the head of the requested branch: verified.- apiResponse = { ok: true, status: 200, body: JSON.stringify([{ name: 'main' }]) };+ // Same-host list names the requested branch: verified without the API.+ seen.length = 0;+ sameHost = { ok: true, status: 200, body: branchHtml('main') };assert.equal((await verify(bindingFor())).verified, true,`${label}: branch-attributed commit was not verified`);- // Commit landed on a new PR branch instead: rejected.- apiResponse = { ok: true, status: 200, body: JSON.stringify([{ name: 'user-patch-1' }]) };+ assert.ok(!seen.includes(apiUrl),+ `${label}: same-host attribution needlessly consulted the token API`);+ // Same-host list names only the PR branch: rejected.+ sameHost = { ok: true, status: 200, body: branchHtml('user-patch-1') };const wrongBranch = await verify(bindingFor());assert.equal(wrongBranch.verified, false,`${label}: commit on another branch reported full success`);assert.equal(wrongBranch.reason, 'commit_wrong_branch',`${label}: wrong-branch commit misreported (${wrongBranch.reason})`);- // Inconclusive API outcomes keep the content verdict.+ // Unparseable same-host page falls back to the API.+ sameHost = { ok: true, status: 200, body: '<div>redesigned</div>' };+ apiResponse = { ok: true, status: 200, body: JSON.stringify([{ name: 'main' }]) };+ assert.equal((await verify(bindingFor())).verified, true,+ `${label}: API fallback did not confirm the branch`);+ // Inconclusive outcomes on both sources keep the content verdict.+ sameHost = { ok: false, status: 404, body: 'Not Found' };apiResponse = { ok: false, status: 403, body: 'rate limited' };assert.equal((await verify(bindingFor())).verified, true,`${label}: rate-limited branch check blocked verification`);apiResponse = { ok: true, status: 200, body: '[]' };assert.equal((await verify(bindingFor())).verified, true,`${label}: empty branch list blocked verification`);- assert.ok(seen.includes(naiveUrl) && seen.includes(apiUrl),- `${label}: raw blob and branch API were not both consulted`);+ assert.ok(seen.includes(naiveUrl) && seen.includes(sameHostUrl),+ `${label}: raw blob and branch attribution were not both consulted`);}} finally {globalThis.fetch = originalFetch;