From a47a2d08b78af7a267b4247349633bf57211027f Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Sat, 28 Nov 2026 20:28:49 -0500 Subject: [PATCH 1/8] fix(imports): scope website and GitHub duplicates to each library Pass the destination library through URL duplicate lookups and replace the global GitHub URL index with per-library uniqueness. Preserve duplicate protection for legacy unscoped rows and cover migration replay and import routing. --- .../038_library_scoped_github_urls.sql | 15 ++++++++ backend/migrations/schema.sql | 4 +- backend/routers/github_repos.py | 2 +- backend/routers/websites.py | 2 +- backend/services/github_repo_service.py | 7 +++- backend/services/website_service.py | 7 +++- backend/tests/run_import_scope_sql.mjs | 35 +++++++++++++++++ backend/tests/test_import_library_scope.py | 38 +++++++++++++++++++ 8 files changed, 103 insertions(+), 7 deletions(-) create mode 100644 backend/migrations/038_library_scoped_github_urls.sql create mode 100644 backend/tests/run_import_scope_sql.mjs create mode 100644 backend/tests/test_import_library_scope.py diff --git a/backend/migrations/038_library_scoped_github_urls.sql b/backend/migrations/038_library_scoped_github_urls.sql new file mode 100644 index 0000000..2166013 --- /dev/null +++ b/backend/migrations/038_library_scoped_github_urls.sql @@ -0,0 +1,15 @@ +-- A repository can belong to more than one library. Keep duplicate prevention +-- inside each library, including legacy rows without a library assignment. +BEGIN; + +DROP INDEX IF EXISTS public.idx_github_repos_url; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repos_library_url + ON public.github_repos (library_id, url) + WHERE library_id IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repos_unscoped_url + ON public.github_repos (url) + WHERE library_id IS NULL; + +COMMIT; diff --git a/backend/migrations/schema.sql b/backend/migrations/schema.sql index 30b0e09..e7294f3 100644 --- a/backend/migrations/schema.sql +++ b/backend/migrations/schema.sql @@ -117,7 +117,9 @@ CREATE TABLE IF NOT EXISTS github_repos ( item_type TEXT NOT NULL DEFAULT 'github_repo' ); -CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repos_url ON github_repos (url); +DROP INDEX IF EXISTS idx_github_repos_url; +CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repos_library_url ON github_repos (library_id, url) WHERE library_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repos_unscoped_url ON github_repos (url) WHERE library_id IS NULL; CREATE INDEX IF NOT EXISTS idx_github_repos_library ON github_repos (library_id); CREATE INDEX IF NOT EXISTS idx_github_repos_status ON github_repos (status); CREATE INDEX IF NOT EXISTS idx_github_repos_published ON github_repos (published_date); diff --git a/backend/routers/github_repos.py b/backend/routers/github_repos.py index f24d3cc..3f31b1b 100644 --- a/backend/routers/github_repos.py +++ b/backend/routers/github_repos.py @@ -73,7 +73,7 @@ async def import_github_repo(data: GitHubRepoImportRequest): raise HTTPException(status_code=422, detail="Could not parse GitHub repository URL") canonical_url = f"https://github.com/{m.group(1)}/{m.group(2)}" - existing = github_repo_service.get_github_repo_by_url(canonical_url) + existing = github_repo_service.get_github_repo_by_url(canonical_url, library_id=data.library_id) if existing: return JSONResponse( {**existing.model_dump(by_alias=True), "already_exists": True}, diff --git a/backend/routers/websites.py b/backend/routers/websites.py index e3f4145..c34edc9 100644 --- a/backend/routers/websites.py +++ b/backend/routers/websites.py @@ -67,7 +67,7 @@ async def import_website(data: WebsiteImportRequest): raise HTTPException(status_code=422, detail="url must start with http:// or https://") # Deduplicate by URL - existing = website_service.get_website_by_url(url) + existing = website_service.get_website_by_url(url, library_id=data.library_id) if existing: return JSONResponse( {**existing.model_dump(by_alias=True), "already_exists": True}, diff --git a/backend/services/github_repo_service.py b/backend/services/github_repo_service.py index 683bd7e..da71ca0 100644 --- a/backend/services/github_repo_service.py +++ b/backend/services/github_repo_service.py @@ -39,8 +39,11 @@ def get_github_repo(repo_id: str) -> Optional[GitHubRepo]: return GitHubRepo.model_validate(result.data[0]) -def get_github_repo_by_url(url: str) -> Optional[GitHubRepo]: - result = get_client().table(_TABLE).select("*").eq("url", url).execute() +def get_github_repo_by_url(url: str, library_id: Optional[str] = None) -> Optional[GitHubRepo]: + query = get_client().table(_TABLE).select("*").eq("url", url) + if library_id: + query = query.eq("library_id", library_id) + result = query.execute() if not result.data: return None return GitHubRepo.model_validate(result.data[0]) diff --git a/backend/services/website_service.py b/backend/services/website_service.py index 341ec7b..09e3c3d 100644 --- a/backend/services/website_service.py +++ b/backend/services/website_service.py @@ -38,8 +38,11 @@ def get_website(website_id: str) -> Optional[Website]: return Website.model_validate(result.data[0]) -def get_website_by_url(url: str) -> Optional[Website]: - result = get_client().table(_TABLE).select("*").eq("url", url).execute() +def get_website_by_url(url: str, library_id: Optional[str] = None) -> Optional[Website]: + query = get_client().table(_TABLE).select("*").eq("url", url) + if library_id: + query = query.eq("library_id", library_id) + result = query.execute() if not result.data: return None return Website.model_validate(result.data[0]) diff --git a/backend/tests/run_import_scope_sql.mjs b/backend/tests/run_import_scope_sql.mjs new file mode 100644 index 0000000..200d580 --- /dev/null +++ b/backend/tests/run_import_scope_sql.mjs @@ -0,0 +1,35 @@ +// Uses the same disposable PostgreSQL engine as run_citation_sql.mjs. +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { PGlite } from '../data/citation-validation/node_modules/@electric-sql/pglite/dist/index.js' + +const db = new PGlite() +try { + const schema = await readFile(new URL('../migrations/schema.sql', import.meta.url), 'utf8') + const start = schema.indexOf('CREATE TABLE IF NOT EXISTS github_repos') + const end = schema.indexOf('ALTER TABLE github_repos DISABLE ROW LEVEL SECURITY;') + await db.exec(schema.slice(start, end)) + // Simulate the old production index before applying the upgrade. + await db.exec(` + DROP INDEX idx_github_repos_library_url; + DROP INDEX idx_github_repos_unscoped_url; + CREATE UNIQUE INDEX idx_github_repos_url ON github_repos(url); + `) + const insert = (id, library) => db.query(` + INSERT INTO github_repos(id, title, url, owner, repo_name, library_id, created_at) + VALUES ($1, 'Test repo', 'https://github.com/owner/repo', 'owner', 'repo', $2, '2026-11-26') + `, [id, library]) + await insert('original', 'lib_1') + const migration = await readFile(new URL('../migrations/038_library_scoped_github_urls.sql', import.meta.url), 'utf8') + await db.exec(migration) + await db.exec(migration) + await insert('second-library', 'lib_2') + await insert('legacy-unscoped', null) + await assert.rejects(insert('same-library-duplicate', 'lib_1'), error => error.code === '23505') + await assert.rejects(insert('unscoped-duplicate', null), error => error.code === '23505') + assert.equal((await db.query('SELECT count(*)::int AS count FROM github_repos')).rows[0].count, 3) + assert.equal((await db.query("SELECT count(*)::int AS count FROM pg_indexes WHERE indexname = 'idx_github_repos_url'")).rows[0].count, 0) + console.log('Import SQL checks passed: independent libraries, duplicate protection, legacy rows, and migration replay.') +} finally { + await db.close() +} diff --git a/backend/tests/test_import_library_scope.py b/backend/tests/test_import_library_scope.py new file mode 100644 index 0000000..a8b7cff --- /dev/null +++ b/backend/tests/test_import_library_scope.py @@ -0,0 +1,38 @@ +from types import SimpleNamespace + +import pytest + +from conftest import DummyModel + + +@pytest.mark.parametrize("service_name,method", [ + ("website_service", "get_website_by_url"), + ("github_repo_service", "get_github_repo_by_url"), +]) +def test_url_lookup_scopes_duplicates_to_library(mocker, service_name, method): + from services import github_repo_service, website_service + + service = {"website_service": website_service, "github_repo_service": github_repo_service}[service_name] + query = mocker.Mock() + query.select.return_value = query + query.eq.return_value = query + query.execute.return_value = SimpleNamespace(data=[]) + mocker.patch.object(service, "get_client").return_value.table.return_value = query + + assert getattr(service, method)("https://example.org/item", library_id="lib_target") is None + assert query.eq.call_args_list == [mocker.call("url", "https://example.org/item"), mocker.call("library_id", "lib_target")] + + +@pytest.mark.parametrize("endpoint,service_name,method,url,canonical", [ + ("websites", "website_service", "get_website_by_url", "https://example.org", "https://example.org"), + ("github-repos", "github_repo_service", "get_github_repo_by_url", "https://github.com/owner/repo/tree/main", "https://github.com/owner/repo"), +]) +def test_import_duplicate_check_passes_destination_library(client, mocker, endpoint, service_name, method, url, canonical): + lookup = mocker.patch(f"services.{service_name}.{method}", return_value=DummyModel({"id": "existing", "title": "Existing item", "status": "read"})) + + response = client.post(f"/api/{endpoint}/import", json={"url": url, "library_id": "lib_target"}) + + lookup.assert_called_once_with(canonical, library_id="lib_target") + assert response.status_code == 200 + assert response.json()["already_exists"] is True + assert response.json()["status"] == "read" From 7dc36bdc86d8a0b315c42f31b4794c170b9b25ba Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Sat, 28 Nov 2026 20:29:05 -0500 Subject: [PATCH 2/8] feat(extension): detect paper identifiers and capture page metadata Recognize DOI, arXiv, OpenReview, Zenodo, PDF, website, and GitHub sources. Read explicit scholarly metadata or selected identifiers from the active tab, validate URLs, and construct existing ResearchOS import requests. Cover detection and restricted-page fallbacks. --- frontend/src/extension/capture.js | 28 ++++++ frontend/src/extension/capture.test.js | 29 +++++++ frontend/src/extension/core.js | 116 +++++++++++++++++++++++++ frontend/src/extension/core.test.js | 73 ++++++++++++++++ 4 files changed, 246 insertions(+) create mode 100644 frontend/src/extension/capture.js create mode 100644 frontend/src/extension/capture.test.js create mode 100644 frontend/src/extension/core.js create mode 100644 frontend/src/extension/core.test.js diff --git a/frontend/src/extension/capture.js b/frontend/src/extension/capture.js new file mode 100644 index 0000000..1a49e7a --- /dev/null +++ b/frontend/src/extension/capture.js @@ -0,0 +1,28 @@ +// Runs once in the active tab's isolated world after the toolbar is clicked. +// Keep this function self-contained: Chrome serializes it for executeScript. +export function readPageMetadata() { + const metas = [...document.querySelectorAll('meta[name], meta[property]')] + const first = (...names) => metas.find(meta => names.includes((meta.name || meta.getAttribute('property') || '').toLowerCase()))?.content?.trim() || '' + return { + url: location.href, + title: first('citation_title', 'og:title') || document.title, + doi: first('citation_doi', 'dc.identifier.doi', 'dc.identifier', 'prism.doi'), + arxivId: first('citation_arxiv_id'), + paperUrl: first('citation_pdf_url', 'citation_abstract_html_url'), + selection: window.getSelection()?.toString().trim().slice(0, 2048) || '', + } +} + +export async function captureActivePage() { + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }) + if (!tab) return { url: '', title: '' } + const fallback = { url: tab.url || '', title: tab.title || '' } + if (!/^https?:\/\//i.test(fallback.url)) return fallback + try { + const [injection] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: readPageMetadata }) + return injection?.result || fallback + } catch { + // Chrome's PDF viewer and restricted sites still permit a pasted identifier. + return fallback + } +} diff --git a/frontend/src/extension/capture.test.js b/frontend/src/extension/capture.test.js new file mode 100644 index 0000000..af1a43f --- /dev/null +++ b/frontend/src/extension/capture.test.js @@ -0,0 +1,29 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { captureActivePage, readPageMetadata } from './capture' + +afterEach(() => { document.head.innerHTML = ''; vi.unstubAllGlobals(); vi.restoreAllMocks() }) + +describe('active page capture', () => { + it('reads explicit scholarly metadata without scraping unrelated citation text', () => { + document.head.innerHTML = 'Publisher title' + expect(readPageMetadata()).toMatchObject({ title: 'Paper title', doi: '10.1000/article' }) + expect(readPageMetadata()).not.toHaveProperty('description') + }) + + it('falls back to a PDF tab URL when Chrome disallows script injection', async () => { + vi.stubGlobal('chrome', { + tabs: { query: vi.fn(async () => [{ id: 1, url: 'https://example.org/paper.pdf', title: 'A PDF' }]) }, + scripting: { executeScript: vi.fn(async () => { throw new Error('Cannot access this page') }) }, + }) + expect(await captureActivePage()).toEqual({ url: 'https://example.org/paper.pdf', title: 'A PDF' }) + }) + + it('never injects a script into browser-internal pages', async () => { + vi.stubGlobal('chrome', { + tabs: { query: vi.fn(async () => [{ id: 1, url: 'chrome://extensions', title: 'Extensions' }]) }, + scripting: { executeScript: vi.fn() }, + }) + expect(await captureActivePage()).toEqual({ url: 'chrome://extensions', title: 'Extensions' }) + expect(chrome.scripting.executeScript).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/extension/core.js b/frontend/src/extension/core.js new file mode 100644 index 0000000..7551b71 --- /dev/null +++ b/frontend/src/extension/core.js @@ -0,0 +1,116 @@ +export const DEFAULT_SETTINGS = { + backendUrl: 'http://localhost:8000', + frontendUrl: 'http://localhost:5173', + libraryId: '', + connected: false, +} + +export const TYPE_META = { + paper: { label: 'Paper', icon: 'paper', color: 'text-blue-600', bg: 'bg-blue-50' }, + website: { label: 'Website', icon: 'globe', color: 'text-teal-600', bg: 'bg-teal-50' }, + github: { label: 'GitHub', icon: 'github', color: 'text-violet-600', bg: 'bg-violet-50' }, +} + +export function httpUrl(raw) { + try { + const url = new URL(raw) + return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? url : null + } catch { return null } +} + +export function normalizeBase(raw) { + const url = httpUrl(raw.trim()) + if (!url || url.search || url.hash) throw new Error('Enter an http:// or https:// address without a query, fragment, or embedded credentials.') + return url.href.replace(/\/+$/, '') +} + +export function permissionOrigin(raw) { + const url = httpUrl(raw) + if (!url) throw new Error('Enter a valid ResearchOS server address.') + // Chrome match patterns do not accept ports; the configured fetch URL keeps it. + return `${url.protocol}//${url.hostname}/*` +} + +export function extractDoi(raw = '') { + const value = raw.trim().replace(/^doi:\s*/i, '') + const url = httpUrl(value) + if (url && /^(?:dx\.)?doi\.org$/i.test(url.hostname)) { + try { return decodeURIComponent(url.pathname.slice(1)) } catch { return url.pathname.slice(1) } + } + return /^10\.\d{4,9}\/\S+$/i.test(value) ? value : null +} + +export function detectSource(raw) { + const value = raw.trim() + const doi = extractDoi(value) + if (doi) return { type: 'paper', identifier: doi, label: 'DOI detected' } + const arxiv = value.replace(/^arxiv:\s*/i, '') + if (/^(?:\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?\/\d{7})(?:v\d+)?$/i.test(arxiv)) { + // Legacy arXiv identifiers are supported through their abstract URL. + return { type: 'paper', identifier: arxiv.includes('/') ? `https://arxiv.org/abs/${arxiv}` : arxiv, label: 'arXiv detected' } + } + const url = httpUrl(value) + if (!url) return null + const host = url.hostname.toLowerCase().replace(/^www\./, '') + if (host === 'github.com' && /^\/[^/]+\/[^/]+/.test(url.pathname)) { + const [owner, repo] = url.pathname.slice(1).split('/') + return { type: 'github', identifier: `https://github.com/${owner}/${repo.replace(/\.git$/, '')}`, label: 'Repository detected' } + } + if ((host === 'arxiv.org' && /^\/(abs|pdf|html)\//.test(url.pathname)) || + (host === 'openreview.net' && /^\/(forum|pdf)$/.test(url.pathname) && url.searchParams.has('id')) || + (host === 'zenodo.org' && /^\/records?\/\d+/.test(url.pathname)) || + /\.pdf$/i.test(url.pathname) || /\/10\.\d{4,9}\//.test(url.pathname)) { + // The backend accepts abs/pdf URLs; normalize arXiv's HTML reader too. + if (host === 'arxiv.org') url.pathname = url.pathname.replace(/^\/html\//, '/abs/') + return { type: 'paper', identifier: url.href, label: 'Paper detected' } + } + return { type: 'website', identifier: value, label: 'Website detected' } +} + +export function sourceFromPage(page) { + const selected = page.selection?.trim() + if (selected && selected.length < 2048) { + const source = detectSource(selected) + if (source) return { ...source, reason: 'From your selection' } + } + const direct = detectSource(page.url || '') + if (direct?.type === 'github') return { ...direct, reason: 'Current repository' } + // Only explicit scholarly metadata is considered, never arbitrary DOIs in body text. + const doi = extractDoi(page.doi || '') + if (doi) return { type: 'paper', identifier: doi, label: 'DOI detected', reason: 'From page metadata' } + if (page.arxivId) { + const source = detectSource(page.arxivId) + if (source?.type === 'paper') return { ...source, reason: 'From page metadata' } + } + if (page.paperUrl && httpUrl(page.paperUrl)) return { type: 'paper', identifier: page.paperUrl, label: 'Paper detected', reason: 'From page metadata' } + return direct ? { ...direct, reason: 'Current page' } : null +} + +export function importRequest(raw, mode, libraryId) { + const detected = detectSource(raw) + if (!detected) throw new Error('Enter a DOI, arXiv ID, or a full http:// or https:// URL.') + const type = mode === 'auto' ? detected.type : mode + if (!TYPE_META[type]) throw new Error('Choose a supported item type.') + const value = raw.trim() + if (type !== 'paper' && !httpUrl(value)) throw new Error('Websites and repositories need a full http:// or https:// URL.') + if (type === 'github' && detected.type !== 'github') throw new Error('Enter a GitHub repository URL, including its owner and repository name.') + if (!libraryId) throw new Error('Choose a destination library before saving.') + const identifier = type === 'paper' && detected.type === 'paper' ? detected.identifier : value + return { + type, + path: `/api/${{ paper: 'papers', website: 'websites', github: 'github-repos' }[type]}/import`, + body: { [type === 'paper' ? 'identifier' : 'url']: type === 'github' ? detected.identifier : identifier, library_id: libraryId }, + } +} + +export function itemUrl(frontendUrl, type, id) { + const segment = { paper: 'paper', website: 'website', github: 'github-repo' }[type] + return `${normalizeBase(frontendUrl)}/library/${segment}/${encodeURIComponent(id)}` +} + +export function apiError(payload, status) { + const detail = payload?.detail || payload?.error + if (typeof detail === 'string') return detail + if (Array.isArray(detail)) return detail.map(entry => entry.msg).filter(Boolean).join('; ') || `HTTP ${status}` + return detail?.detail || `ResearchOS returned HTTP ${status}.` +} diff --git a/frontend/src/extension/core.test.js b/frontend/src/extension/core.test.js new file mode 100644 index 0000000..5387aeb --- /dev/null +++ b/frontend/src/extension/core.test.js @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest' +import { apiError, detectSource, extractDoi, importRequest, itemUrl, normalizeBase, permissionOrigin, sourceFromPage } from './core' + +describe('extension source detection', () => { + it.each([ + ['10.1038/s41586-024-07487-w', 'paper'], + ['DOI: 10.1000/test', 'paper'], + ['https://doi.org/10.1000/test', 'paper'], + ['2303.01234v2', 'paper'], + ['arXiv:2303.01234', 'paper'], + ['https://arxiv.org/html/2303.01234v2', 'paper'], + ['https://openreview.net/forum?id=abc', 'paper'], + ['https://zenodo.org/records/123456', 'paper'], + ['https://example.org/paper.pdf?download=1', 'paper'], + ['https://publisher.org/doi/10.1000/abc', 'paper'], + ['https://github.com/owner/repo/tree/main', 'github'], + ['https://example.org/article', 'website'], + ['https://github.com/owner', 'website'], + ['https://github.com.evil.test/owner/repo', 'website'], + ['chrome://extensions', undefined], + ['file:///private/paper.pdf', undefined], + ['javascript:alert(1)', undefined], + ['https://user:password@example.org', undefined], + ])('classifies %s as %s', (value, type) => { + expect(detectSource(value)?.type).toBe(type) + }) + + it('preserves DOI suffixes and normalizes repository and HTML reader URLs', () => { + expect(extractDoi('https://doi.org/10.1000%2Ffoo(1)?utm_source=test')).toBe('10.1000/foo(1)') + expect(detectSource('https://github.com/owner/repo.git/issues/1').identifier).toBe('https://github.com/owner/repo') + expect(detectSource('https://arxiv.org/html/2303.01234v2').identifier).toBe('https://arxiv.org/abs/2303.01234v2') + }) + + it('prefers an explicit selection, then scholarly metadata, then the page URL', () => { + const page = { url: 'https://publisher.test/article', doi: '10.1000/article', selection: '10.1000/selected' } + expect(sourceFromPage(page).identifier).toBe('10.1000/selected') + expect(sourceFromPage({ ...page, selection: 'ordinary selected text' }).identifier).toBe('10.1000/article') + expect(sourceFromPage({ url: page.url }).type).toBe('website') + expect(sourceFromPage({ url: 'chrome://newtab' })).toBeNull() + expect(sourceFromPage({ url: page.url, paperUrl: 'javascript:alert(1)' }).type).toBe('website') + }) + + it('keeps GitHub repositories as repos when CITATION metadata includes a DOI', () => { + expect(sourceFromPage({ url: 'https://github.com/owner/repo', doi: '10.1000/software' }).type).toBe('github') + }) +}) + +describe('extension API contracts', () => { + it('uses existing import endpoints and always passes a library ID', () => { + expect(importRequest('doi:10.1000/paper', 'auto', 'lib_1')).toEqual({ type: 'paper', path: '/api/papers/import', body: { identifier: '10.1000/paper', library_id: 'lib_1' } }) + expect(importRequest('https://example.org', 'auto', 'lib_2')).toMatchObject({ path: '/api/websites/import', body: { url: 'https://example.org', library_id: 'lib_2' } }) + expect(importRequest('https://github.com/owner/repo/issues', 'auto', 'lib_2')).toMatchObject({ path: '/api/github-repos/import', body: { url: 'https://github.com/owner/repo', library_id: 'lib_2' } }) + expect(importRequest('https://publisher.org/article', 'paper', 'lib_2').path).toBe('/api/papers/import') + expect(importRequest('https://arxiv.org/abs/2303.01234', 'website', 'lib_2').path).toBe('/api/websites/import') + expect(() => importRequest('10.1000/paper', 'auto', '')).toThrow('destination library') + expect(() => importRequest('10.1000/paper', 'website', 'lib_1')).toThrow('full http') + expect(() => importRequest('https://example.org', 'github', 'lib_1')).toThrow('GitHub repository') + }) + + it('validates server URLs and constructs host permissions without port numbers', () => { + expect(normalizeBase(' http://localhost:8000/ ')).toBe('http://localhost:8000') + expect(permissionOrigin('http://localhost:8000')).toBe('http://localhost/*') + expect(permissionOrigin('https://example.org/research')).toBe('https://example.org/*') + for (const invalid of ['file:///tmp', 'https://user:secret@example.org', 'https://example.org?token=secret', 'https://example.org/#fragment']) expect(() => normalizeBase(invalid)).toThrow() + expect(itemUrl('https://example.org/app/', 'github', 'repo/123')).toBe('https://example.org/app/library/github-repo/repo%2F123') + }) + + it('makes FastAPI validation and server errors readable', () => { + expect(apiError({ detail: [{ msg: 'Invalid URL' }] }, 422)).toBe('Invalid URL') + expect(apiError({ detail: 'Rate limited' }, 429)).toBe('Rate limited') + expect(apiError({}, 500)).toContain('500') + }) +}) From 870fcebad7b310c97c9a354e435fcd8023b28fba Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Sat, 28 Nov 2026 20:29:09 -0500 Subject: [PATCH 3/8] feat(extension): persist Inbox imports in a background worker Connect to a user-selected backend, validate destination libraries, and save through existing import endpoints. Persist results and recent captures, reject concurrent writes, and recover interrupted saves without replaying them. Keep import feedback in the popup and clear legacy toolbar badges. --- frontend/src/extension/api.js | 30 +++++++ frontend/src/extension/background.js | 99 +++++++++++++++++++++ frontend/src/extension/background.test.js | 101 ++++++++++++++++++++++ 3 files changed, 230 insertions(+) create mode 100644 frontend/src/extension/api.js create mode 100644 frontend/src/extension/background.js create mode 100644 frontend/src/extension/background.test.js diff --git a/frontend/src/extension/api.js b/frontend/src/extension/api.js new file mode 100644 index 0000000..21c71a0 --- /dev/null +++ b/frontend/src/extension/api.js @@ -0,0 +1,30 @@ +import { apiError, permissionOrigin } from './core' + +export async function requestApi(settings, path, body) { + const allowed = await chrome.permissions.contains({ origins: [permissionOrigin(settings.backendUrl)] }) + if (!allowed) throw new Error('Server access is missing. Open connection settings and reconnect to ResearchOS.') + let response + try { + response = await fetch(`${settings.backendUrl}${path}`, { + method: body ? 'POST' : 'GET', + headers: body ? { 'Content-Type': 'application/json' } : {}, + body: body ? JSON.stringify(body) : undefined, + credentials: 'omit', + redirect: 'error', + // Finish before Chrome's 30-second service-worker fetch limit. + signal: AbortSignal.timeout(25000), + }) + } catch (error) { + const uncertain = Boolean(body) + const message = uncertain + ? 'The server did not confirm this save. Check your Inbox before trying again; the import may have completed.' + : 'Could not reach ResearchOS. Check the server address and make sure the backend is running.' + throw Object.assign(new Error(message), { uncertain, cause: error }) + } + let data + try { data = await response.json() } catch { + throw Object.assign(new Error('The server returned an unreadable response. Check the backend address.'), { uncertain: Boolean(body) }) + } + if (!response.ok) throw Object.assign(new Error(apiError(data, response.status)), { uncertain: Boolean(body) && response.status >= 500 }) + return data +} diff --git a/frontend/src/extension/background.js b/frontend/src/extension/background.js new file mode 100644 index 0000000..4a6190a --- /dev/null +++ b/frontend/src/extension/background.js @@ -0,0 +1,99 @@ +import { DEFAULT_SETTINGS, importRequest, itemUrl, normalizeBase } from './core' +import { requestApi } from './api' + +let activeSave = false + +// A terminated worker cannot know whether a POST committed. Never replay it. +const ready = chrome.storage.local.get('job').then(async ({ job }) => { + // Clear badges left behind by earlier extension versions. Save feedback lives + // in the popup, where it can be understood alongside the captured item. + await chrome.action.setBadgeText({ text: '' }) + if (job?.status === 'saving') { + await chrome.storage.local.set({ job: { ...job, status: 'uncertain', error: 'The previous save was interrupted. Check your Inbox before trying again.' } }) + } +}) + +async function settings() { + const stored = await chrome.storage.local.get('settings') + return { ...DEFAULT_SETTINGS, ...stored.settings } +} + +async function librariesFor(config) { + const libraries = await requestApi(config, '/api/libraries') + if (!Array.isArray(libraries) || libraries.some(lib => typeof lib.id !== 'string' || typeof lib.name !== 'string')) { + throw new Error('This address is not a compatible ResearchOS API. Use the backend address, usually http://localhost:8000.') + } + return libraries +} + +async function connect(input) { + if (activeSave) throw new Error('Wait for the current save to finish before changing connections.') + const previous = await settings() + const backendUrl = normalizeBase(input.backendUrl).replace(/\/api$/, '') + const config = { ...DEFAULT_SETTINGS, backendUrl, frontendUrl: normalizeBase(input.frontendUrl), connected: true } + const libraries = await librariesFor(config) + if (!libraries.length) throw new Error('Create a library in ResearchOS first, then reconnect.') + config.libraryId = backendUrl === previous.backendUrl && libraries.some(lib => lib.id === previous.libraryId) ? previous.libraryId : libraries[0].id + await chrome.storage.local.set({ settings: config }) + // History belongs to one server and is never carried into a different database. + if (backendUrl !== previous.backendUrl) await chrome.storage.local.remove(['job', 'recent']) + return { settings: config, libraries } +} + +async function saveItem(input) { + if (activeSave) throw new Error('An item is already being saved. Please wait.') + activeSave = true + let job + try { + const config = await settings() + if (!config.connected) throw new Error('Connect to ResearchOS before saving.') + const request = importRequest(input.identifier, input.mode, input.libraryId) + const libraries = await librariesFor(config) + const library = libraries.find(lib => lib.id === input.libraryId) + if (!library) throw new Error('This library is no longer available. Reopen the extension and choose another library.') + job = { + id: crypto.randomUUID(), status: 'saving', identifier: input.identifier.trim(), type: request.type, + libraryId: library.id, libraryName: library.name, startedAt: Date.now(), frontendUrl: config.frontendUrl, + } + await chrome.storage.local.set({ job, settings: { ...config, libraryId: library.id } }) + const item = await requestApi(config, request.path, request.body) + if (!item || typeof item.id !== 'string' || typeof item.title !== 'string') { + throw Object.assign(new Error('The server did not return a saved item. Check your Inbox before trying again.'), { uncertain: true }) + } + job = { + ...job, status: item.already_exists ? 'duplicate' : 'saved', title: item.title, + itemId: item.id, itemStatus: item.status, itemLibraryId: item.library_id, + url: itemUrl(config.frontendUrl, request.type, item.id), finishedAt: Date.now(), + } + const { recent = [] } = await chrome.storage.local.get('recent') + await chrome.storage.local.set({ job, recent: [job, ...recent.filter(entry => entry.url !== job.url)].slice(0, 5) }) + return job + } catch (error) { + if (job) { + job = { ...job, status: error.uncertain ? 'uncertain' : 'error', error: error.message, finishedAt: Date.now() } + await chrome.storage.local.set({ job }) + } + throw error + } finally { activeSave = false } +} + +export async function handleMessage(message) { + await ready + switch (message?.type) { + case 'GET_STATE': { + const state = await chrome.storage.local.get(['job', 'recent']) + return { ...state, settings: await settings() } + } + case 'CONNECT': return connect(message.settings) + case 'LIBRARIES': return librariesFor(await settings()) + case 'SAVE': return saveItem(message) + default: throw new Error('Unknown ResearchOS extension command.') + } +} + +chrome.runtime.onMessage.addListener((message, sender, respond) => { + // Only our own extension pages can issue API operations, never website scripts. + if (sender.id !== chrome.runtime.id || !sender.url?.startsWith(chrome.runtime.getURL(''))) return false + handleMessage(message).then(data => respond({ ok: true, data }), error => respond({ ok: false, error: error.message })) + return true +}) diff --git a/frontend/src/extension/background.test.js b/frontend/src/extension/background.test.js new file mode 100644 index 0000000..a59377c --- /dev/null +++ b/frontend/src/extension/background.test.js @@ -0,0 +1,101 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { DEFAULT_SETTINGS } from './core' + +let stored, chromeMock, handler +const library = { id: 'lib_1', name: 'My Library' } +const item = { id: 'p_1', title: 'A useful paper', library_id: library.id, status: 'inbox', already_exists: false } +const response = (body, status = 200) => ({ ok: status < 400, status, json: async () => body }) + +async function load() { + vi.resetModules() + return (await import('./background')).handleMessage +} + +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() } }, + 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])]))), + set: vi.fn(async values => { Object.assign(stored, structuredClone(values)) }), + remove: vi.fn(async keys => { for (const key of keys) delete stored[key] }), + } }, + action: { setBadgeText: vi.fn(async () => {}), setBadgeBackgroundColor: vi.fn(async () => {}) }, + } + vi.stubGlobal('chrome', chromeMock) + vi.stubGlobal('fetch', vi.fn(async (_url, options) => response(options.method === 'POST' ? item : [library]))) +}) +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() }) + +describe('background imports', () => { + it('persists success and recent history using the selected library and existing backend API', async () => { + handler = await load() + const result = await handler({ type: 'SAVE', identifier: '10.1000/paper', mode: 'auto', libraryId: library.id }) + expect(fetch).toHaveBeenLastCalledWith('http://localhost:8000/api/papers/import', expect.objectContaining({ method: 'POST', body: JSON.stringify({ identifier: '10.1000/paper', library_id: library.id }), credentials: 'omit', redirect: 'error' })) + expect(result).toMatchObject({ status: 'saved', itemId: item.id, libraryName: library.name, url: 'http://localhost:5173/library/paper/p_1' }) + expect(stored.job.status).toBe('saved') + expect(stored.recent).toHaveLength(1) + }) + + it('reports duplicates without changing their existing status', async () => { + fetch.mockImplementation(async (_url, options) => response(options.method === 'POST' ? { ...item, status: 'read', already_exists: true } : [library])) + handler = await load() + expect(await handler({ type: 'SAVE', identifier: '10.1000/paper', mode: 'auto', libraryId: library.id })).toMatchObject({ status: 'duplicate', itemStatus: 'read' }) + expect(fetch.mock.calls.filter(([, opts]) => opts.method !== 'GET')).toHaveLength(1) + }) + + it('blocks concurrent saves and never submits to a missing library', async () => { + handler = await load() + let finish + fetch.mockImplementationOnce(() => new Promise(resolve => { finish = resolve })) + const saving = handler({ type: 'SAVE', identifier: '10.1000/paper', mode: 'auto', libraryId: library.id }) + await vi.waitFor(() => expect(finish).toBeTypeOf('function')) + await expect(handler({ type: 'SAVE', identifier: '10.1000/paper', mode: 'auto', libraryId: library.id })).rejects.toThrow('already being saved') + finish(response([])) + await expect(saving).rejects.toThrow('no longer available') + expect(fetch.mock.calls.some(([, opts]) => opts.method === 'POST')).toBe(false) + }) + + it('keeps an uncertain result after transport failure and never retries the POST', async () => { + fetch.mockImplementation(async (_url, options) => { + if (options.method === 'POST') throw new Error('Connection lost') + return response([library]) + }) + handler = await load() + await expect(handler({ type: 'SAVE', identifier: '10.1000/paper', mode: 'auto', libraryId: library.id })).rejects.toThrow('may have completed') + expect(stored.job.status).toBe('uncertain') + expect(fetch).toHaveBeenCalledTimes(2) + }) + + it('recovers interrupted saves without replaying them after a worker restart', async () => { + stored.job = { status: 'saving', identifier: '10.1000/paper' } + handler = await load() + expect((await handler({ type: 'GET_STATE' })).job).toMatchObject({ status: 'uncertain', error: expect.stringContaining('interrupted') }) + expect(fetch).not.toHaveBeenCalled() + }) + + it('persists readable validation failures', async () => { + fetch.mockImplementation(async (_url, opts) => opts.method === 'POST' ? response({ detail: [{ msg: 'Invalid identifier' }] }, 422) : response([library])) + handler = await load() + await expect(handler({ type: 'SAVE', identifier: '10.1000/paper', mode: 'auto', libraryId: library.id })).rejects.toThrow('Invalid identifier') + expect(stored.job.status).toBe('error') + }) + + it('requires server permissions and leaves a working connection intact if reconnecting fails', async () => { + chromeMock.permissions.contains.mockResolvedValue(false) + handler = await load() + await expect(handler({ type: 'CONNECT', settings: { backendUrl: 'https://new.example.org', frontendUrl: 'https://new.example.org' } })).rejects.toThrow('Server access is missing') + expect(stored.settings.backendUrl).toBe(DEFAULT_SETTINGS.backendUrl) + expect(fetch).not.toHaveBeenCalled() + }) + + it('rejects messages from web pages and content scripts', async () => { + await load() + const listener = chromeMock.runtime.onMessage.addListener.mock.calls[0][0] + const respond = vi.fn() + expect(listener({ type: 'SAVE' }, { id: 'extension-id', url: 'https://example.org' }, respond)).toBe(false) + expect(listener({ type: 'SAVE' }, { id: 'other-extension', url: 'chrome-extension://other-extension/popup.html' }, respond)).toBe(false) + expect(fetch).not.toHaveBeenCalled() + }) +}) From a0397654f10fd853ef6222c1af637127bd402e51 Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Sat, 28 Nov 2026 20:29:55 -0500 Subject: [PATCH 4/8] feat(extension): add a themed Inbox popup and Chrome build Package a Manifest V3 extension with optional server permissions and a keyboard shortcut. Reuse the ResearchOS palette and theme provider for light, dark, and system modes. Add connection settings, editable capture input, type overrides, library selection, and result feedback with popup interaction tests. --- frontend/extension/popup.html | 13 ++ frontend/extension/public/icons/icon128.png | Bin 0 -> 2334 bytes frontend/extension/public/icons/icon16.png | Bin 0 -> 406 bytes frontend/extension/public/icons/icon32.png | Bin 0 -> 727 bytes frontend/extension/public/icons/icon48.png | Bin 0 -> 989 bytes frontend/extension/public/manifest.json | 23 +++ frontend/extension/tailwind.config.cjs | 7 + frontend/package.json | 1 + frontend/src/extension/App.jsx | 213 ++++++++++++++++++++ frontend/src/extension/App.test.jsx | 107 ++++++++++ frontend/src/extension/Icon.jsx | 18 ++ frontend/src/extension/main.jsx | 7 + frontend/src/extension/styles.css | 23 +++ frontend/vite.extension.config.js | 24 +++ 14 files changed, 436 insertions(+) create mode 100644 frontend/extension/popup.html create mode 100644 frontend/extension/public/icons/icon128.png create mode 100644 frontend/extension/public/icons/icon16.png create mode 100644 frontend/extension/public/icons/icon32.png create mode 100644 frontend/extension/public/icons/icon48.png create mode 100644 frontend/extension/public/manifest.json create mode 100644 frontend/extension/tailwind.config.cjs create mode 100644 frontend/src/extension/App.jsx create mode 100644 frontend/src/extension/App.test.jsx create mode 100644 frontend/src/extension/Icon.jsx create mode 100644 frontend/src/extension/main.jsx create mode 100644 frontend/src/extension/styles.css create mode 100644 frontend/vite.extension.config.js diff --git a/frontend/extension/popup.html b/frontend/extension/popup.html new file mode 100644 index 0000000..4e1d0ae --- /dev/null +++ b/frontend/extension/popup.html @@ -0,0 +1,13 @@ + + + + + + + Save to ResearchOS + + +
+ + + diff --git a/frontend/extension/public/icons/icon128.png b/frontend/extension/public/icons/icon128.png new file mode 100644 index 0000000000000000000000000000000000000000..fadf737ebd00c3671067859e6fe4966bc544e2f5 GIT binary patch literal 2334 zcmV+(3E}pMP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D2(w87>Vw~9re~(7-q%(2Ue)xBMw%4G z*|BK3I6h9Nr=lb~6X-|Te#^yiK-<_EjpON&@`TfT5~cYppq-U*n!jPy6i4IYP?YB9 zqBL7=IKhA+#%aD5CHVzhgfvE4v>2})g!{&6R?w3PSSHCXF2>U*Xw29YCDWzSarA=& z&VUPZoEB#n65y^6@Tl`hcxDmffPDwU^ zi**p~27rS(g&~E0h6G%#gJ?GZ#<6=v^H|qM&%Grx3sCL$_mZwUh;{>j%QpvDe@?&N zd02aI3AkJbF=BvcUoT1r4-vXg(bx1YFsLaPR#puyUP2h6A?)B;q#OCNE6cc%;h zQ1NQ3n4w0_oepuLEBHF zo&HrgYXETRddpZao0Z4V*V#a4@UQ=-&*)AY09?JbN!z0)T~~)Hs=-IL)1?lAZeRCz zbKU?L=T&M3-06`jU4mb|Mx_p7VlxPE-T(kIe$0UPlZ`@ApWx3kUk9nc+y{FH=&`yG zVE}-}YFkw^StuGBd{+=-0HD(7CJIF==K;AMd?3mIz;>a?r{Du|1^^s|qWQh}75g0z zd<#AhX#mi*P=tvUQmVGeBzh0j7U*2U$KV681^_CBqR%IrO0|S0p%+2meGNVkZ2-_W zxLvf-?lY0W2jUH&S}4*fslf;04FFUMMY<$8_`nMT0F^=!x1n5nlFh&ZL|w|b`W#sJ9qO-jf1EE{-X09^ex#QiHB8+c&=jK?;log48604lq6bV$cdn@r<{0Z@^%A#6mU z=OPU+3^4Q#WPODUgr18uyf6STy(0+sJ(OMs2HqIp;~Qodgs?50o`XcZFo5aRz^yI$ zv;PY52Cy{&wDD_X9f&mm#$Vhy!=`*Nfk*?`+y+i1-2~zcpt}7Vf%*M!GbWL20#OD~ z{f!=usWxh0xmd+8O~U(Nwy(0_B-I3B41mT}+4hZK(_5@yzJQ{Q>YM??3j#l1=JnMC zA`GC?_z(hzEn@Wb^B|~LK}70ELGbo_y~=q=GlBC4P|fjib(>h2@y!HI8$dP3$8jdh zvObx>Ndt7r@jv+9&W;>kOyHaWy5#t_SL1vzfl~(PlHB)2dU)vwo&;m)C6tqqZ@4oKqYOjA8q1FMt=X^cM6xi z!5p6hRTJQDCT;CwBDG~V031E^kCNwQI>+Zg#RMucam#pC1K^9RjOD7bmE&{3Wdca& z?+@7wfGeLf__lL=4meGq>z+hx2H@)UUCQw};4%SrA?uh2u^2$*#?30)*pz?6g(j~4 ztX9@;la5=`uoyt4dZ!{7K!?k1!__|M9l6_QumQO5(B)J24_t4b!3N;ILx;{8uMJ#p zpTP#;zC(xf8!k{>Z=b;i;F{%D;{JlRalL&88vwI*PTBecNL{$zK7$Q_GOfxouBvqZ z<(p|-Z=b;i0GDs_lmLCX0W-zr_F*vqmT6I`8Y1Mlrk6rZ;d1+oqGY;6AMC@>yL51; zH?HAo`-~RS{3Ly_FMYc@toPIR@(~x?XA~_L$LWJZK-!}^=|Q)q%h|5tTKkNS#>FA} z;7~B;wf&WwiOmkK;!^vJ7US6g`XCobSx^a^|NR|S4qe^YX&M*WX9SJYe2qR4cswW# z5GDBq`b5Bg#%X@7GyrEN5D-K%T`CQLdB8Z$irN7IuR#J(8lap9B>5G3K)`EOc7hKr zq}hpvg95&iWT$r-01CapW5WuDeH#DKIG!G9I5^-L=;iTb11J=n_$LaJGjhPm0 zFCnkgPa~t6&j5EOmZ)jKlKVm1X0C>J!cK`qY07*qoM6N<$ Ef)w>o>;M1& literal 0 HcmV?d00001 diff --git a/frontend/extension/public/icons/icon16.png b/frontend/extension/public/icons/icon16.png new file mode 100644 index 0000000000000000000000000000000000000000..4f017f12bba6bf6fb5188c0a68d4abb85030e6fb GIT binary patch literal 406 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|SkfJR9T^xl z_H+M9WCij$3p^r=85sBugD~Uq{1quc4ceYAjv*HQ$q5Zir+@iNh55z{t&!euCU8ih zH0*0UPePR>kSi8pUi;f$Yg^W@Yy8_JBMlO-_5a^jd*4vx@ga?E;cNcv16Tt3cHa?_CfzQFBztFI9z1uVlA2NP;p6b&C3VgtY_E)Rwy4gv^ut| y?clDTyP0=61sPbFN14{$?$dMR0s6d5hN0%nQJu_=YnOmw$>8bg=d#Wzp$P!H>#{Zg literal 0 HcmV?d00001 diff --git a/frontend/extension/public/icons/icon32.png b/frontend/extension/public/icons/icon32.png new file mode 100644 index 0000000000000000000000000000000000000000..eb82bc58de70d316009bfb2a116be7e3035e26db GIT binary patch literal 727 zcmV;|0x127P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0&Gb{K~z{ry_dgB z96=Pvx3sj(pI~Y0ZgEMK%1Vo1b(N$@5mMR6x+_tLAe<0|fP@qggg{~;!6HR0R78TM zga}qj2;qpgx3ib~G2uJwte3Yldo$?XgAb>(Z{GXv%-i|lI0~EaugBals(L|l;l4mT z*N?_&uK!Fpg>l^rV_p_+*koQ1&C%SB8^oWfbD6kdd|2`M$W8L*Q|d4b+>kA&0x&EJ z2k`7&B6zfve|8@@C=A*Nknr0@mrJ|&)#Hy}v7FysalD}UoHl~F?N*jtT5a!d&TkNd zMi2rPXd`&JlNYe@#aw{t2xPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D19C}3K~!i%)tXOe z)Ib!*bM)xZqeqY4bQ59gNiTv258|mOPaecmZ)viqs36#bf>4$sB1J?*im3D;MJyuz zfx=Qz6p>aBvSK$$yW8F97oFYNm+WLRGcM@|KU%UcnfGO1CNGnM9~`F}DM<4D`f&10Hx}Ee_;G@Z z_blB=LCK8LTCM!oW1$NV&4mrg;yE#;c%OqEZGXZ;t*3P+By;C^{u7WdJOH z*rvx$%% zE7g{rtIlT{^|k6lnE&V{8|m}pnS`K zhY%VsOO^?v>q1#;HM~&Ubf2Q|CVJ%QQfpmEv{tj-&3{%c!lj1;6I9CULZa5-$A);V zrYNGZl-Gswnll=&gU(nZ4T##~ytSI5=!|9IEeGAm_@B#(6xFeWub0?zV$ro46;#Kv z95*;fH|`{ocVu|iL_gRG*nSYPSFD*Aa_RBHdSamJ#=A=R(*hy3AFkt<1^su$w%gi| zuY?Ac75tu~pFGpQ3%Wsr%LLARX7WrZC)$Z&00000 LNkvXXu0mjf5WCWr literal 0 HcmV?d00001 diff --git a/frontend/extension/public/manifest.json b/frontend/extension/public/manifest.json new file mode 100644 index 0000000..67bee31 --- /dev/null +++ b/frontend/extension/public/manifest.json @@ -0,0 +1,23 @@ +{ + "manifest_version": 3, + "name": "ResearchOS — Save to Inbox", + "description": "Save papers, DOIs, websites, and GitHub repositories to your ResearchOS Inbox.", + "version": "0.1.0", + "minimum_chrome_version": "109", + "permissions": ["activeTab", "scripting", "storage"], + "optional_host_permissions": ["http://*/*", "https://*/*"], + "action": { + "default_popup": "popup.html", + "default_title": "Save to ResearchOS", + "default_icon": { "16": "icons/icon16.png", "32": "icons/icon32.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } + }, + "icons": { "16": "icons/icon16.png", "32": "icons/icon32.png", "48": "icons/icon48.png", "128": "icons/icon128.png" }, + "background": { "service_worker": "background.js", "type": "module" }, + "commands": { + "_execute_action": { + "suggested_key": { "default": "Alt+Shift+S", "mac": "Alt+Shift+S" }, + "description": "Save to ResearchOS Inbox" + } + }, + "content_security_policy": { "extension_pages": "script-src 'self'; object-src 'none'; base-uri 'none'" } +} diff --git a/frontend/extension/tailwind.config.cjs b/frontend/extension/tailwind.config.cjs new file mode 100644 index 0000000..9f9649a --- /dev/null +++ b/frontend/extension/tailwind.config.cjs @@ -0,0 +1,7 @@ +const path = require('node:path') +const app = require('../tailwind.config.cjs') + +module.exports = { + ...app, + content: [path.join(__dirname, '../src/extension/**/*.{js,jsx}'), path.join(__dirname, 'popup.html')], +} diff --git a/frontend/package.json b/frontend/package.json index 3949c9e..3058581 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite", "build": "vite build", + "build:extension": "vite build --config vite.extension.config.js", "preview": "vite preview", "test": "vitest", "test:run": "vitest run", diff --git a/frontend/src/extension/App.jsx b/frontend/src/extension/App.jsx new file mode 100644 index 0000000..74d239d --- /dev/null +++ b/frontend/src/extension/App.jsx @@ -0,0 +1,213 @@ +import { useEffect, useState } from 'react' +import { useTheme } from '../context/ThemeContext' +import { captureActivePage } from './capture' +import { DEFAULT_SETTINGS, TYPE_META, detectSource, normalizeBase, permissionOrigin, sourceFromPage } from './core' +import Icon from './Icon' + +async function command(type, values = {}) { + const result = await chrome.runtime.sendMessage({ type, ...values }) + if (!result?.ok) throw new Error(result?.error || 'The extension could not respond. Reload it from chrome://extensions and try again.') + return result.data +} + +function openTab(url) { chrome.tabs.create({ url }) } + +function Connection({ settings, onConnected, onBack, busy }) { + const [backendUrl, setBackendUrl] = useState(settings.backendUrl) + const [frontendUrl, setFrontendUrl] = useState(settings.frontendUrl) + const [connecting, setConnecting] = useState(false) + const [error, setError] = useState('') + + async function connect(event) { + event.preventDefault() + setError('') + setConnecting(true) + try { + const backend = normalizeBase(backendUrl).replace(/\/api$/, '') + const frontend = normalizeBase(frontendUrl) + // This must be called directly in the submit gesture, before any await. + const permitted = await chrome.permissions.request({ origins: [permissionOrigin(backend)] }) + if (!permitted) throw new Error('Allow access to your ResearchOS server to connect. You can try again below.') + const connected = await command('CONNECT', { settings: { backendUrl: backend, frontendUrl: frontend } }) + onConnected(connected) + } catch (err) { setError(err.message) } + finally { setConnecting(false) } + } + + return
+ {settings.connected && } +
+

Connect your workspace

+

Send what you find straight to your ResearchOS library.

+
+
+ + + {error &&

{error}

} + +
+

Uses your existing ResearchOS backend. Your database credentials stay on the server. Chrome will ask for access to the server you choose.

+
+} + +function JobResult({ job }) { + if (!job || job.status === 'saving') return null + const success = job.status === 'saved' + const duplicate = job.status === 'duplicate' + const title = success ? 'Saved to Inbox' : duplicate ? 'Already in your library' : job.status === 'uncertain' ? 'Check your Inbox' : 'Could not save' + return
+
+ +
+

{title}

+

{job.error || job.title}

+ {duplicate &&

The existing item and its reading status were kept.

} + {success &&

{job.libraryName} / Inbox

} + {job.url && } +
+
+
+} + +export default function App() { + const { mode: theme, setMode: setTheme } = useTheme() + const [settings, setSettings] = useState(DEFAULT_SETTINGS) + const [showSettings, setShowSettings] = useState(false) + const [loading, setLoading] = useState(true) + const [libraries, setLibraries] = useState([]) + const [libraryId, setLibraryId] = useState('') + const [identifier, setIdentifier] = useState('') + const [mode, setMode] = useState('auto') + const [page, setPage] = useState(null) + const [pageSource, setPageSource] = useState(null) + const [job, setJob] = useState(null) + const [recent, setRecent] = useState([]) + const [submitting, setSubmitting] = useState(false) + const [error, setError] = useState('') + const [libraryError, setLibraryError] = useState('') + const [refreshing, setRefreshing] = useState(false) + const busy = submitting || job?.status === 'saving' + const detected = detectSource(identifier) + const effectiveType = mode === 'auto' ? detected?.type : mode + const meta = TYPE_META[effectiveType] + + useEffect(() => { + let alive = true + async function start() { + try { + const [state, currentPage] = await Promise.all([command('GET_STATE'), captureActivePage().catch(() => null)]) + if (!alive) return + setSettings(state.settings) + setLibraryId(state.settings.libraryId) + setRecent(state.recent || []) + const source = currentPage ? sourceFromPage(currentPage) : null + setPage(currentPage) + setPageSource(source) + if (state.job?.status === 'saving') { + 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) + } + if (state.settings.connected) { + try { + const libs = await command('LIBRARIES') + if (alive) setLibraries(libs) + } catch (err) { if (alive) setLibraryError(err.message) } + } + } catch (err) { if (alive) setError(err.message) } + finally { if (alive) setLoading(false) } + } + start() + const onStorage = (changes, area) => { + if (area !== 'local') return + if (changes.job) setJob(changes.job.newValue || null) + if (changes.recent) setRecent(changes.recent.newValue || []) + } + chrome.storage.onChanged.addListener(onStorage) + return () => { alive = false; chrome.storage.onChanged.removeListener(onStorage) } + }, []) + + async function refreshLibraries() { + setRefreshing(true) + setLibraryError('') + try { setLibraries(await command('LIBRARIES')) } + catch (err) { setLibraryError(err.message) } + finally { setRefreshing(false) } + } + + function editIdentifier(value) { + setIdentifier(value) + setJob(null) + setError('') + } + + async function save(event) { + event.preventDefault() + if (busy || !identifier.trim()) return + setSubmitting(true) + setError('') + setJob(null) + try { setJob(await command('SAVE', { identifier, mode, libraryId })) } + catch (err) { setError(err.message) } + finally { setSubmitting(false) } + } + + function connected(result) { + if (result.settings.backendUrl !== settings.backendUrl) setRecent([]) + setSettings(result.settings) + setLibraryId(result.settings.libraryId) + setLibraries(result.libraries) + setJob(null) + setShowSettings(false) + setError('') + setLibraryError('') + } + + return
+
+
ResearchOS
+ Web clipper +
+ {loading ?
Opening your workspace…
: showSettings || !settings.connected ? + <> setShowSettings(false)} busy={busy} />{error &&

{error}

} : +
+

Save to Inbox

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

+ {pageSource &&
+ +

{pageSource.reason}

{page?.title || pageSource.identifier}

+
} +
+
+
{detected && {detected.label}}
+