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: validate memory learning and PDF viewer preferences
Emre Sokulludfee3d8e7daa
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.jsindex 39d241012..0ac6a43b7 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -337,7 +337,7 @@ async function setNativePdfMimeHandlerEnabled(enabled) {async function syncNativePdfMimeHandlerFromStorage() {const stored = await chrome.storage.local.get({ [PDF_VIEWER_ENABLED_KEY]: true });- return setNativePdfMimeHandlerEnabled(stored?.[PDF_VIEWER_ENABLED_KEY] !== false);+ return setNativePdfMimeHandlerEnabled(stored?.[PDF_VIEWER_ENABLED_KEY] === true);}function reportPdfMimeHandlerSyncFailure(error) {@@ -710,17 +710,17 @@ async function saveUserMemoryExtractionQueue(queue) {}async function isUserMemoryExtractionEnabled() {- const stored = await chrome.storage.local.get([- USER_MEMORY_ENABLED_KEY,- USER_MEMORY_AUTO_CAPTURE_KEY,- ]);+ const stored = await chrome.storage.local.get({+ [USER_MEMORY_ENABLED_KEY]: true,+ [USER_MEMORY_AUTO_CAPTURE_KEY]: true,+ });return stored[USER_MEMORY_ENABLED_KEY] !== false- && stored[USER_MEMORY_AUTO_CAPTURE_KEY] !== false;+ && stored[USER_MEMORY_AUTO_CAPTURE_KEY] === true;}async function isUserMemoryFormCaptureEnabled() {- const stored = await chrome.storage.local.get(USER_MEMORY_FORM_CAPTURE_KEY);- return stored[USER_MEMORY_FORM_CAPTURE_KEY] !== false;+ const stored = await chrome.storage.local.get({ [USER_MEMORY_FORM_CAPTURE_KEY]: true });+ return stored[USER_MEMORY_FORM_CAPTURE_KEY] === true;}async function withUserMemoryExtractionQueueLock(task) {@@ -1179,7 +1179,8 @@ chrome.runtime.onStartup?.addListener(async () => {// Listen for setting changeschrome.storage.onChanged.addListener((changes, areaName) => {if (areaName === 'local' && changes[PDF_VIEWER_ENABLED_KEY]) {- setNativePdfMimeHandlerEnabled(changes[PDF_VIEWER_ENABLED_KEY].newValue !== false)+ const value = changes[PDF_VIEWER_ENABLED_KEY].newValue;+ setNativePdfMimeHandlerEnabled(value === undefined || value === true).catch(reportPdfMimeHandlerSyncFailure);}if (changes.wbLocale) {@@ -2958,19 +2959,19 @@ async function handleMessage(msg, sender) {case 'get_user_memory': {const store = await userMemoryStore.load();- const settings = await chrome.storage.local.get([- USER_MEMORY_ENABLED_KEY,- USER_MEMORY_AUTO_CAPTURE_KEY,- USER_MEMORY_FORM_CAPTURE_KEY,- USER_MEMORY_MAX_PROMPT_CHARS_KEY,- ]);+ const settings = await chrome.storage.local.get({+ [USER_MEMORY_ENABLED_KEY]: true,+ [USER_MEMORY_AUTO_CAPTURE_KEY]: true,+ [USER_MEMORY_FORM_CAPTURE_KEY]: true,+ [USER_MEMORY_MAX_PROMPT_CHARS_KEY]: normalizeUserMemoryMaxPromptChars(),+ });return {ok: true,store,records: store.records,enabled: settings[USER_MEMORY_ENABLED_KEY] !== false,- autoCaptureEnabled: settings[USER_MEMORY_AUTO_CAPTURE_KEY] !== false,- formCaptureEnabled: settings[USER_MEMORY_FORM_CAPTURE_KEY] !== false,+ autoCaptureEnabled: settings[USER_MEMORY_AUTO_CAPTURE_KEY] === true,+ formCaptureEnabled: settings[USER_MEMORY_FORM_CAPTURE_KEY] === true,maxPromptChars: normalizeUserMemoryMaxPromptChars(settings[USER_MEMORY_MAX_PROMPT_CHARS_KEY]),};}diff --git a/src/chrome/src/ui/pdf-handler.js b/src/chrome/src/ui/pdf-handler.jsindex 362b4c511..adec9f04b 100644--- a/src/chrome/src/ui/pdf-handler.js+++ b/src/chrome/src/ui/pdf-handler.js@@ -680,7 +680,7 @@ async function initialize() {}if (!explicitViewer) {const stored = await api.storage.local.get({ [PDF_VIEWER_ENABLED_KEY]: true });- if (stored?.[PDF_VIEWER_ENABLED_KEY] === false) {+ if (stored?.[PDF_VIEWER_ENABLED_KEY] !== true) {await fallbackToNative();return;}diff --git a/src/chrome/src/ui/settings.js b/src/chrome/src/ui/settings.jsindex da9dde953..256589151 100644--- a/src/chrome/src/ui/settings.js+++ b/src/chrome/src/ui/settings.js@@ -794,7 +794,7 @@ async function init() {}verboseToggle.checked = stored.verboseMode || false;if (selectionShortcutToggle) selectionShortcutToggle.checked = stored.selectionShortcutEnabled !== false;- if (pdfViewerToggle) pdfViewerToggle.checked = stored.pdfViewerEnabled !== false;+ if (pdfViewerToggle) pdfViewerToggle.checked = stored.pdfViewerEnabled === undefined || stored.pdfViewerEnabled === true;if (autoGroupTabsToggle) autoGroupTabsToggle.checked = stored[AUTO_GROUP_TABS_KEY] !== false;if (helpImproveToggle) helpImproveToggle.checked = stored.helpImproveWebBrain !== false; // on by defaultscreenshotToggle.checked = stored.screenshotFallback ?? true; // on by defaultdiff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex cdb7eb961..831dc313d 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -599,17 +599,17 @@ async function saveUserMemoryExtractionQueue(queue) {}async function isUserMemoryExtractionEnabled() {- const stored = await browser.storage.local.get([- USER_MEMORY_ENABLED_KEY,- USER_MEMORY_AUTO_CAPTURE_KEY,- ]);+ const stored = await browser.storage.local.get({+ [USER_MEMORY_ENABLED_KEY]: true,+ [USER_MEMORY_AUTO_CAPTURE_KEY]: true,+ });return stored[USER_MEMORY_ENABLED_KEY] !== false- && stored[USER_MEMORY_AUTO_CAPTURE_KEY] !== false;+ && stored[USER_MEMORY_AUTO_CAPTURE_KEY] === true;}async function isUserMemoryFormCaptureEnabled() {- const stored = await browser.storage.local.get(USER_MEMORY_FORM_CAPTURE_KEY);- return stored[USER_MEMORY_FORM_CAPTURE_KEY] !== false;+ const stored = await browser.storage.local.get({ [USER_MEMORY_FORM_CAPTURE_KEY]: true });+ return stored[USER_MEMORY_FORM_CAPTURE_KEY] === true;}async function withUserMemoryExtractionQueueLock(task) {@@ -2468,19 +2468,19 @@ async function handleMessage(msg, sender) {case 'profile_sync_reset': return { ok: true, ...(await profileSync.reset(String(msg.password || ''))) };case 'get_user_memory': {const store = await userMemoryStore.load();- const settings = await browser.storage.local.get([- USER_MEMORY_ENABLED_KEY,- USER_MEMORY_AUTO_CAPTURE_KEY,- USER_MEMORY_FORM_CAPTURE_KEY,- USER_MEMORY_MAX_PROMPT_CHARS_KEY,- ]);+ const settings = await browser.storage.local.get({+ [USER_MEMORY_ENABLED_KEY]: true,+ [USER_MEMORY_AUTO_CAPTURE_KEY]: true,+ [USER_MEMORY_FORM_CAPTURE_KEY]: true,+ [USER_MEMORY_MAX_PROMPT_CHARS_KEY]: normalizeUserMemoryMaxPromptChars(),+ });return {ok: true,store,records: store.records,enabled: settings[USER_MEMORY_ENABLED_KEY] !== false,- autoCaptureEnabled: settings[USER_MEMORY_AUTO_CAPTURE_KEY] !== false,- formCaptureEnabled: settings[USER_MEMORY_FORM_CAPTURE_KEY] !== false,+ autoCaptureEnabled: settings[USER_MEMORY_AUTO_CAPTURE_KEY] === true,+ formCaptureEnabled: settings[USER_MEMORY_FORM_CAPTURE_KEY] === true,maxPromptChars: normalizeUserMemoryMaxPromptChars(settings[USER_MEMORY_MAX_PROMPT_CHARS_KEY]),};}diff --git a/test/pdf-selection.mjs b/test/pdf-selection.mjsindex f26d6eb66..6c543604b 100644--- a/test/pdf-selection.mjs+++ b/test/pdf-selection.mjs@@ -45,10 +45,10 @@ async function testPdfViewerDefaultsOnWithExplicitAndCapabilityFallbacks() {const background = await readFile(path.join(root, 'src', 'chrome', 'src', 'background.js'), 'utf8');assert.match(html, /id="toggle-pdf-viewer"/);assert.match(settings, /pdfViewerEnabled/);- assert.match(settings, /stored\.pdfViewerEnabled !== false/);+ assert.match(settings, /stored\.pdfViewerEnabled === undefined \|\| stored\.pdfViewerEnabled === true/);assert.match(source, /typeof api\?\.mimeHandler\?\.getStreamInfo === 'function'/);assert.match(source, /api\.storage\.local\.get\(\{ \[PDF_VIEWER_ENABLED_KEY\]: true \}\)/);- assert.match(source, /if \(stored\?\.\[PDF_VIEWER_ENABLED_KEY\] === false\)/);+ assert.match(source, /if \(stored\?\.\[PDF_VIEWER_ENABLED_KEY\] !== true\)/);assert.match(source, /const explicitViewer = Boolean\(explicitUrl && Number\.isInteger\(explicitTabId\) && explicitTabId >= 0\)/);assert.match(source, /if \(!explicitViewer\)/);assert.match(source, /fallbackToNative\(\);/);@@ -56,7 +56,47 @@ async function testPdfViewerDefaultsOnWithExplicitAndCapabilityFallbacks() {assert.match(source, /MAX_PDF_PAGES/);assert.match(background, /mimeHandler\?\.setMimeHandlerOptions/);assert.match(background, /syncNativePdfMimeHandlerFromStorage/);- assert.match(background, /changes\[PDF_VIEWER_ENABLED_KEY\]\.newValue !== false/);+ assert.match(background, /const value = changes\[PDF_VIEWER_ENABLED_KEY\]\.newValue;\s*setNativePdfMimeHandlerEnabled\(value === undefined \|\| value === true\)/);+}++async function testPdfPreferencesRejectMalformedValues() {+ const background = await readFile(path.join(root, 'src/chrome/src/background.js'), 'utf8');+ const handler = await readFile(handlerJsPath, 'utf8');+ const settings = await readFile(settingsJsPath, 'utf8');+ const syncBlock = background.match(/async function syncNativePdfMimeHandlerFromStorage\(\) \{[\s\S]*?\n\}/)?.[0];+ const changeBlock = background.match(/if \(areaName === 'local' && changes\[PDF_VIEWER_ENABLED_KEY\]\) \{[\s\S]*?\n \}/)?.[0];+ const toggleBlock = settings.match(/pdfViewerToggle\.checked = [^;]+;/)?.[0];+ const gateStart = handler.indexOf(' if (!explicitViewer) {');+ const gateEnd = handler.indexOf(' const streamInfo = explicitViewer', gateStart);+ assert.ok(syncBlock && changeBlock && toggleBlock && gateStart >= 0 && gateEnd > gateStart);+ for (const [value, expected] of [+ [undefined, true], [true, true], [false, false], [null, false],+ ['false', false], ['true', false], [0, false], [1, false], [{}, false], [[], false],+ ]) {+ const stored = value === undefined ? {} : { pdfViewerEnabled: value };+ const api = { storage: { local: { get: async defaults => ({ ...defaults, ...stored }) } } };+ const updates = [];+ const setEnabled = async enabled => { updates.push(enabled); };+ const sync = Function('chrome', 'PDF_VIEWER_ENABLED_KEY', 'setNativePdfMimeHandlerEnabled',+ `${syncBlock}\nreturn syncNativePdfMimeHandlerFromStorage;`)(api, 'pdfViewerEnabled', setEnabled);+ await sync();+ const changes = { pdfViewerEnabled: value === undefined ? { oldValue: true } : { newValue: value } };+ Function('changes', 'areaName', 'PDF_VIEWER_ENABLED_KEY', 'setNativePdfMimeHandlerEnabled', 'reportPdfMimeHandlerSyncFailure',+ changeBlock)(changes, 'local', 'pdfViewerEnabled', setEnabled, error => { throw error; });+ assert.deepEqual(updates, [expected, expected], `PDF runtime: ${JSON.stringify(value)}`);+ const toggle = { checked: true };+ Function('stored', 'pdfViewerToggle', toggleBlock)(stored, toggle);+ assert.equal(toggle.checked, expected);+ for (const explicitViewer of [false, true]) {+ let fallbacks = 0;+ const continued = await Function('api', 'PDF_VIEWER_ENABLED_KEY', 'explicitViewer', 'fallbackToNative',+ `return (async () => { ${handler.slice(gateStart, gateEnd)} return true; })();`)(+ api, 'pdfViewerEnabled', explicitViewer, async () => { fallbacks++; },+ );+ assert.equal(continued === true, explicitViewer || expected);+ assert.equal(fallbacks, explicitViewer || expected ? 0 : 1);+ }+ }}async function testPdfHandlerProvidesCompleteViewerControls() {@@ -377,6 +417,7 @@ const tests = [['manifest registers a top-level application/pdf handler', testManifestRegistration],['PDF handler consumes Chrome stream info and renders a text layer', testHandlerUsesChromeStreamAndTextLayer],['PDF viewer defaults on with explicit and capability fallbacks', testPdfViewerDefaultsOnWithExplicitAndCapabilityFallbacks],+ ['PDF preference validation preserves defaults and explicit viewer entry', testPdfPreferencesRejectMalformedValues],['PDF handler provides complete viewer controls', testPdfHandlerProvidesCompleteViewerControls],['scanned PDF OCR has a bounded handler/background contract', testScannedPdfOcrContract],['OCR normalization keeps bounded normalized text lines', testOcrNormalizationKeepsOnlyBoundedNormalizedLines],diff --git a/test/run.js b/test/run.jsindex c6bbbc733..f64795639 100644--- a/test/run.js+++ b/test/run.js@@ -4277,8 +4277,8 @@ test('user memory browser wiring is mirrored and non-blocking', () => {assert.doesNotMatch(addMemoryRoute[1], new RegExp(`${runtime}\\.storage\\.local\\.set\\(\\{ \\[USER_MEMORY_ENABLED_KEY\\]: true \\}\\)`), `${label}: manual memory saves should not re-enable disabled memory`);assert.match(background, /case 'delete_user_memory': \{[\s\S]*userMemoryStore\.delete\(String\(msg\.id \|\| ''\)\)[\s\S]*syncAgentUserMemoryFromStorage/, `${label}: user-facing memory delete should hard-delete records`);assert.doesNotMatch(background, /case 'delete_user_memory': \{[\s\S]*userMemoryStore\.archive\(String\(msg\.id \|\| ''\)\)/, `${label}: user-facing memory delete should not archive plaintext`);- assert.match(background, new RegExp(`${runtime}\\.storage\\.local\\.get\\(\\[\\s*USER_MEMORY_ENABLED_KEY,[\\s\\S]*USER_MEMORY_AUTO_CAPTURE_KEY`), `${label}: extraction should read both memory and auto-capture toggles`);- assert.match(background, /async function isUserMemoryExtractionEnabled\(\)[\s\S]*stored\[USER_MEMORY_ENABLED_KEY\] !== false[\s\S]*stored\[USER_MEMORY_AUTO_CAPTURE_KEY\] !== false/, `${label}: extraction should be gated by the main memory toggle`);+ assert.match(background, new RegExp(`${runtime}\\.storage\\.local\\.get\\(\\{\\s*\\[USER_MEMORY_ENABLED_KEY\\]: true,[\\s\\S]*\\[USER_MEMORY_AUTO_CAPTURE_KEY\\]: true`), `${label}: extraction should apply defaults while reading both memory toggles`);+ assert.match(background, /async function isUserMemoryExtractionEnabled\(\)[\s\S]*stored\[USER_MEMORY_ENABLED_KEY\] !== false[\s\S]*stored\[USER_MEMORY_AUTO_CAPTURE_KEY\] === true/, `${label}: extraction should require valid auto-capture permission and respect the main memory toggle`);assert.match(background, /if \(!await isUserMemoryExtractionEnabled\(\)\) return \{ queued: false, reason: 'disabled' \};/, `${label}: enqueue should not run when memory is disabled`);assert.match(background, /const formCompletionTurn = sourceContext === 'form_completion';/, `${label}: form-derived memory should be classified before extraction text is built`);assert.match(background, /if \(!await isUserMemoryFormCaptureEnabled\(\)\) \{[\s\S]*return \{ queued: false, reason: 'form_capture_disabled' \};/, `${label}: form-derived memory should be gated by its opt-in setting`);@@ -4347,6 +4347,50 @@ test('user memory browser wiring is mirrored and non-blocking', () => {}});+for (const [label, memory] of [['chrome', userMemoryCh], ['firefox', userMemoryFx]]) {+ test(`${label} memory learning defaults on but rejects invalid or unreadable preferences`, async () => {+ const source = fs.readFileSync(path.join(ROOT, `src/${label}/src/background.js`), 'utf8');+ const start = source.indexOf('async function isUserMemoryExtractionEnabled()');+ const end = source.indexOf('async function withUserMemoryExtractionQueueLock(', start);+ const routeStart = source.indexOf("case 'get_user_memory': {");+ const routeEnd = source.indexOf("case 'add_user_memory': {", routeStart);+ assert.ok(start >= 0 && end > start && routeStart >= 0 && routeEnd > routeStart);+ let preferences = {};+ let storageError = false;+ const api = { storage: { local: { get: async defaults => {+ if (storageError) throw new Error('Storage unavailable');+ return { ...defaults, ...preferences };+ } } } };+ const runtime = vm.runInNewContext(+ `${source.slice(start, end)}+ async function getUserMemory() { switch ('get_user_memory') { ${source.slice(routeStart, routeEnd)} } }+ ({ isUserMemoryExtractionEnabled, isUserMemoryFormCaptureEnabled, getUserMemory });`,+ { ...memory, [label === 'chrome' ? 'chrome' : 'browser']: api, userMemoryStore: { load: async () => ({ records: [] }) } },+ );+ for (const [key, property, getter] of [+ [memory.USER_MEMORY_AUTO_CAPTURE_KEY, 'autoCaptureEnabled', 'isUserMemoryExtractionEnabled'],+ [memory.USER_MEMORY_FORM_CAPTURE_KEY, 'formCaptureEnabled', 'isUserMemoryFormCaptureEnabled'],+ ]) {+ for (const [value, expected] of [+ [undefined, true], [true, true], [false, false], [null, false],+ ['false', false], ['true', false], [0, false], [1, false], [{}, false], [[], false],+ ]) {+ preferences = value === undefined ? {} : { [key]: value };+ const detail = `${key}: ${JSON.stringify(value)}`;+ assert.equal(await runtime[getter](), expected, `${detail}: extraction gate`);+ assert.equal((await runtime.getUserMemory())[property], expected, `${detail}: settings response`);+ }+ }+ preferences = { [memory.USER_MEMORY_ENABLED_KEY]: false };+ assert.equal(await runtime.isUserMemoryExtractionEnabled(), false, 'main memory opt-out must disable learning');+ assert.equal((await runtime.getUserMemory()).enabled, false);+ storageError = true;+ await assert.rejects(runtime.isUserMemoryExtractionEnabled(), /Storage unavailable/);+ await assert.rejects(runtime.isUserMemoryFormCaptureEnabled(), /Storage unavailable/);+ await assert.rejects(runtime.getUserMemory(), /Storage unavailable/);+ });+}+test('chrome target blank redirect ignores browser new-tab placeholders', async () => {const realChrome = globalThis.chrome;const realSetTimeout = globalThis.setTimeout;