diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cd0d182..9d1683f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -17,6 +17,8 @@ jobs: run: npm install --prefix backend/data/citation-validation --no-audit --no-fund --ignore-scripts @electric-sql/pglite@0.5.14 - name: Verify citation migration and transactions run: node backend/tests/run_citation_sql.mjs + - name: Verify library-scoped import uniqueness + run: node backend/tests/run_import_scope_sql.mjs backend: runs-on: ubuntu-latest @@ -56,6 +58,8 @@ jobs: run: npm run test:run - name: Build frontend run: npm run build + - name: Build Chrome extension + run: npm run build:extension e2e: runs-on: ubuntu-24.04 @@ -83,3 +87,6 @@ jobs: - name: Run E2E smoke tests timeout-minutes: 8 run: npm run test:e2e + - name: Test unpacked Chrome extension + timeout-minutes: 3 + run: npm run test:extension diff --git a/README.md b/README.md index de36dd3..6d944d1 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,10 @@ Open [http://localhost:5173](http://localhost:5173). See [docs/getting-started.m ## Documentation +### Chrome extension + +Capture papers, DOIs, websites, and GitHub repositories into Inbox from Chrome, with the same ResearchOS colors and light/dark/system themes. See [build and installation instructions](frontend/extension/README.md). + Detailed documentation lives in [`docs/`](docs/README.md): | Section | What's covered | 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" diff --git a/frontend/extension/README.md b/frontend/extension/README.md new file mode 100644 index 0000000..7b5f62d --- /dev/null +++ b/frontend/extension/README.md @@ -0,0 +1,98 @@ +# ResearchOS Chrome extension + +Save papers, DOIs, arXiv IDs, websites, and GitHub repositories to a ResearchOS library's **Inbox**, using the same imports and duplicate detection as Quick Add in the app. The popup shares the app's Tailwind color palette and theme provider, with light, dark, and system modes. + +## Preview + +These screenshots show the actual popup running in Chromium with a local demo backend. They use test identifiers and library names rather than private library data. + +| Light mode | Dark mode | +| --- | --- | +| ![ResearchOS capture popup in light mode](screenshots/popup-light.png) | ![ResearchOS capture popup in dark mode](screenshots/popup-dark.png) | + +## Capabilities + +| Capability | Current behavior | +| --- | --- | +| Capture the current page | Prefills from the active tab's URL, selected identifier, or explicit scholarly metadata. | +| 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. | +| Fetch metadata | Uses the existing backend import endpoints, including their normal metadata lookup and paper PDF download behavior where supported. | +| Handle duplicates | Shows the existing item without resetting its reading status; website and repository checks respect the selected library. | +| Save in the background | Continues normal imports after the popup closes, persists results, and avoids automatically replaying uncertain writes. | +| Revisit saved items | Opens an imported item in ResearchOS and shows the latest three of five locally stored recent captures. | +| Match the app | Reuses the app's palette and theme provider, with independently persisted light, dark, and system preferences. | +| Connect to a workspace | Supports a configured local or hosted backend and app URL; requests Chrome host access when connecting. | + +This is an unpacked Chrome extension that depends on a running ResearchOS backend. It saves through the app's existing import pipeline; it does not add full-page archival, local PDF upload, offline sync, or authentication for protected deployments. Toolbar badges do not persist while browsing unrelated pages. + +## Build and install + +From the repository root: + +```sh +cd frontend +npm ci +npm run build:extension +``` + +1. Open `chrome://extensions` in Chrome and enable **Developer mode**. +2. Click **Load unpacked** and select `frontend/extension/dist`. +3. Pin **ResearchOS — Save to Inbox** in Chrome's extensions menu. +4. Open the popup and connect it to your running ResearchOS backend (default `http://localhost:8000`) and app (default `http://localhost:5173`). Allow Chrome's request for access to your server. +5. Choose the destination library and click **Save to Inbox**. + +Rebuild and click **Reload** on `chrome://extensions` after changing the source. No additional npm dependency is required. For an existing database, run [`038_library_scoped_github_urls.sql`](../../backend/migrations/038_library_scoped_github_urls.sql) in the Supabase SQL editor, then restart the backend. This removes the old global GitHub URL constraint so the same repository can be saved independently in different libraries; duplicates within a library remain blocked. Fresh installs using `schema.sql` already include the corrected indexes. + +## Capturing research + +- Click the toolbar icon or press **Alt+Shift+S** to open the popup. Customize the shortcut at `chrome://extensions/shortcuts`. +- 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. +- Every new item uses the existing backend import endpoint and starts with `status="inbox"`. Existing duplicates retain their reading status. The extension does not move read items back to Inbox. +- Imports run in the extension service worker and normally finish even if the popup closes. Reopen the popup to see the result and recent captures. Import results do not add persistent toolbar badges while browsing other pages. +- The last five successful imports or duplicate results are stored locally; the popup shows the latest three. Switching to another backend clears that history. Theme preference is stored separately in the extension; its colors match the app, but its preference does not sync to the app's browser tab. + +## Connections and privacy + +The backend writes to the same Supabase database configured for your ResearchOS app. Do not enter Supabase credentials into the extension. Keep the backend running when saving. Hosted installations can enter their own HTTPS backend and app URLs, including a path prefix. A trailing `/api` on the backend address is accepted and normalized. + +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. + +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. + +## Potential future additions + +These are ideas for later work, not capabilities included in this release. The order groups related changes rather than committing to a delivery schedule. + +| 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. | +| Offline capture queue | Keep unsent captures until the backend is available. | Add server-side idempotency or reconciliation before automatically retrying writes. | +| Full-page snapshots and highlights | Preserve article text, selections, and source context alongside an item. | Define storage, provenance, and a user-approved page-content capture flow. | +| Authentication and workspace profiles | Connect to protected deployments and switch between multiple servers. | Integrate the deployment's auth flow, isolate credentials and history, and support sign-out. | +| Site-specific paper detection | Improve capture from more publisher layouts and richer scholarly metadata. | Add focused adapters and fixtures; keep DOI extraction tied to the actual article. | +| Contextual saved state | Indicate whether the current page is already in the selected library. | Use a read-only lookup, URL/DOI normalization, and library-specific state; never reuse the last import's status globally. | +| Better long-running import progress | Follow slow metadata/PDF imports and recover across browser restarts. | Introduce backend import jobs and status polling rather than extending a single POST indefinitely. | +| Firefox and Edge packages | Make capture available in other browsers. | Verify browser API, Manifest V3, permissions, and packaging compatibility separately. | +| Store distribution and release archives | Install updates without rebuilding or loading the folder manually. | Prepare a privacy disclosure, versioned artifacts, signing, and a release process. | + +## Validation + +```sh +cd frontend +npm run test:run -- src/extension +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`. + +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 new file mode 100644 index 0000000..99ef8b3 --- /dev/null +++ b/frontend/extension/e2e/extension.spec.js @@ -0,0 +1,108 @@ +import { test, expect, chromium } from '@playwright/test' +import { createServer } from 'node:http' +import { cp, mkdir, readFile, writeFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' + +test('unpacked extension connects, imports all item types, handles duplicates, and persists themes', async ({}, testInfo) => { + const imported = [] + const libraries = [{ id: 'lib_1', name: 'My Library' }, { id: 'lib_2', name: 'Reading Group' }] + const server = createServer(async (request, response) => { + if (request.url === '/article') { + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Research article

A paper worth keeping

') + return + } + response.setHeader('Content-Type', 'application/json') + if (request.url === '/api/libraries') { response.end(JSON.stringify(libraries)); return } + if (/^\/api\/(papers|websites|github-repos)\/import$/.test(request.url) && request.method === 'POST') { + let body = '' + for await (const part of request) body += part + const data = JSON.parse(body) + const duplicate = imported.some(entry => entry.path === request.url && JSON.stringify(entry.body) === body) + imported.push({ path: request.url, body: data }) + response.writeHead(duplicate ? 200 : 201) + response.end(JSON.stringify({ id: 'item_1', title: 'A paper worth keeping', status: duplicate ? 'read' : 'inbox', library_id: data.library_id, already_exists: duplicate })) + return + } + response.writeHead(404) + response.end(JSON.stringify({ detail: 'Not found' })) + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const base = `http://127.0.0.1:${server.address().port}` + let context + try { + // Only this disposable copy gets an already-granted test-server permission. + // The shipped manifest requests server access through the user's Connect gesture. + const extensionPath = testInfo.outputPath('unpacked') + await mkdir(extensionPath, { recursive: true }) + await cp(fileURLToPath(new URL('../dist/', import.meta.url)), extensionPath, { recursive: true }) + const manifestPath = `${extensionPath}/manifest.json` + const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) + expect(manifest.host_permissions).toBeUndefined() + manifest.host_permissions = ['http://127.0.0.1/*'] + await writeFile(manifestPath, JSON.stringify(manifest)) + context = await chromium.launchPersistentContext(testInfo.outputPath('profile'), { + channel: 'chromium', headless: true, + viewport: { width: 400, height: 680 }, + args: [`--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`], + }) + let [worker] = context.serviceWorkers() + if (!worker) worker = await context.waitForEvent('serviceworker') + const extensionId = worker.url().split('/')[2] + const popup = await context.newPage() + const errors = [] + popup.on('pageerror', error => errors.push(error.message)) + await popup.goto(`chrome-extension://${extensionId}/popup.html`) + await expect(popup.getByRole('heading', { name: 'Connect your workspace' })).toBeVisible() + await popup.getByLabel(/Backend address/).fill(base) + await popup.getByLabel(/App address/).fill(base) + await popup.getByRole('button', { name: 'Connect to ResearchOS' }).click() + await expect(popup.getByRole('heading', { name: 'Save to Inbox' })).toBeVisible() + + // Real script injection in the same isolated world used by activeTab capture. + const article = await context.newPage() + await article.goto(`${base}/article`) + const captured = await worker.evaluate(async origin => { + const [tab] = await chrome.tabs.query({ url: `${origin}/article` }) + const [result] = await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => ({ doi: document.querySelector('meta[name="citation_doi"]').content, title: document.title }) }) + return result.result + }, base) + expect(captured.doi).toBe('10.1000/browser-test') + await article.close() + + await popup.getByLabel('DOI, arXiv ID, or URL').fill(captured.doi) + await popup.getByLabel('Save to library').selectOption('lib_2') + await popup.getByLabel('Color theme').selectOption('light') + await expect(popup.locator('html')).not.toHaveClass('dark') + await popup.screenshot({ path: testInfo.outputPath('popup-light.png'), animations: 'disabled' }) + await popup.getByLabel('Color theme').selectOption('dark') + await expect(popup.locator('html')).toHaveClass('dark') + await expect(popup.locator('body')).toHaveCSS('background-color', 'rgb(30, 30, 30)') + await popup.screenshot({ path: testInfo.outputPath('popup-dark.png'), animations: 'disabled' }) + await popup.getByRole('button', { name: 'Save to Inbox', exact: true }).click() + await expect(popup.getByText('Saved to Inbox', { exact: true })).toBeVisible() + expect(imported[0]).toEqual({ path: '/api/papers/import', body: { identifier: '10.1000/browser-test', library_id: 'lib_2' } }) + + await popup.getByRole('button', { name: 'Save again' }).click() + await expect(popup.getByText('Already in your library')).toBeVisible() + await expect(popup.getByText('The existing item and its reading status were kept.')).toBeVisible() + + for (const [identifier, path, normalized] of [ + ['https://example.org/article', '/api/websites/import', 'https://example.org/article'], + ['https://github.com/owner/repo/tree/main', '/api/github-repos/import', 'https://github.com/owner/repo'], + ]) { + await popup.getByLabel('DOI, arXiv ID, or URL').fill(identifier) + await popup.getByRole('button', { name: 'Save to Inbox', exact: true }).click() + await expect(popup.getByText('Saved to Inbox', { exact: true })).toBeVisible() + expect(imported.at(-1)).toEqual({ path, body: { url: normalized, library_id: 'lib_2' } }) + } + await popup.reload() + 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') + expect(errors).toEqual([]) + } finally { + await context?.close() + await new Promise(resolve => server.close(resolve)) + } +}) 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 0000000..fadf737 Binary files /dev/null and b/frontend/extension/public/icons/icon128.png differ diff --git a/frontend/extension/public/icons/icon16.png b/frontend/extension/public/icons/icon16.png new file mode 100644 index 0000000..4f017f1 Binary files /dev/null and b/frontend/extension/public/icons/icon16.png differ diff --git a/frontend/extension/public/icons/icon32.png b/frontend/extension/public/icons/icon32.png new file mode 100644 index 0000000..eb82bc5 Binary files /dev/null and b/frontend/extension/public/icons/icon32.png differ diff --git a/frontend/extension/public/icons/icon48.png b/frontend/extension/public/icons/icon48.png new file mode 100644 index 0000000..09d4a90 Binary files /dev/null and b/frontend/extension/public/icons/icon48.png differ 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/screenshots/popup-dark.png b/frontend/extension/screenshots/popup-dark.png new file mode 100644 index 0000000..cb4c2af Binary files /dev/null and b/frontend/extension/screenshots/popup-dark.png differ diff --git a/frontend/extension/screenshots/popup-light.png b/frontend/extension/screenshots/popup-light.png new file mode 100644 index 0000000..968e7f2 Binary files /dev/null and b/frontend/extension/screenshots/popup-light.png differ 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..548cd38 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -6,10 +6,13 @@ "scripts": { "dev": "vite", "build": "vite build", + "build:extension": "vite build --config vite.extension.config.js", "preview": "vite preview", "test": "vitest", "test:run": "vitest run", - "test:e2e": "playwright test" + "test:e2e": "playwright test", + "pretest:extension": "npm run build:extension", + "test:extension": "playwright test --config playwright.extension.config.js" }, "dependencies": { "@dnd-kit/core": "^6.3.1", diff --git a/frontend/playwright.extension.config.js b/frontend/playwright.extension.config.js new file mode 100644 index 0000000..9af8912 --- /dev/null +++ b/frontend/playwright.extension.config.js @@ -0,0 +1,10 @@ +import { defineConfig } from '@playwright/test' + +export default defineConfig({ + testDir: './extension/e2e', + outputDir: './test-results/extension', + fullyParallel: false, + workers: 1, + timeout: 60_000, + use: { trace: 'retain-on-failure' }, +}) 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}}
+