diff --git a/frontend/extension/README.md b/frontend/extension/README.md index 7b5f62d..6c226b3 100644 --- a/frontend/extension/README.md +++ b/frontend/extension/README.md @@ -10,11 +10,18 @@ These screenshots show the actual popup running in Chromium with a local demo ba | --- | --- | | ![ResearchOS capture popup in light mode](screenshots/popup-light.png) | ![ResearchOS capture popup in dark mode](screenshots/popup-dark.png) | +Right-click capture opens a separate window with the clicked target and destination library ready for confirmation: + +| Light mode | Dark mode | +| --- | --- | +| ![Right-clicked link capture window in light mode](screenshots/context-capture-light.png) | ![Right-clicked link capture window in dark mode](screenshots/context-capture-dark.png) | + ## Capabilities | Capability | Current behavior | | --- | --- | | Capture the current page | Prefills from the active tab's URL, selected identifier, or explicit scholarly metadata. | +| Capture with a right-click | Opens the same capture UI in a small window for the clicked page, link, or selected identifier; waits for you to confirm Save. | | Paste an identifier | Accepts DOIs, arXiv IDs, and HTTP/HTTPS URLs independently of the current page. | | Choose an item type | Automatically detects papers, websites, and GitHub repositories, with manual type overrides. | | Choose a destination | Saves new items to Inbox in the selected ResearchOS library. | @@ -48,6 +55,9 @@ Rebuild and click **Reload** on `chrome://extensions` after changing the source. ## Capturing research - Click the toolbar icon or press **Alt+Shift+S** to open the popup. Customize the shortcut at `chrome://extensions/shortcuts`. +- Right-click a web page, link, or selected DOI/arXiv identifier/URL and choose **Save to ResearchOS**. A small capture window shows that target and your last saved library. Review it and click **Save to Inbox**; opening the window does not import anything automatically. +- Right-clicked links and selections take precedence over the containing page. Invalid selections stay in the input with an explanation so you can correct them. Page captures can use scholarly metadata, including metadata inside a clicked frame where Chrome allows access. +- Each right-click capture has its own temporary target, so opening another capture does not replace one you are reviewing. Closing the capture window clears that target; browser restart or extension reload clears all temporary targets. A capture window restored after that asks you to capture again. - The extension uses the current page's URL and explicit scholarly metadata such as `citation_doi`. A selected DOI, arXiv identifier, or URL takes precedence. - Paste an identifier or URL to save something other than the current page. - **Auto** recognizes DOI/arXiv, OpenReview, Zenodo, PDF and GitHub links. Use **Paper** for publisher pages without scholarly metadata, **Website** to keep a page as a website, or **GitHub** for a repository. Chrome-internal pages and local files cannot be captured; paste a public identifier instead. @@ -61,7 +71,7 @@ The backend writes to the same Supabase database configured for your ResearchOS The extension follows this repository's current unauthenticated backend API. Deployments behind an additional sign-in proxy or custom token authentication need a corresponding authentication integration; this extension does not copy browser sessions or store database keys. -Required permissions are `activeTab`, `scripting`, and `storage`. Page metadata is read only when opening the popup. Server access is requested for the configured hostname on connection; Chrome host permissions cover that host's ports, but fetches use the exact configured URL. No permanent access to every page, browsing history, third-party fonts, or analytics is requested. Only the identifier/URL and library ID are sent to ResearchOS. The backend's usual metadata and AI behavior still applies. +Required permissions are `activeTab`, `scripting`, `storage`, and `contextMenus`. Page metadata is read only when you open the toolbar popup or choose to capture a page from the context menu. Link/selection captures use the explicit target without reading the containing page's metadata. Temporary right-click targets live in extension session storage and are removed when their capture window closes. Server access is requested for the configured hostname on connection; Chrome host permissions cover that host's ports, but fetches use the exact configured URL. No permanent access to every page, browsing history, third-party fonts, or analytics is requested. Only the identifier/URL and library ID are sent to ResearchOS. The backend's usual metadata and AI behavior still applies. If a request loses its connection, times out, or the browser stops during a save, the result may be uncertain even if ResearchOS completed the import. Check Inbox before retrying. The extension never automatically replays a write. Requests time out after 25 seconds to respect Chrome's service-worker fetch limit. @@ -71,7 +81,6 @@ These are ideas for later work, not capabilities included in this release. The o | Addition | What it would enable | Implementation considerations | | --- | --- | --- | -| Right-click capture | Save a page, link, or selected DOI from Chrome's context menu. | Add the context-menu permission and reuse detection and import handling. | | Collections, tags, and capture notes | File an item and record why it matters while saving. | Load library-scoped collections and define how annotations apply to existing duplicates. | | Batch capture | Import selected tabs, bookmarks, or a pasted list of identifiers. | Show per-item progress, cancellation, duplicate review, and rate limits. | | PDF attachment upload | Upload a local or already-open PDF when a DOI or public paper link is unavailable. | Use the app's PDF metadata and upload flow, with explicit file selection and size limits. | @@ -93,6 +102,6 @@ npx playwright install chromium npm run test:extension ``` -The browser test loads a disposable copy of the built Manifest V3 extension in Chromium and uses a local mock API, without contacting your database. It grants only the mock server's host in that disposable copy, since headless Chromium cannot display Chrome's native optional-permission prompt. It verifies service-worker imports for all three item types, library selection, duplicate handling, real script injection, theme persistence, and light/dark screenshots. The shipped manifest retains optional server access only. Browser output is under `frontend/test-results/extension`. +The browser test loads a disposable copy of the built Manifest V3 extension in Chromium and uses a local mock API, without contacting your database. It grants only the mock server's host in that disposable copy, since headless Chromium cannot display Chrome's native optional-permission prompt. It verifies service-worker imports for all three item types, library selection, duplicate handling, real script injection, theme persistence, and light/dark screenshots. It also checks menu registration and capture-window/session handoff for page, link, and selection intents, including explicit save confirmation and cleanup. Context-menu event handling and target extraction are covered by unit tests rather than automating Chrome's native menu. The shipped manifest retains optional server access only. Browser output is under `frontend/test-results/extension`. Chrome references: [host permissions and network requests](https://developer.chrome.com/docs/extensions/develop/concepts/network-requests), [runtime permission requests](https://developer.chrome.com/docs/extensions/reference/api/permissions), and [service worker lifecycle](https://developer.chrome.com/docs/extensions/develop/concepts/service-workers/lifecycle). diff --git a/frontend/extension/e2e/extension.spec.js b/frontend/extension/e2e/extension.spec.js index 99ef8b3..2828b6c 100644 --- a/frontend/extension/e2e/extension.spec.js +++ b/frontend/extension/e2e/extension.spec.js @@ -100,6 +100,52 @@ test('unpacked extension connects, imports all item types, handles duplicates, a await expect(popup.getByRole('heading', { name: 'Save to Inbox' })).toBeVisible() await expect(popup.getByLabel('Save to library')).toHaveValue('lib_2') await expect(popup.getByLabel('Color theme')).toHaveValue('dark') + + // Context-menu event handling and target extraction are covered in contextMenu.test. + // Here exercise the browser/session/window handoff with each resulting intent. + await worker.evaluate(async () => { + await chrome.contextMenus.update('researchos-save-to-inbox', { title: 'Save to ResearchOS' }) + }) + for (const [contextType, identifier, type, reason] of [ + ['selection', '10.1000/context-selection', 'paper', 'Selected text'], + ['link', 'https://example.org/linked-article', 'website', 'Right-clicked link'], + ['page', '10.1000/context-page', 'paper', 'Current page'], + ]) { + const previousImports = imported.length + const opened = context.waitForEvent('page') + const captureId = await worker.evaluate(async capture => { + const id = crypto.randomUUID() + const key = `researchos.contextCapture.${id}` + await chrome.storage.session.set({ [key]: capture }) + const window = await chrome.windows.create({ url: chrome.runtime.getURL(`popup.html?capture=${id}`), type: 'popup', width: 420, height: 680 }) + await chrome.storage.session.set({ [key]: { ...capture, windowId: window.id } }) + return id + }, { context: contextType, identifier, page: { title: identifier }, source: { + type, identifier, reason, + buttonLabel: { page: 'Use this page', link: 'Use this link', selection: 'Use this selection' }[contextType], + }, error: '' }) + const captureWindow = await opened + await expect(captureWindow.getByRole('heading', { name: 'Save to Inbox' })).toBeVisible() + await expect(captureWindow.getByLabel('DOI, arXiv ID, or URL')).toHaveValue(identifier) + await expect(captureWindow.getByLabel('Save to library')).toHaveValue('lib_2') + await expect(captureWindow.getByText(reason)).toBeVisible() + await expect(captureWindow.getByRole('button', { name: { page: 'Use this page', link: 'Use this link', selection: 'Use this selection' }[contextType] })).toBeVisible() + expect(imported.length).toBe(previousImports) + if (contextType === 'link') { + for (const theme of ['light', 'dark']) { + await captureWindow.getByLabel('Color theme').selectOption(theme) + await captureWindow.locator('#root').screenshot({ path: testInfo.outputPath(`context-capture-${theme}.png`), animations: 'disabled' }) + } + } + await captureWindow.getByRole('button', { name: 'Save to Inbox', exact: true }).click() + await expect(captureWindow.getByText('Saved to Inbox', { exact: true })).toBeVisible() + expect(imported.at(-1)).toEqual({ + path: type === 'paper' ? '/api/papers/import' : '/api/websites/import', + body: { [type === 'paper' ? 'identifier' : 'url']: identifier, library_id: 'lib_2' }, + }) + await captureWindow.close() + await expect.poll(() => worker.evaluate(async id => (await chrome.storage.session.get(`researchos.contextCapture.${id}`))[`researchos.contextCapture.${id}`], captureId)).toBeUndefined() + } expect(errors).toEqual([]) } finally { await context?.close() diff --git a/frontend/extension/public/manifest.json b/frontend/extension/public/manifest.json index 67bee31..1911d95 100644 --- a/frontend/extension/public/manifest.json +++ b/frontend/extension/public/manifest.json @@ -4,7 +4,7 @@ "description": "Save papers, DOIs, websites, and GitHub repositories to your ResearchOS Inbox.", "version": "0.1.0", "minimum_chrome_version": "109", - "permissions": ["activeTab", "scripting", "storage"], + "permissions": ["activeTab", "scripting", "storage", "contextMenus"], "optional_host_permissions": ["http://*/*", "https://*/*"], "action": { "default_popup": "popup.html", diff --git a/frontend/extension/screenshots/context-capture-dark.png b/frontend/extension/screenshots/context-capture-dark.png new file mode 100644 index 0000000..9e1ab0b Binary files /dev/null and b/frontend/extension/screenshots/context-capture-dark.png differ diff --git a/frontend/extension/screenshots/context-capture-light.png b/frontend/extension/screenshots/context-capture-light.png new file mode 100644 index 0000000..1f7e0ad Binary files /dev/null and b/frontend/extension/screenshots/context-capture-light.png differ diff --git a/frontend/src/extension/App.jsx b/frontend/src/extension/App.jsx index 74d239d..48cc9a6 100644 --- a/frontend/src/extension/App.jsx +++ b/frontend/src/extension/App.jsx @@ -101,21 +101,30 @@ export default function App() { let alive = true async function start() { try { - const [state, currentPage] = await Promise.all([command('GET_STATE'), captureActivePage().catch(() => null)]) + const captureId = new URLSearchParams(window.location.search).get('capture') + const captureRequest = captureId !== null + ? command('GET_CONTEXT_CAPTURE', { id: captureId }).catch(err => ({ identifier: '', error: err.message })) + : captureActivePage().then(currentPage => ({ + page: currentPage, + source: currentPage ? sourceFromPage(currentPage) : null, + })).catch(() => ({})) + const [state, capture] = await Promise.all([command('GET_STATE'), captureRequest]) if (!alive) return setSettings(state.settings) setLibraryId(state.settings.libraryId) setRecent(state.recent || []) - const source = currentPage ? sourceFromPage(currentPage) : null - setPage(currentPage) + const source = capture.source + setPage(capture.page) setPageSource(source) - if (state.job?.status === 'saving') { + if (capture.error) setError(capture.error) + if (state.job?.status === 'saving' && captureId === null) { setIdentifier(state.job.identifier) setLibraryId(state.job.libraryId) setJob(state.job) } else { - setIdentifier(source?.identifier || '') - if (state.job && (['error', 'uncertain'].includes(state.job.status) || state.job.identifier === source?.identifier)) setJob(state.job) + setIdentifier(capture.identifier ?? source?.identifier ?? '') + if (state.job && (state.job.status === 'saving' || state.job.identifier === (capture.identifier ?? source?.identifier) || + (captureId === null && ['error', 'uncertain'].includes(state.job.status)))) setJob(state.job) } if (state.settings.connected) { try { @@ -183,7 +192,7 @@ export default function App() {

Save to Inbox

Keep a paper, a page, or your next idea.

{pageSource &&
-

{pageSource.reason}

{page?.title || pageSource.identifier}

+

{pageSource.reason}

{page?.title || pageSource.identifier}

}
diff --git a/frontend/src/extension/App.test.jsx b/frontend/src/extension/App.test.jsx index 9c07221..de9aa9b 100644 --- a/frontend/src/extension/App.test.jsx +++ b/frontend/src/extension/App.test.jsx @@ -3,16 +3,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ThemeProvider } from '../context/ThemeContext' import App from './App' import { DEFAULT_SETTINGS } from './core' +import { captureActivePage } from './capture' vi.mock('./capture', () => ({ captureActivePage: vi.fn(async () => ({ url: 'https://example.org/article', title: 'An interesting article' })) })) -let listeners, saved, connected +let listeners, saved, connected, capture const library = { id: 'lib_1', name: 'My Library' } const mount = () => render() beforeEach(() => { connected = true saved = null + capture = { identifier: '10.1000/selected', context: 'selection', page: { title: '10.1000/selected' }, source: { type: 'paper', identifier: '10.1000/selected', reason: 'Selected text', buttonLabel: 'Use this selection' } } listeners = new Set() localStorage.clear() vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })) @@ -23,6 +25,7 @@ beforeEach(() => { runtime: { sendMessage: vi.fn(async message => { if (message.type === 'GET_STATE') return { ok: true, data: { settings: { ...DEFAULT_SETTINGS, connected, libraryId: library.id } } } if (message.type === 'LIBRARIES') return { ok: true, data: [library] } + if (message.type === 'GET_CONTEXT_CAPTURE') return { ok: true, data: capture } if (message.type === 'CONNECT') return { ok: true, data: { settings: { ...DEFAULT_SETTINGS, ...message.settings, connected: true, libraryId: library.id }, libraries: [library] } } if (message.type === 'SAVE') { saved = message @@ -37,6 +40,7 @@ afterEach(() => { vi.restoreAllMocks() document.documentElement.classList.remove('dark') localStorage.clear() + window.history.replaceState({}, '', '/') }) describe('extension popup', () => { @@ -93,9 +97,11 @@ describe('extension popup', () => { expect(screen.getByText(/existing item and its reading status were kept/)).toBeInTheDocument() }) - it('disables saving when the destination library has been deleted', async () => { + it.each([false, true])('disables saving when the library is deleted (context window: %s)', async contextWindow => { + if (contextWindow) window.history.replaceState({}, '', '/popup.html?capture=test-capture') chrome.runtime.sendMessage.mockImplementation(async message => { if (message.type === 'GET_STATE') return { ok: true, data: { settings: { ...DEFAULT_SETTINGS, connected: true, libraryId: 'deleted' } } } + if (message.type === 'GET_CONTEXT_CAPTURE') return { ok: true, data: capture } return { ok: true, data: [library] } }) mount() @@ -104,4 +110,81 @@ describe('extension popup', () => { fireEvent.change(screen.getByLabelText('Save to library'), { target: { value: library.id } }) expect(screen.getByRole('button', { name: 'Save to Inbox' })).toBeEnabled() }) + + it('prefills the right-click target and waits for confirmation before importing', async () => { + window.history.replaceState({}, '', '/popup.html?capture=test-capture') + captureActivePage.mockClear() + mount() + await screen.findByRole('heading', { name: 'Save to Inbox' }) + expect(captureActivePage).not.toHaveBeenCalled() + expect(screen.getByLabelText('DOI, arXiv ID, or URL')).toHaveValue('10.1000/selected') + expect(screen.getByLabelText('Save to library')).toHaveValue(library.id) + expect(screen.getByText('Selected text')).toBeInTheDocument() + expect(saved).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Save to Inbox' })) + await screen.findByText('Saved to Inbox') + expect(saved).toMatchObject({ identifier: '10.1000/selected', libraryId: library.id }) + }) + + it('retains an invalid selection until the user corrects it', async () => { + window.history.replaceState({}, '', '/popup.html?capture=test-capture') + capture = { identifier: 'ordinary prose', source: null, error: 'Edit the input before saving.' } + mount() + await screen.findByRole('heading', { name: 'Save to Inbox' }) + expect(screen.getByLabelText('DOI, arXiv ID, or URL')).toHaveValue('ordinary prose') + expect(screen.getByRole('alert')).toHaveTextContent('Edit the input') + expect(screen.getByRole('button', { name: 'Save to Inbox' })).toBeDisabled() + fireEvent.change(screen.getByLabelText('DOI, arXiv ID, or URL'), { target: { value: '10.1000/corrected' } }) + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Save to Inbox' })).toBeEnabled() + }) + + it('preserves the context target through first-time connection setup', async () => { + window.history.replaceState({}, '', '/popup.html?capture=test-capture') + connected = false + mount() + await screen.findByRole('heading', { name: 'Connect your workspace' }) + fireEvent.click(screen.getByRole('button', { name: 'Connect to ResearchOS' })) + await screen.findByRole('heading', { name: 'Save to Inbox' }) + expect(screen.getByLabelText('DOI, arXiv ID, or URL')).toHaveValue('10.1000/selected') + expect(saved).toBeNull() + }) + + it('reports a missing context capture without substituting the active page', async () => { + window.history.replaceState({}, '', '/popup.html?capture=expired') + const sendMessage = chrome.runtime.sendMessage.getMockImplementation() + chrome.runtime.sendMessage.mockImplementation(message => message.type === 'GET_CONTEXT_CAPTURE' + ? { ok: false, error: 'This capture is no longer available.' } : sendMessage(message)) + mount() + await screen.findByRole('heading', { name: 'Save to Inbox' }) + expect(screen.getByLabelText('DOI, arXiv ID, or URL')).toHaveValue('') + expect(screen.getByRole('alert')).toHaveTextContent('no longer available') + expect(screen.getByRole('button', { name: 'Save to Inbox' })).toBeDisabled() + }) + + it('preserves the target and blocks saving when the backend is unavailable', async () => { + window.history.replaceState({}, '', '/popup.html?capture=test-capture') + const sendMessage = chrome.runtime.sendMessage.getMockImplementation() + chrome.runtime.sendMessage.mockImplementation(message => message.type === 'LIBRARIES' + ? { ok: false, error: 'Could not reach ResearchOS.' } : sendMessage(message)) + mount() + await screen.findByRole('heading', { name: 'Save to Inbox' }) + expect(screen.getByLabelText('DOI, arXiv ID, or URL')).toHaveValue('10.1000/selected') + expect(screen.getByRole('alert')).toHaveTextContent('Could not reach ResearchOS') + expect(screen.getByRole('button', { name: 'Save to Inbox' })).toBeDisabled() + expect(saved).toBeNull() + }) + + it('keeps a new context target while another item finishes saving', async () => { + window.history.replaceState({}, '', '/popup.html?capture=test-capture') + const sendMessage = chrome.runtime.sendMessage.getMockImplementation() + chrome.runtime.sendMessage.mockImplementation(message => message.type === 'GET_STATE' + ? { ok: true, data: { settings: { ...DEFAULT_SETTINGS, connected: true, libraryId: library.id }, job: { status: 'saving', identifier: '10.1000/other', libraryId: library.id } } } + : sendMessage(message)) + mount() + await screen.findByRole('heading', { name: 'Save to Inbox' }) + expect(screen.getByLabelText('DOI, arXiv ID, or URL')).toHaveValue('10.1000/selected') + expect(screen.getByRole('button', { name: 'Saving to Inbox…' })).toBeDisabled() + expect(saved).toBeNull() + }) }) diff --git a/frontend/src/extension/background.js b/frontend/src/extension/background.js index 4a6190a..e23716e 100644 --- a/frontend/src/extension/background.js +++ b/frontend/src/extension/background.js @@ -1,5 +1,8 @@ import { DEFAULT_SETTINGS, importRequest, itemUrl, normalizeBase } from './core' import { requestApi } from './api' +import { getContextCapture, listenForContextMenus } from './contextMenu' + +listenForContextMenus() let activeSave = false @@ -85,6 +88,7 @@ export async function handleMessage(message) { return { ...state, settings: await settings() } } case 'CONNECT': return connect(message.settings) + case 'GET_CONTEXT_CAPTURE': return getContextCapture(message.id) case 'LIBRARIES': return librariesFor(await settings()) case 'SAVE': return saveItem(message) default: throw new Error('Unknown ResearchOS extension command.') diff --git a/frontend/src/extension/background.test.js b/frontend/src/extension/background.test.js index a59377c..a371043 100644 --- a/frontend/src/extension/background.test.js +++ b/frontend/src/extension/background.test.js @@ -14,7 +14,9 @@ async function load() { beforeEach(() => { stored = { settings: { ...DEFAULT_SETTINGS, connected: true, libraryId: library.id } } chromeMock = { - runtime: { id: 'extension-id', getURL: path => `chrome-extension://extension-id/${path}`, onMessage: { addListener: vi.fn() } }, + runtime: { id: 'extension-id', getURL: path => `chrome-extension://extension-id/${path}`, onMessage: { addListener: vi.fn() }, onInstalled: { addListener: vi.fn() } }, + contextMenus: { onClicked: { addListener: vi.fn() } }, + windows: { onRemoved: { addListener: vi.fn() } }, permissions: { contains: vi.fn(async () => true) }, storage: { local: { get: vi.fn(async keys => Object.fromEntries((Array.isArray(keys) ? keys : [keys]).map(key => [key, structuredClone(stored[key])]))), diff --git a/frontend/src/extension/contextMenu.js b/frontend/src/extension/contextMenu.js new file mode 100644 index 0000000..a2a68d9 --- /dev/null +++ b/frontend/src/extension/contextMenu.js @@ -0,0 +1,92 @@ +import { readPageMetadata } from './capture' +import { detectSource, httpUrl, sourceFromPage } from './core' + +export const CONTEXT_MENU_ID = 'researchos-save-to-inbox' +const CAPTURE_PREFIX = 'researchos.contextCapture.' + +export async function registerContextMenu() { + await chrome.contextMenus.removeAll() + await new Promise((resolve, reject) => { + chrome.contextMenus.create({ + id: CONTEXT_MENU_ID, + title: 'Save to ResearchOS', + contexts: ['page', 'link', 'selection'], + documentUrlPatterns: ['http://*/*', 'https://*/*'], + }, () => { + const error = chrome.runtime.lastError + if (error) reject(new Error(error.message)) + else resolve() + }) + }) +} + +export async function captureContextTarget(info, tab) { + // An explicit selection/link must never fall back to its containing page. + const context = info.selectionText?.trim() ? 'selection' : info.linkUrl ? 'link' : 'page' + const raw = context === 'selection' ? info.selectionText.trim() + : context === 'link' ? info.linkUrl : info.frameUrl || info.pageUrl || tab?.url || '' + let page = { url: context === 'selection' ? '' : raw, title: context === 'page' && !info.frameUrl ? tab?.title || raw : raw } + if (context === 'page' && httpUrl(raw) && Number.isInteger(tab?.id)) { + try { + const [injection] = await chrome.scripting.executeScript({ + target: { tabId: tab.id, ...(Number.isInteger(info.frameId) ? { frameIds: [info.frameId] } : {}) }, + func: readPageMetadata, + }) + if (injection?.result) page = { ...page, ...injection.result, selection: '' } + } catch { /* Restricted pages and PDF viewers can still use the original URL. */ } + } + const source = context === 'page' ? sourceFromPage(page) : detectSource(raw) + const reason = { page: 'Current page', link: 'Right-clicked link', selection: 'Selected text' }[context] + return { + context, page, + identifier: source?.identifier || raw, + source: source ? { ...source, reason, buttonLabel: { page: 'Use this page', link: 'Use this link', selection: 'Use this selection' }[context] } : null, + error: source ? '' : 'This capture is not a supported DOI, arXiv ID, or HTTP/HTTPS URL. Edit the input before saving.', + } +} + +export async function openContextCapture(info, tab) { + if (info.menuItemId !== CONTEXT_MENU_ID) return + const capture = await captureContextTarget(info, tab) + const id = crypto.randomUUID() + const key = `${CAPTURE_PREFIX}${id}` + // Session storage keeps targets out of URLs and gives each capture window its + // own input, even if another context-menu action is triggered immediately. + await chrome.storage.session.set({ [key]: capture }) + try { + const window = await chrome.windows.create({ + url: chrome.runtime.getURL(`popup.html?capture=${id}`), + type: 'popup', width: 420, height: 680, focused: true, + }) + await chrome.storage.session.set({ [key]: { ...capture, windowId: window.id } }) + } catch (error) { + await chrome.storage.session.remove(key) + throw error + } +} + +export async function getContextCapture(id) { + if (typeof id !== 'string' || !/^[0-9a-f-]{36}$/i.test(id)) throw new Error('This capture link is invalid. Choose Save to ResearchOS again.') + const key = `${CAPTURE_PREFIX}${id}` + const stored = await chrome.storage.session.get(key) + if (!stored[key]) throw new Error('This capture is no longer available. Choose Save to ResearchOS again.') + return stored[key] +} + +export async function clearContextCapture(windowId) { + const stored = await chrome.storage.session.get(null) + const keys = Object.keys(stored).filter(key => key.startsWith(CAPTURE_PREFIX) && stored[key].windowId === windowId) + if (keys.length) await chrome.storage.session.remove(keys) +} + +export function listenForContextMenus() { + chrome.runtime.onInstalled.addListener(() => { + registerContextMenu().catch(error => console.error('Could not register ResearchOS context menu:', error.message)) + }) + chrome.contextMenus.onClicked.addListener((info, tab) => { + openContextCapture(info, tab).catch(error => console.error('Could not open ResearchOS capture:', error.message)) + }) + chrome.windows.onRemoved.addListener(windowId => { + clearContextCapture(windowId).catch(error => console.error('Could not clear ResearchOS capture:', error.message)) + }) +} diff --git a/frontend/src/extension/contextMenu.test.js b/frontend/src/extension/contextMenu.test.js new file mode 100644 index 0000000..c161925 --- /dev/null +++ b/frontend/src/extension/contextMenu.test.js @@ -0,0 +1,127 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + CONTEXT_MENU_ID, captureContextTarget, clearContextCapture, getContextCapture, + listenForContextMenus, openContextCapture, registerContextMenu, +} from './contextMenu' + +let session +const containingPage = { id: 7, url: 'https://example.org/reading-list', title: 'Reading list' } + +beforeEach(() => { + session = {} + vi.stubGlobal('chrome', { + runtime: { getURL: path => `chrome-extension://researchos/${path}`, onInstalled: { addListener: vi.fn() } }, + contextMenus: { + removeAll: vi.fn(async () => {}), + create: vi.fn((_entry, callback) => { callback() }), + onClicked: { addListener: vi.fn() }, + }, + scripting: { executeScript: vi.fn(async () => [{ result: { url: containingPage.url, title: 'Article', doi: '10.1000/article' } }]) }, + windows: { create: vi.fn(async () => ({ id: 12 })), onRemoved: { addListener: vi.fn() } }, + storage: { session: { + get: vi.fn(async key => key === null ? { ...session } : { [key]: session[key] }), + set: vi.fn(async values => { Object.assign(session, values) }), + remove: vi.fn(async keys => { for (const key of Array.isArray(keys) ? keys : [keys]) delete session[key] }), + } }, + }) +}) +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() }) + +describe('context-menu registration', () => { + it('replaces menu entries on install/update and registers all capture contexts', async () => { + await registerContextMenu() + await registerContextMenu() + expect(chrome.contextMenus.removeAll).toHaveBeenCalledTimes(2) + expect(chrome.contextMenus.create).toHaveBeenLastCalledWith(expect.objectContaining({ + id: CONTEXT_MENU_ID, title: 'Save to ResearchOS', contexts: ['page', 'link', 'selection'], + documentUrlPatterns: ['http://*/*', 'https://*/*'], + }), expect.any(Function)) + expect(chrome.contextMenus.removeAll.mock.invocationCallOrder[1]).toBeLessThan(chrome.contextMenus.create.mock.invocationCallOrder[1]) + }) + + it('registers installation, click, and window cleanup listeners', async () => { + listenForContextMenus() + expect(chrome.runtime.onInstalled.addListener).toHaveBeenCalledOnce() + expect(chrome.contextMenus.onClicked.addListener).toHaveBeenCalledOnce() + expect(chrome.windows.onRemoved.addListener).toHaveBeenCalledOnce() + const onClicked = chrome.contextMenus.onClicked.addListener.mock.calls[0][0] + onClicked({ menuItemId: CONTEXT_MENU_ID, linkUrl: 'https://github.com/owner/repo' }, containingPage) + await vi.waitFor(() => expect(chrome.windows.create).toHaveBeenCalledOnce()) + expect(Object.values(session)[0].identifier).toBe('https://github.com/owner/repo') + }) + + it('reports registration errors instead of leaving them in an unchecked callback', async () => { + chrome.runtime.lastError = { message: 'Registration failed' } + await expect(registerContextMenu()).rejects.toThrow('Registration failed') + }) +}) + +describe('context-menu targets', () => { + it('captures the clicked page scholarly metadata', async () => { + const capture = await captureContextTarget({ pageUrl: containingPage.url, frameId: 0 }, containingPage) + expect(capture).toMatchObject({ context: 'page', identifier: '10.1000/article', source: { type: 'paper' } }) + expect(chrome.scripting.executeScript).toHaveBeenCalledWith(expect.objectContaining({ target: { tabId: 7, frameIds: [0] } })) + }) + + it('uses the clicked link rather than metadata from its containing page', async () => { + const capture = await captureContextTarget({ linkUrl: 'https://github.com/owner/repo/tree/main', pageUrl: containingPage.url }, containingPage) + expect(capture).toMatchObject({ context: 'link', identifier: 'https://github.com/owner/repo', source: { type: 'github', reason: 'Right-clicked link' } }) + expect(capture.page.title).not.toBe(containingPage.title) + expect(chrome.scripting.executeScript).not.toHaveBeenCalled() + }) + + it('uses selected identifiers, including when they are selected inside a link', async () => { + const capture = await captureContextTarget({ selectionText: ' DOI: 10.1000/selected ', linkUrl: 'https://example.org/other', pageUrl: containingPage.url }, containingPage) + expect(capture).toMatchObject({ context: 'selection', identifier: '10.1000/selected', source: { type: 'paper' } }) + expect(chrome.scripting.executeScript).not.toHaveBeenCalled() + }) + + it('keeps an invalid selection editable instead of silently substituting the page', async () => { + const capture = await captureContextTarget({ selectionText: 'ordinary prose', pageUrl: containingPage.url }, containingPage) + expect(capture).toMatchObject({ identifier: 'ordinary prose', source: null, error: expect.stringContaining('Edit the input') }) + expect(chrome.scripting.executeScript).not.toHaveBeenCalled() + }) + + it('uses a frame URL and metadata from that frame for a page click inside an iframe', async () => { + await captureContextTarget({ pageUrl: containingPage.url, frameUrl: 'https://publisher.org/article', frameId: 3 }, containingPage) + expect(chrome.scripting.executeScript).toHaveBeenCalledWith(expect.objectContaining({ target: { tabId: 7, frameIds: [3] } })) + }) + + it('falls back to the original PDF URL when script injection is blocked', async () => { + chrome.scripting.executeScript.mockRejectedValue(new Error('Cannot access viewer')) + expect(await captureContextTarget({ pageUrl: 'https://example.org/paper.pdf' }, containingPage)).toMatchObject({ identifier: 'https://example.org/paper.pdf', source: { type: 'paper' } }) + }) +}) + +describe('capture-window transport', () => { + it('isolates captures and keeps raw targets out of window URLs', async () => { + await openContextCapture({ menuItemId: CONTEXT_MENU_ID, selectionText: '10.1000/first' }, containingPage) + await openContextCapture({ menuItemId: CONTEXT_MENU_ID, linkUrl: 'https://example.org/second' }, containingPage) + const urls = chrome.windows.create.mock.calls.map(([options]) => options.url) + const ids = urls.map(url => new URL(url).searchParams.get('capture')) + expect(ids[0]).not.toBe(ids[1]) + expect(urls[0]).not.toContain('10.1000') + expect(await getContextCapture(ids[0])).toMatchObject({ identifier: '10.1000/first' }) + expect(await getContextCapture(ids[1])).toMatchObject({ identifier: 'https://example.org/second' }) + }) + + it('clears a closed capture window without deleting unrelated session data', async () => { + await openContextCapture({ menuItemId: CONTEXT_MENU_ID, selectionText: '10.1000/first' }, containingPage) + session.unrelated = { windowId: 12 } + await clearContextCapture(12) + expect(session).toEqual({ unrelated: { windowId: 12 } }) + }) + + it('cleans up when Chrome cannot open the capture window', async () => { + chrome.windows.create.mockRejectedValue(new Error('Window unavailable')) + await expect(openContextCapture({ menuItemId: CONTEXT_MENU_ID, selectionText: '10.1000/first' }, containingPage)).rejects.toThrow('Window unavailable') + expect(session).toEqual({}) + }) + + it('rejects missing captures and ignores clicks on other menu items', async () => { + await expect(getContextCapture('invalid')).rejects.toThrow('invalid') + await expect(getContextCapture(crypto.randomUUID())).rejects.toThrow('no longer available') + await openContextCapture({ menuItemId: 'another-extension-menu', pageUrl: containingPage.url }, containingPage) + expect(chrome.windows.create).not.toHaveBeenCalled() + }) +})