Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
15 changes: 15 additions & 0 deletions backend/migrations/038_library_scoped_github_urls.sql
Original file line number Diff line number Diff line change
@@ -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;
4 changes: 3 additions & 1 deletion backend/migrations/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion backend/routers/github_repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
2 changes: 1 addition & 1 deletion backend/routers/websites.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
7 changes: 5 additions & 2 deletions backend/services/github_repo_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
7 changes: 5 additions & 2 deletions backend/services/website_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
35 changes: 35 additions & 0 deletions backend/tests/run_import_scope_sql.mjs
Original file line number Diff line number Diff line change
@@ -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()
}
38 changes: 38 additions & 0 deletions backend/tests/test_import_library_scope.py
Original file line number Diff line number Diff line change
@@ -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"
98 changes: 98 additions & 0 deletions frontend/extension/README.md
Original file line number Diff line number Diff line change
@@ -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).
Loading
Loading