Skip to content

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

Fix reviewed quota recovery and browser test failures

Barack Sokullu19aa4c9221b0
diff --git a/docs/compass-quota-validation.md b/docs/compass-quota-validation.md
index 29da3a242..81c35f731 100644
--- a/docs/compass-quota-validation.md
+++ b/docs/compass-quota-validation.md
@@ -10,8 +10,8 @@ Both repositories were clean before implementation. No applicable `AGENTS.md` wa
| Cloud weekly usage | Passed, including `$0.375` and legacy usage aliases |
| Cloud Plus, portal subscription recovery, renewal notices | Passed |
| Cloud PHP syntax | Passed for service, promotion trait, routes, and both new CLI scripts |
-| Extension `npm run test:compass-quota` | 15 tests passed across Chrome and Firefox |
-| Extension `npm run test:compass-quota:ui` | 392 assertions passed in Chromium and Firefox, all 23 supported locales |
+| Extension `npm run test:compass-quota` | 19 tests passed across Chrome and Firefox |
+| Extension `npm run test:compass-quota:ui` | 400 assertions passed in Chromium and Firefox, all 23 supported locales |
| Extension billing/payment notice | Passed in both builds |
| Extension runtime lifecycle suite | 218 tests and 14 UI/content lifecycle checks passed |
| Extension provider limits | Passed |
@@ -37,6 +37,10 @@ After these fixes, the promotion suites, PHP syntax, weekly usage, Plus, portal
## Existing failures
+The first GitHub review findings were addressed in both PRs. Ordinary quota reads now use a shared read lock without creating lifetime claims or rewriting the store; metering and expiring client telemetry also avoid allocating claims. Sharing explicitly creates the opaque identifier. Regressions rotate device headers across 50 direct usage reads and 20 real HTTP usage/malformed-chat requests, check unchanged store bytes, and retain conversion counting without a claim. Both browsers now emit one recovery signal on response-only quota failure, and provider switching checks connection results, exceptions, and stale tests before reporting readiness. The rendered test server selects locale identifiers from a fixed allowlist. The PDF browser test captures its Chrome tab ID at creation instead of rediscovering it by URL.
+
+After these changes, the cloud promotion suite, syntax, weekly usage, Plus, payment recovery, renewal notices, 19 quota tests, 400 browser assertions, payment notice checks, both builds, and real Chrome PDF/WebMCP tests passed. Screenshots were regenerated at 280 and 420 px. GitHub checks and fresh Codex reviews are tracked on the PRs.
+
- **Extension `npm test`:** the final run reached the legacy `test/run.js` suite: **2,425 passed, 1 failed** out of 2,426. The failing test is `extended provider catalog is complete, mirrored, safe, and excluded-provider clean`; its expected catalog omits existing `freebuff2api`. The unchanged HEAD test reproduces that failure. Earlier chained suites passed; checks chained after this failing legacy suite were not executed by `npm test`. Two source-extraction assertions affected by the expanded quota renderer were updated and now pass.
- **Cloud `composer check`:** the native Windows checkout gives `tests/apache-health-guard.sh` CRLF line endings, and Bash rejects its `set -u` / function syntax. The aggregate check stops there with exit 2. This shell script was not changed.
- **Cloud PHP checks run separately:** `tool-request-shape.php` fails its default-upstream-model assertion because the existing local `.env` sets `UPSTREAM_MODEL_ID=stepfun/step-3.7-flash`, while the test expects the constructor's GPT-5.6 Luna Pro default. The unchanged HEAD service/test reproduces this failure.
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 002709d48..39c7ab213 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -22466,13 +22466,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
onUpdate('thinking', { step: 1, note: 'Preparing response…' });
let finalResponse = '';
let status = 'done';
+ let quotaFailure = false;
try {
finalResponse = await this._generateContextOnlyResponse(
tabId, messages, provider, costState, runId,
{ phase: 'response_only', step: 1, runOptions, currentUserMessage, priorMessageSet, shareCapture },
);
} catch (error) {
- if (error.quota) onUpdate('quota', { quota: error.quota });
+ if (error.quota) {
+ quotaFailure = true;
+ onUpdate('quota', { quota: error.quota });
+ }
status = this._isCostAllowanceError(error) ? 'cost_limit' : 'error';
finalResponse = this._isCostAllowanceError(error)
? error.message
@@ -22486,7 +22490,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('text', { content: finalResponse, replace: true });
- if (status !== 'done') onUpdate('error', { message: finalResponse });
+ if (status !== 'done' && !quotaFailure) onUpdate('error', { message: finalResponse });
this._persist(tabId);
return { content: finalResponse, status };
}
diff --git a/src/chrome/src/ui/compass-quota.js b/src/chrome/src/ui/compass-quota.js
index 5deb3072b..f00df6c12 100644
--- a/src/chrome/src/ui/compass-quota.js
+++ b/src/chrome/src/ui/compass-quota.js
@@ -41,7 +41,15 @@ export function createQuotaController({ t, locale, request, openUrl, providers,
const providerArea = el('div', '', 'quota-providers');
const status = el('div', '', 'quota-status');
status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
- const share = button(t('quota.get'), () => { host.dataset.claimOpen = 'true'; showClaim(); }, 'quota-share');
+ const share = button(t('quota.get'), async () => {
+ host.dataset.claimOpen = 'true';
+ operations.version++;
+ try {
+ if (!social?.share_url) social = await request('/promotions/social');
+ if (cards.get(host)?.refresh !== refresh) return;
+ renderState(); showClaim();
+ } catch (error) { status.textContent = error.message; }
+ }, 'quota-share');
const subscribe = button(t('quota.subscribe'), () => { event('checkout_open'); openUrl(quota.subscribe_url); }, 'subscribe-btn');
const other = button(t('quota.other'), async () => {
providerArea.replaceChildren();
@@ -88,7 +96,7 @@ export function createQuotaController({ t, locale, request, openUrl, providers,
}
function showClaim(focus = true) {
- if (!social) { void refresh().then(() => { if (social) showClaim(); }); return; }
+ if (!social?.share_url) { return; }
if (!social.eligible || social.status === 'pending') { claimArea.replaceChildren(); return; }
// A balance/status refresh must not replace the user's focused editor or draft.
const existingForm = claimArea.querySelector('form');
@@ -150,9 +158,9 @@ export function createQuotaController({ t, locale, request, openUrl, providers,
const version = operations.version;
inflight = (async () => {
try {
- const [nextSocial, nextUsage] = await Promise.all([request('/promotions/social'), request('/usage')]);
+ const nextUsage = await request('/usage');
if (cards.get(host)?.refresh !== refresh || operations.version !== version || operations.submitting) return;
- social = nextSocial;
+ social = nextUsage.social_claim;
Object.assign(state, nextUsage);
status.textContent = nextUsage.tier !== 'free' ? t('quota.ready') : '';
renderState();
diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.js
index e52ca77b7..4f69de036 100644
--- a/src/chrome/src/ui/sidepanel.js
+++ b/src/chrome/src/ui/sidepanel.js
@@ -6774,7 +6774,8 @@ const quotaController = createQuotaController({
if (isProcessing) throw new Error(t('sp.retry.busy'));
await setActiveChatProvider(id);
selectedProviderId = id; providerSelect.value = id; syncProviderPickerButton();
- await testConnection({ providerId: id });
+ const result = await testConnection({ providerId: id });
+ if (!result?.ok) throw new Error(result?.error || t('sp.status.failed'));
},
openSettings: openProvidersSettingsPage,
continueTask(btn, context) {
@@ -7618,10 +7619,12 @@ async function testConnection(options = {}) {
statusDot.title = res.ok
? t('sp.status.connected', { model: res.model || providerId })
: t('sp.status.error', { msg: res.error });
- } catch {
+ return res;
+ } catch (error) {
if (requestId !== providerTestRequestId || providerSelect.value !== providerId) return;
statusDot.className = 'status-dot offline';
statusDot.title = t('sp.status.failed');
+ return { ok: false, error: error?.message || t('sp.status.failed') };
}
}
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index fd6694c35..dcfe3b317 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -20262,13 +20262,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
onUpdate('thinking', { step: 1, note: 'Preparing response…' });
let finalResponse = '';
let status = 'done';
+ let quotaFailure = false;
try {
finalResponse = await this._generateContextOnlyResponse(
tabId, messages, provider, costState, runId,
{ phase: 'response_only', step: 1, runOptions, currentUserMessage, priorMessageSet, shareCapture },
);
} catch (error) {
- if (error.quota) onUpdate('quota', { quota: error.quota });
+ if (error.quota) {
+ quotaFailure = true;
+ onUpdate('quota', { quota: error.quota });
+ }
status = this._isCostAllowanceError(error) ? 'cost_limit' : 'error';
finalResponse = this._isCostAllowanceError(error)
? error.message
@@ -20282,7 +20286,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
messages.push({ role: 'assistant', content: finalResponse });
onUpdate('text', { content: finalResponse, replace: true });
- if (status !== 'done') onUpdate('error', { message: finalResponse });
+ if (status !== 'done' && !quotaFailure) onUpdate('error', { message: finalResponse });
this._persist(tabId);
return { content: finalResponse, status };
}
diff --git a/src/firefox/src/ui/compass-quota.js b/src/firefox/src/ui/compass-quota.js
index 5deb3072b..f00df6c12 100644
--- a/src/firefox/src/ui/compass-quota.js
+++ b/src/firefox/src/ui/compass-quota.js
@@ -41,7 +41,15 @@ export function createQuotaController({ t, locale, request, openUrl, providers,
const providerArea = el('div', '', 'quota-providers');
const status = el('div', '', 'quota-status');
status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
- const share = button(t('quota.get'), () => { host.dataset.claimOpen = 'true'; showClaim(); }, 'quota-share');
+ const share = button(t('quota.get'), async () => {
+ host.dataset.claimOpen = 'true';
+ operations.version++;
+ try {
+ if (!social?.share_url) social = await request('/promotions/social');
+ if (cards.get(host)?.refresh !== refresh) return;
+ renderState(); showClaim();
+ } catch (error) { status.textContent = error.message; }
+ }, 'quota-share');
const subscribe = button(t('quota.subscribe'), () => { event('checkout_open'); openUrl(quota.subscribe_url); }, 'subscribe-btn');
const other = button(t('quota.other'), async () => {
providerArea.replaceChildren();
@@ -88,7 +96,7 @@ export function createQuotaController({ t, locale, request, openUrl, providers,
}
function showClaim(focus = true) {
- if (!social) { void refresh().then(() => { if (social) showClaim(); }); return; }
+ if (!social?.share_url) { return; }
if (!social.eligible || social.status === 'pending') { claimArea.replaceChildren(); return; }
// A balance/status refresh must not replace the user's focused editor or draft.
const existingForm = claimArea.querySelector('form');
@@ -150,9 +158,9 @@ export function createQuotaController({ t, locale, request, openUrl, providers,
const version = operations.version;
inflight = (async () => {
try {
- const [nextSocial, nextUsage] = await Promise.all([request('/promotions/social'), request('/usage')]);
+ const nextUsage = await request('/usage');
if (cards.get(host)?.refresh !== refresh || operations.version !== version || operations.submitting) return;
- social = nextSocial;
+ social = nextUsage.social_claim;
Object.assign(state, nextUsage);
status.textContent = nextUsage.tier !== 'free' ? t('quota.ready') : '';
renderState();
diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.js
index e05299d63..ae1ae14dc 100644
--- a/src/firefox/src/ui/sidepanel.js
+++ b/src/firefox/src/ui/sidepanel.js
@@ -6618,7 +6618,8 @@ const quotaController = createQuotaController({
if (isProcessing) throw new Error(t('sp.retry.busy'));
await setActiveChatProvider(id);
selectedProviderId = id; providerSelect.value = id; syncProviderPickerButton();
- await testConnection({ providerId: id });
+ const result = await testConnection({ providerId: id });
+ if (!result?.ok) throw new Error(result?.error || t('sp.status.failed'));
},
openSettings: openProvidersSettingsPage,
continueTask(btn, context) {
@@ -7413,10 +7414,12 @@ async function testConnection(options = {}) {
statusDot.title = res.ok
? t('sp.status.connected', { model: res.model || providerId })
: t('sp.status.error', { msg: res.error });
- } catch {
+ return res;
+ } catch (error) {
if (requestId !== providerTestRequestId || providerSelect.value !== providerId) return;
statusDot.className = 'status-dot offline';
statusDot.title = t('sp.status.failed');
+ return { ok: false, error: error?.message || t('sp.status.failed') };
}
}
diff --git a/test/compass-quota-ui.mjs b/test/compass-quota-ui.mjs
index 6fe4a0eef..a828d794a 100644
--- a/test/compass-quota-ui.mjs
+++ b/test/compass-quota-ui.mjs
@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';
import assert from 'node:assert/strict';
const root = resolve('.');
+const locales = ['en', 'es', 'fr', 'tr', 'zh', 'ru', 'uk', 'ar', 'ja', 'ko', 'id', 'th', 'ms', 'tl', 'pl', 'he', 'hi', 'pt', 'vi', 'bn', 'fa', 'nl', 'de'];
const output = resolve(process.env.QUOTA_UI_OUTPUT || resolve(tmpdir(), 'webbrain-compass-review'));
await mkdir(output, { recursive: true });
const fixture = (build, locale) => `<!doctype html><meta charset="utf-8"><link rel="stylesheet" href="/src/${build}/styles/sidepanel.css">
@@ -20,7 +21,7 @@ const code=${JSON.stringify(locale)};
document.documentElement.lang=code; document.documentElement.dir=['ar','he','fa'].includes(code)?'rtl':'ltr';
const t=(key,params={})=>(quotaTranslations[code][key] || dict[key] || en[key] || key).replace(/[{]([a-z]+)[}]/g,(_,k)=>params[k] ?? '{'+k+'}');
window.requests=[];window.opened=[];window.switched=[];window.continuations=[];window.settingsOpened=0;window.deferredRefresh=[];
-window.claim={eligible:true,status:'draft',claim_id:'opaque-random-claim',share_url:'https://webbrain.one/?share=opaque-random-claim',remaining_credit_usd:0};
+window.claim={eligible:true,status:'draft',claim_id:null,share_url:null,remaining_credit_usd:0};
window.usage={tier:'free',base_weekly_allowance_usd:0.375,weekly_limit_usd:0.375,promotional_balance_usd:0,next_reset_at:'2026-10-12T00:00:00Z'};
window.makeController=()=>createQuotaController({t,locale:()=>code,request:async(path,body)=>{
requests.push({path,body});if(window.offline)throw Error('offline');
@@ -30,10 +31,11 @@ window.makeController=()=>createQuotaController({t,locale:()=>code,request:async
if(window.rejectSubmission)throw Error('Submission not received.');
claim={...claim,status:'pending',platform:body.platform,post_url:body.post_url};return {...claim};
}
+ if(path==='/promotions/social')claim={...claim,claim_id:'opaque-random-claim',share_url:'https://webbrain.one/?share=opaque-random-claim'};
const snapshot=path==='/usage'?{...usage,social_claim:{...claim}}:{...claim};
if(window.delayRefresh)return new Promise((resolve,reject)=>deferredRefresh.push(()=>window.failDelayedRefresh?reject(Error('offline')):resolve(snapshot)));
return snapshot;
-},openUrl:url=>opened.push(url),providers:async()=>[{id:'webbrain_cloud',label:'WebBrain Compass'},{id:'own-key',label:'My API key'},{id:'local',label:'Local model'}],switchProvider:async id=>switched.push(id),openSettings:()=>settingsOpened++,continueTask:(_button,context)=>continuations.push(context),persist:()=>{}});
+},openUrl:url=>opened.push(url),providers:async()=>[{id:'webbrain_cloud',label:'WebBrain Compass'},{id:'own-key',label:'My API key'},{id:'local',label:'Local model'}],switchProvider:async id=>{if(window.providerError)throw Error(window.providerError);switched.push(id);},openSettings:()=>settingsOpened++,continueTask:(_button,context)=>continuations.push(context),persist:()=>{}});
window.controller=makeController();controller.mount(document.querySelector('#card'),{code:'webbrain_cloud_free_tier_exceeded',usage:{...usage,social_claim:claim},subscribe_url:'https://buy.stripe.com/test?client_reference_id=device-guid'},{mode:'act',foreground:true});
window.ready=true;
</script>`;
@@ -44,7 +46,9 @@ const server = createServer(async (req, res) => {
const build = url.searchParams.get('build');
if (!['chrome', 'firefox'].includes(build)) throw Error('unknown build');
res.setHeader('Content-Type', 'text/html; charset=utf-8');
- res.end(fixture(build, url.searchParams.get('locale') || 'en')); return;
+ const requestedLocale = url.searchParams.get('locale');
+ const locale = locales.find(code => code === requestedLocale) || 'en';
+ res.end(fixture(build, locale)); return;
}
const path = resolve(root, '.' + url.pathname);
if (!path.startsWith(root + sep)) throw Error('outside root');
@@ -60,7 +64,7 @@ try {
if (process.env.QUOTA_UI_BROWSER && process.env.QUOTA_UI_BROWSER !== build) continue;
const browser = await engine.launch();
try {
- for (const lang of ['en', 'es', 'fr', 'tr', 'zh', 'ru', 'uk', 'ar', 'ja', 'ko', 'id', 'th', 'ms', 'tl', 'pl', 'he', 'hi', 'pt', 'vi', 'bn', 'fa', 'nl', 'de']) {
+ for (const lang of locales) {
const page = await browser.newPage({ viewport: { width: 280, height: 1000 }, timezoneId: 'Europe/Istanbul' });
const errors = []; page.on('pageerror', e => errors.push(e.message));
await page.goto(`${origin}/quota?build=${build}&locale=${lang}`);
@@ -69,6 +73,7 @@ try {
assert.equal(await page.locator('#card').evaluate(el => /quota\.|\{(?:base|credit|time)\}/.test(el.textContent)), false); checks++;
assert.equal(await page.evaluate(() => continuations.length), 0); checks++;
if (lang === 'en') {
+ assert.equal(await page.evaluate(() => requests.filter(r => r.path === '/promotions/social').length), 0); checks++;
assert.match(await page.locator('.quota-balance').textContent(), /\$0\.375/);
assert.match(await page.locator('.quota-reset').textContent(), /3:00:00 AM/);
await page.locator('.quota-share').focus();
@@ -105,7 +110,7 @@ try {
assert.match(await page.locator('.quota-claim input').inputValue(), /bsky\.app/); checks += 3;
// A focus refresh may already have read draft state when submission completes.
await page.evaluate(() => { window.delayRefresh = true; window.staleRefresh = controller.refreshAll(); });
- assert.equal(await page.evaluate(() => deferredRefresh.length), 2); checks++;
+ assert.equal(await page.evaluate(() => deferredRefresh.length), 1); checks++;
await page.locator('.quota-claim form button[type=submit]').click();
await page.waitForFunction(() => claim.status === 'pending');
await page.evaluate(async () => { window.delayRefresh = false; deferredRefresh.splice(0).forEach(resolve => resolve()); await staleRefresh; });
@@ -150,6 +155,12 @@ try {
assert.equal(await page.evaluate(() => continuations.length), 0); checks += 3;
await page.locator('.quota-other').click();
await page.locator('.quota-providers select').selectOption('local');
+ await page.evaluate(() => { window.providerError = 'Invalid credentials'; });
+ await page.locator('.quota-providers button').first().click();
+ assert.match(await page.locator('.quota-status').textContent(), /Invalid credentials/);
+ assert.deepEqual(await page.evaluate(() => switched), []);
+ assert.equal(await page.evaluate(() => requests.filter(r => r.body?.event === 'provider_switch').length), 0); checks += 3;
+ await page.evaluate(() => { window.providerError = null; });
await page.locator('.quota-providers button').first().click();
assert.deepEqual(await page.evaluate(() => switched), ['local']);
assert.equal(await page.evaluate(() => continuations.length), 0); checks += 2;
diff --git a/test/compass-quota.mjs b/test/compass-quota.mjs
index d7c77b882..e8dc5ca7a 100644
--- a/test/compass-quota.mjs
+++ b/test/compass-quota.mjs
@@ -100,6 +100,48 @@ for (const browser of ['chrome', 'firefox']) {
render(host, 'Restored localized text');
assert.equal(mounted[2].retry, true, 'restored durable-turn decision must survive rerendering');
});
+ test(`${browser}: response-only quota emits one recovery signal and preserves the stopped turn`, async () => {
+ const agent = new Agent({});
+ agent._consumeContextOnlyAbort = () => null;
+ agent._persist = () => {};
+ const events = [];
+ const messages = [{ role: 'user', content: 'Keep this question' }];
+ const error = provider._httpError(402, JSON.stringify(payload), 'Compass');
+ agent._generateContextOnlyResponse = async () => { throw error; };
+ const result = await agent._completeResponseOnlyTurn(41, messages, (type, data) => events.push({ type, data }));
+ assert.equal(result.status, 'cost_limit');
+ assert.equal(events.filter(e => e.type === 'quota').length, 1);
+ assert.equal(events.filter(e => e.type === 'error').length, 0);
+ assert.equal(messages[0].content, 'Keep this question');
+ assert.equal(messages.at(-1).content, result.content);
+ agent._generateContextOnlyResponse = async () => { throw new Error('Other failure'); };
+ events.length = 0;
+ await agent._completeResponseOnlyTurn(41, messages, (type, data) => events.push({ type, data }));
+ assert.equal(events.filter(e => e.type === 'error').length, 1, 'ordinary errors must still be rendered');
+ });
+ test(`${browser}: quota provider switch checks real connection results, exceptions and stale tests`, async () => {
+ const panel = fs.readFileSync(new URL('ui/sidepanel.js', base), 'utf8');
+ const start = panel.indexOf('async function testConnection(');
+ const connection = panel.slice(start, panel.indexOf('function getSlashAutocompleteContext(', start));
+ const switchStart = panel.indexOf(' async switchProvider(id) {');
+ const switchMethod = panel.slice(switchStart, panel.indexOf(' openSettings:', switchStart));
+ let response = { ok: false, error: 'Invalid credentials' };
+ let failure;
+ const sandbox = { providerSelect: { value: 'own-key' }, providerTestRequestId: 0, isProcessing: false,
+ statusDot: {}, t: key => key, setActiveChatProvider: async () => {}, syncProviderPickerButton: () => {},
+ sendToBackground: async () => { if (failure) throw failure; return response; } };
+ const context = vm.createContext(sandbox);
+ const switchProvider = vm.runInContext(`${connection}; ({${switchMethod}}).switchProvider`, context);
+ await assert.rejects(switchProvider('own-key'), /Invalid credentials/);
+ assert.equal(sandbox.statusDot.className, 'status-dot offline');
+ failure = new Error('Network unavailable');
+ await assert.rejects(switchProvider('own-key'), /Network unavailable/);
+ failure = null; response = { ok: true, model: 'local model' };
+ await switchProvider('local');
+ assert.equal(sandbox.statusDot.className, 'status-dot online');
+ sandbox.sendToBackground = async () => { sandbox.providerTestRequestId++; return response; };
+ await assert.rejects(switchProvider('local'), /sp.status.failed/);
+ });
test(`${browser}: all supported locales and exact decimal displays`, () => {
const codes = ['en', 'es', 'fr', 'tr', 'zh', 'ru', 'uk', 'ar', 'ja', 'ko', 'id', 'th', 'ms', 'tl', 'pl', 'he', 'hi', 'pt', 'vi', 'bn', 'fa', 'nl', 'de'];
for (const code of codes) {
diff --git a/test/pdf-mime-handler-e2e.mjs b/test/pdf-mime-handler-e2e.mjs
index 30347fc12..de457544c 100644
--- a/test/pdf-mime-handler-e2e.mjs
+++ b/test/pdf-mime-handler-e2e.mjs
@@ -157,15 +157,13 @@ async function inspectPdfRouting(context, url, extensionId, waitMs = 2000) {
// page itself is the signal, and no probe should be issued.
async function assertHandlerTabSkipsContentTypeProbe(context, settings, extensionId, fixture) {
const sourceUrl = fixture.opaqueUrl;
- const page = await context.newPage();
+ // Capture Chrome's tab ID when creating it. A PDF target may be replaced by
+ // the native viewer before Playwright's Page and chrome.tabs snapshots agree.
+ const tabId = await settings.evaluate(async url => (await chrome.tabs.create({ url, active: false })).id, sourceUrl);
+ assert.ok(Number.isInteger(tabId) && tabId > 0, 'Could not create the tab showing the opaque PDF.');
try {
- await page.goto(sourceUrl, { waitUntil: 'commit', timeout: 30_000 });
-
- const tabId = await settings.waitForFunction(async url => {
- const tabs = await chrome.tabs.query({});
- return tabs.find(tab => tab.url === url)?.id ?? null;
- }, sourceUrl, { timeout: 15_000 }).then(handle => handle.jsonValue());
- assert.ok(Number.isInteger(tabId) && tabId > 0, 'Could not find the tab showing the opaque PDF.');
+ await settings.waitForFunction(async ({ id, url }) => (await chrome.tabs.get(id)).url === url,
+ { id: tabId, url: sourceUrl }, { timeout: 15_000 });
// Exactly what the "Open PDF with WebBrain" context menu does. That entry
// is the only route to a wrapped handler URL, and it appears because the
@@ -226,7 +224,7 @@ async function assertHandlerTabSkipsContentTypeProbe(context, settings, extensio
`The handler tab triggered a Content-Type probe: ${fixture.requests.join(', ')}`,
);
} finally {
- await page.close();
+ await settings.evaluate(id => chrome.tabs.remove(id), tabId);
}
}