Skip to content

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

修复:补齐 PDF handler 的 read_page 自动路由

16Mikueb49da2ed85c
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 447fb2f8c..c11d96960 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -71,6 +71,7 @@ import {
buildClaudeDocumentBlock,
PDF_PASSTHROUGH_MAX_BYTES,
} from './pdf-tools.js';
+import { pdfUrlFromTabUrl } from './pdf-extraction.js';
import { normalizePdfOcrResult, PDF_OCR_SYSTEM_PROMPT } from './pdf-ocr.js';
import * as trace from '../trace/recorder.js';
import { buildTerminalRuntimeEvent, enqueueCloudRuntimeEvent, flushCloudRuntimeOutbox } from '../trace/cloud-runtime-outbox.js';
@@ -5358,6 +5359,7 @@ export class Agent extends LoopDetector {
* Decide whether `pageUrl` is a PDF tab the content-script path
* cannot reach. Two paths:
* - Fast path: URL pattern (`isPdfUrl`). Catches `*.pdf` paths and
+ * WebBrain's PDF handler URL after unwrapping its `url` parameter.
* `?file=*.pdf` viewer URLs — the bulk of cases.
* - Slow path: HEAD probe with credentials. Catches PDFs served
* from endpoints whose URL doesn't reveal the type, e.g.
@@ -5377,7 +5379,8 @@ export class Agent extends LoopDetector {
*/
async _isPdfTab(tabId, pageUrl) {
if (!pageUrl) return false;
- if (isPdfUrl(pageUrl)) return true;
+ const pdfUrl = pdfUrlFromTabUrl(pageUrl);
+ if (isPdfUrl(pdfUrl)) return true;
// Cache hit?
const cached = this._isPdfTabCache.get(tabId);
@@ -5387,9 +5390,9 @@ export class Agent extends LoopDetector {
// route to read_pdf, and a fetch against chrome:// or about:// just
// throws.
let isPdf = false;
- if (/^https?:/i.test(pageUrl)) {
+ if (/^https?:/i.test(pdfUrl)) {
try {
- const res = await fetch(pageUrl, {
+ const res = await fetch(pdfUrl, {
method: 'HEAD',
credentials: 'include',
});
@@ -31533,12 +31536,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const pageUrl = tabForPdfCheck?.url || '';
// _isPdfTab does sync URL-pattern match first, then a HEAD probe
// (credentialed) so PDFs served from extension-less paths like
- // `/download?id=42` with `Content-Type: application/pdf` are
- // caught too. Cached per (tabId, pageUrl) — at most one probe
- // per tab+URL.
+ // `/download?id=42` with `Content-Type: application/pdf` are caught
+ // too. A WebBrain PDF handler URL is unwrapped before both checks.
+ // Cached per (tabId, pageUrl) — at most one probe per tab+URL.
if (await this._isPdfTab(tabId, pageUrl)) {
if (name === 'read_page') {
- const pdfResult = await this.executeTool(tabId, 'read_pdf', { url: pageUrl });
+ const pdfResult = await this.executeTool(
+ tabId,
+ 'read_pdf',
+ { url: pdfUrlFromTabUrl(pageUrl) },
+ );
return {
...pdfResult,
redirectedFrom: 'read_page',
diff --git a/src/chrome/src/agent/pdf-extraction.js b/src/chrome/src/agent/pdf-extraction.js
index 27c951545..c75c7e4b4 100644
--- a/src/chrome/src/agent/pdf-extraction.js
+++ b/src/chrome/src/agent/pdf-extraction.js
@@ -25,7 +25,7 @@ function pdfHandlerPage(runtime) {
// When the native MIME handler owns a PDF tab, the tab URL is our own viewer
// page wrapping the real URL in ?url=. read_pdf falls back to the tab URL when
// called without an explicit one, so unwrap it before the scheme check.
-function unwrapPdfHandlerUrl(url, runtime = globalThis.chrome?.runtime) {
+export function unwrapPdfHandlerUrl(url, runtime = globalThis.chrome?.runtime) {
if (url.protocol !== 'chrome-extension:' && url.protocol !== 'moz-extension:') return url;
if (typeof runtime?.getURL !== 'function') return url;
let handler;
@@ -44,6 +44,16 @@ function unwrapPdfHandlerUrl(url, runtime = globalThis.chrome?.runtime) {
}
}
+export function pdfUrlFromTabUrl(value, runtime = globalThis.chrome?.runtime) {
+ let url;
+ try {
+ url = new URL(String(value || ''));
+ } catch {
+ return String(value || '');
+ }
+ return unwrapPdfHandlerUrl(url, runtime).href;
+}
+
export function normalizePdfUrl(value, runtime = globalThis.chrome?.runtime) {
let url;
try {
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 7d3e87e9d..42b4ac30a 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -59,6 +59,7 @@ import {
import { executeWikipediaSkillTool } from './wikipedia-offline.js';
import {
isPdfUrl,
+ pdfUrlFromTabUrl,
extractPdfText,
providerSupportsPdfPassthrough,
buildClaudeDocumentBlock,
@@ -9185,15 +9186,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
*/
async _isPdfTab(tabId, pageUrl) {
if (!pageUrl) return false;
- if (isPdfUrl(pageUrl)) return true;
+ const pdfUrl = pdfUrlFromTabUrl(pageUrl);
+ if (isPdfUrl(pdfUrl)) return true;
const cached = this._isPdfTabCache.get(tabId);
if (cached && cached.url === pageUrl) return cached.isPdf;
let isPdf = false;
- if (/^https?:/i.test(pageUrl)) {
+ if (/^https?:/i.test(pdfUrl)) {
try {
- const res = await fetch(pageUrl, {
+ const res = await fetch(pdfUrl, {
method: 'HEAD',
credentials: 'include',
});
@@ -26047,11 +26049,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
// _isPdfTab does sync URL-pattern match + credentialed HEAD
// fallback so PDFs served from extension-less paths (e.g.
- // `/download?id=42` with `Content-Type: application/pdf`) are
- // also caught. Cached per (tabId, pageUrl).
+ // `/download?id=42` with `Content-Type: application/pdf`) are also
+ // caught. A WebBrain PDF handler URL is unwrapped before both checks.
+ // Cached per (tabId, pageUrl).
if (await this._isPdfTab(tabId, pageUrl)) {
if (name === 'read_page') {
- const pdfResult = await this.executeTool(tabId, 'read_pdf', { url: pageUrl });
+ const pdfResult = await this.executeTool(
+ tabId,
+ 'read_pdf',
+ { url: pdfUrlFromTabUrl(pageUrl) },
+ );
return {
...pdfResult,
redirectedFrom: 'read_page',
diff --git a/src/firefox/src/agent/pdf-tools.js b/src/firefox/src/agent/pdf-tools.js
index 95b505560..845113c81 100644
--- a/src/firefox/src/agent/pdf-tools.js
+++ b/src/firefox/src/agent/pdf-tools.js
@@ -23,6 +23,41 @@
*/
let pdfjsModule = null;
+const DEFAULT_PDF_HANDLER_PAGE = 'src/ui/pdf-handler.html';
+
+function pdfHandlerPage(runtime) {
+ const manifest = typeof runtime?.getManifest === 'function' ? runtime.getManifest() : null;
+ return manifest?.mime_types_handler?.['application/pdf']?.handler_url || DEFAULT_PDF_HANDLER_PAGE;
+}
+
+function unwrapPdfHandlerUrl(url, runtime) {
+ if (url.protocol !== 'chrome-extension:' && url.protocol !== 'moz-extension:') return url;
+ if (typeof runtime?.getURL !== 'function') return url;
+ let handler;
+ try {
+ handler = new URL(runtime.getURL(pdfHandlerPage(runtime)));
+ } catch {
+ return url;
+ }
+ if (url.origin !== handler.origin || url.pathname !== handler.pathname) return url;
+ const inner = url.searchParams.get('url');
+ if (!inner) return url;
+ try {
+ return new URL(inner);
+ } catch {
+ return url;
+ }
+}
+
+export function pdfUrlFromTabUrl(value, runtime = globalThis.browser?.runtime || globalThis.chrome?.runtime) {
+ let url;
+ try {
+ url = new URL(String(value || ''));
+ } catch {
+ return String(value || '');
+ }
+ return unwrapPdfHandlerUrl(url, runtime).href;
+}
/**
* Lazy-load pdfjs only on first PDF read. The legacy bundle is ~1 MB
diff --git a/test/run.js b/test/run.js
index 2ac3082db..79ac31b65 100644
--- a/test/run.js
+++ b/test/run.js
@@ -1353,6 +1353,75 @@ function test(name, fn) { tests.push({ name, fn }); }
console.log('\nselection quote');
+test('read_page redirects WebBrain PDF handler tabs to read_pdf with the source URL', async () => {
+ const previousChrome = globalThis.chrome;
+ const previousBrowser = globalThis.browser;
+ const makeStorageArea = () => ({
+ get: async values => {
+ if (typeof values === 'string') return {};
+ if (Array.isArray(values)) return Object.fromEntries(values.map(key => [key, undefined]));
+ return values || {};
+ },
+ set: async () => {},
+ remove: async () => {},
+ });
+ try {
+ for (const [label, AgentClass, apiName, scheme] of [
+ ['chrome', AgentCh, 'chrome', 'chrome-extension'],
+ ['firefox', AgentFx, 'browser', 'moz-extension'],
+ ]) {
+ const sourceUrl = 'https://papers.example.test/handler-source.pdf';
+ const extensionId = `${label}-pdf-routing`;
+ const handlerUrl = `${scheme}://${extensionId}/src/ui/pdf-handler.html?url=${encodeURIComponent(sourceUrl)}&tabId=73`;
+ const storageArea = makeStorageArea();
+ const api = {
+ runtime: {
+ id: extensionId,
+ getURL: path => `${scheme}://${extensionId}/${path}`,
+ getManifest: () => ({
+ mime_types_handler: {
+ 'application/pdf': { handler_url: 'src/ui/pdf-handler.html' },
+ },
+ }),
+ },
+ storage: {
+ local: storageArea,
+ session: storageArea,
+ onChanged: { addListener: () => {} },
+ },
+ tabs: {
+ get: async () => ({ id: 73, url: handlerUrl }),
+ },
+ };
+ globalThis[apiName] = api;
+ const agent = new AgentClass({});
+ agent._richTextToolbarToolBlock = async () => null;
+ const delegated = [];
+ const executeTool = agent.executeTool.bind(agent);
+ agent.executeTool = async (tabId, name, args, ...rest) => {
+ if (name === 'read_pdf') {
+ delegated.push({ tabId, name, args });
+ return { success: true, pages: ['handler source'] };
+ }
+ return executeTool(tabId, name, args, ...rest);
+ };
+
+ const result = await executeTool(73, 'read_page', {});
+ assert.equal(result.redirectedFrom, 'read_page', `${label}: read_page did not redirect`);
+ assert.deepEqual(delegated, [{
+ tabId: 73,
+ name: 'read_pdf',
+ args: { url: sourceUrl },
+ }], `${label}: redirect did not preserve the handler's source URL`);
+ }
+ } finally {
+ if (previousChrome === undefined) delete globalThis.chrome;
+ else globalThis.chrome = previousChrome;
+ if (previousBrowser === undefined) delete globalThis.browser;
+ else globalThis.browser = previousBrowser;
+ }
+});
+
test('buildSelectionQuote preserves multiline answer text as an editable quote', () => {
const selected = 'First line\n\n<script>alert("x")</script>';
const expected = '> First line\n> \n> <script>alert("x")</script>\n\n';