From b4f68c89238a9778fe15d83579b4892fbcd49283 Mon Sep 17 00:00:00 2001 From: Sarthak Agrawal Date: Fri, 9 Oct 2026 11:16:33 +0530 Subject: [PATCH 1/2] Simplify Reader to a saved-link inbox with ChatGPT MCP --- .github/workflows/ci.yml | 5 +- .gitignore | 6 + AGENTS.md | 47 +- PROJECT_STATUS.md | 118 +- README.md | 302 +-- STATUS.md | 8 +- app.html | 327 +-- biome.json | 47 +- docs/architecture/data-flow.md | 2 + .../decisions/0001-vite-spa-hono-worker.md | 2 + .../decisions/0002-turso-drizzle.md | 2 + docs/architecture/decisions/0003-r2-pdfs.md | 2 + .../decisions/0004-better-auth-google.md | 2 + .../decisions/0005-ai-gateway-byok.md | 2 + .../decisions/0006-mv3-side-panel.md | 2 + .../decisions/0007-content-extraction.md | 2 + docs/architecture/decisions/0008-rss-inbox.md | 2 + .../decisions/0010-cloudflare-d1.md | 2 + docs/architecture/how-it-works.md | 2 + docs/architecture/overview.md | 107 +- docs/development/commands.md | 79 +- docs/development/setup.md | 2 + docs/development/testing.md | 192 +- docs/index.md | 2 + docs/knowledge/failed-approaches.md | 2 + docs/knowledge/learnings.md | 2 + docs/operations/env.md | 2 + docs/operations/jobs.md | 2 + docs/product/features.md | 100 +- docs/product/overview.md | 74 +- docs/product/surfaces.md | 63 +- knip.jsonc | 5 - landing-astro/src/layouts/Layout.astro | 109 - landing-astro/src/pages/changelog/index.astro | 158 +- landing-astro/src/pages/faq.astro | 159 +- landing-astro/src/pages/index.astro | 330 +-- landing-astro/src/styles/landing.css | 977 +------- package.json | 29 +- packages/chrome-extension/PRIVACY.md | 36 +- packages/chrome-extension/README.md | 62 +- packages/chrome-extension/manifest.json | 27 +- packages/chrome-extension/package.json | 6 +- .../chrome-extension/side-panel/index.html | 12 - .../src/__tests__/api.test.ts | 29 + packages/chrome-extension/src/api.ts | 25 + packages/chrome-extension/src/background.ts | 150 -- .../chrome-extension/src/content-script.ts | 69 - packages/chrome-extension/src/popup/App.tsx | 572 +---- .../chrome-extension/src/side-panel/App.tsx | 104 - .../src/side-panel/components/Chat.tsx | 376 --- .../src/side-panel/components/PageHeader.tsx | 129 - .../side-panel/components/QuickActions.tsx | 35 - .../src/side-panel/components/SaveButton.tsx | 380 --- .../src/side-panel/components/TTSPlayer.tsx | 89 - .../lib/__tests__/importQuality.test.ts | 45 - .../side-panel/lib/__tests__/types.test.ts | 136 - .../src/side-panel/lib/api.ts | 301 --- .../src/side-panel/lib/importQuality.ts | 81 - .../src/side-panel/lib/reading-list-sync.ts | 222 -- .../src/side-panel/lib/storage.ts | 29 - .../src/side-panel/lib/types.ts | 56 - .../chrome-extension/src/side-panel/main.tsx | 10 - .../chrome-extension/src/styles/globals.css | 21 +- packages/chrome-extension/tsconfig.json | 2 +- packages/chrome-extension/vite.config.ts | 28 +- packages/chrome-extension/vitest.config.ts | 21 +- playwright.config.ts | 19 +- pnpm-lock.yaml | 2222 +---------------- public/.well-known/agent-skills/index.json | 10 +- public/.well-known/ai-catalog.json | 7 - public/agents.md | 30 +- public/api-ai.json | 24 +- public/changelog.md | 33 +- public/faq.md | 55 +- public/index.md | 63 +- public/llms-full.txt | 98 +- public/llms.txt | 48 +- public/login.md | 10 +- public/pricing.md | 23 +- scripts/account-handler-fixture.ts | 51 - scripts/check-code-health.mjs | 6 +- scripts/local-ai.mjs | 30 - scripts/memory-capture-demo.ts | 29 - scripts/pdf-browser-fixture.mjs | 71 - scripts/qualify-account-article.test.ts | 359 --- scripts/qualify-account-notes.test.ts | 528 ---- scripts/qualify-account-pdf.mjs | 107 - scripts/qualify-guest-pdf.mjs | 125 - scripts/qualify-import-signin.mjs | 90 - scripts/qualify-local-library.mjs | 87 - src/AppProvidersLayout.tsx | 8 - src/agent-edge.mjs | 10 - src/agent-surfaces.test.ts | 21 +- src/components/AddArticleDialog.tsx | 578 ----- src/components/AppearanceToolbar.tsx | 165 -- src/components/ArticleCard.tsx | 417 ---- src/components/ArticleSummary.tsx | 379 --- src/components/ArticleTagEditor.tsx | 103 - src/components/ExportDataButton.tsx | 62 - src/components/ExtensionConnectClient.tsx | 41 +- src/components/HomeClient.tsx | 1298 ++-------- src/components/LibraryEmptyOnboarding.tsx | 139 -- src/components/LocalPdfReader.tsx | 66 - src/components/LocalReaderClient.tsx | 118 - src/components/LoginClient.tsx | 64 +- src/components/Navbar.tsx | 119 +- src/components/NotesAIChat.tsx | 649 ----- src/components/PDFReaderClient.tsx | 214 -- src/components/PDFViewer.tsx | 242 -- src/components/PdfPageNotes.tsx | 207 -- src/components/ReaderClient.tsx | 111 - src/components/ReaderView.tsx | 114 - src/components/ResearchBriefPanel.tsx | 205 -- src/components/SearchBar.tsx | 384 --- src/components/TTSPlayer.tsx | 96 - src/components/TagInput.tsx | 172 -- src/components/board/AddWebsiteDialog.tsx | 246 -- src/components/board/BoardCanvasClient.tsx | 606 ----- src/components/board/BoardListClient.tsx | 98 - src/components/board/BoardToolbar.tsx | 183 -- src/components/board/ElementPickerPanel.tsx | 240 -- src/components/board/ShareDialog.tsx | 33 - src/components/board/edges/LabeledEdge.tsx | 91 - .../board/hooks/useBoardArticleSync.ts | 89 - .../board/hooks/useBoardAutoSave.ts | 104 - src/components/board/hooks/useBoardData.ts | 49 - src/components/board/nodes/AIChatNode.tsx | 402 --- src/components/board/nodes/IframeNode.tsx | 92 - src/components/board/nodes/NoteNode.tsx | 160 -- src/components/board/nodes/ReaderNode.tsx | 128 - src/components/board/nodes/WebsiteNode.tsx | 120 - src/components/reader/ArticleShareDialog.tsx | 33 - src/components/reader/NoteCard.tsx | 111 - src/components/reader/NoteMarkerGroup.tsx | 109 - src/components/reader/ReaderCore.tsx | 1492 ----------- src/components/reader/SessionReviewPanel.tsx | 109 - src/components/reader/SharedArticleReader.tsx | 15 - src/components/saasmaker-feedback.tsx | 43 - src/components/ui/ShareLinkDialog.tsx | 172 -- src/components/ui/badge.tsx | 46 - src/components/ui/dialog.tsx | 107 - src/components/ui/dropdown-menu.tsx | 99 - src/components/ui/label.tsx | 19 - src/components/ui/segmented-control.tsx | 53 - src/hooks/useIsMobileViewport.ts | 18 - .../browser-memory-snapshots.json | 18 - src/lib/__fixtures__/memory-captures.json | 53 - src/lib/__tests__/api-keys.test.ts | 46 + .../articles-db-sanitization.test.ts | 93 - src/lib/__tests__/articles-db-search.test.ts | 60 - .../__tests__/browser-memory-import.test.ts | 137 - src/lib/__tests__/category-utils.test.ts | 128 - src/lib/__tests__/link-content.test.ts | 49 + src/lib/__tests__/links-db.test.ts | 81 + src/lib/__tests__/memories-db.test.ts | 142 -- src/lib/__tests__/memory-capture.test.ts | 64 - src/lib/__tests__/note-merge.test.ts | 43 - src/lib/__tests__/reading-time-utils.test.ts | 46 - src/lib/__tests__/research-brief.test.ts | 126 - .../__tests__/rss-parser-performance.test.ts | 64 - src/lib/__tests__/rss-parser.test.ts | 92 - src/lib/__tests__/rss-refresh.test.ts | 97 - src/lib/__tests__/tag-utils.test.ts | 61 - src/lib/ai-cloudflare.test.ts | 172 -- src/lib/ai-cloudflare.ts | 120 - src/lib/ai-config.ts | 13 - src/lib/ai-server.ts | 154 -- src/lib/ai-vendor-hooks.ts | 70 - src/lib/ai-vendor.ts | 61 - src/lib/analytics.ts | 8 +- src/lib/annotatable.ts | 24 - src/lib/api-keys.ts | 5 +- src/lib/article-query.ts | 3 - src/lib/articles-db.ts | 1224 --------- src/lib/auth-api.test.ts | 49 +- src/lib/auth-api.ts | 5 +- src/lib/auth0-mcp.test.ts | 16 + src/lib/auth0-mcp.ts | 8 +- src/lib/board-note-sync.ts | 71 - src/lib/boards-db.ts | 414 --- src/lib/browser-memory-import.ts | 216 -- src/lib/category-utils.ts | 26 - src/lib/db/client.ts | 2 - src/lib/import-draft.ts | 42 - src/lib/link-content.ts | 60 + src/lib/links-db.ts | 156 ++ src/lib/lists-db.ts | 287 --- src/lib/local-library.ts | 278 --- src/lib/memories-db.ts | 345 --- src/lib/memory-capture-fixtures.ts | 85 - src/lib/memory-capture.ts | 210 -- src/lib/note-merge.ts | 30 - src/lib/pdf-service.ts | 16 - src/lib/reading-time-utils.ts | 19 - src/lib/research-brief.ts | 372 --- src/lib/rss-db.ts | 236 -- src/lib/rss-parser.ts | 226 -- src/lib/rss-refresh.ts | 109 - src/lib/save-account-notes.ts | 21 - src/lib/shared-ai-budget.test.ts | 111 - src/lib/shared-ai-budget.ts | 136 - src/lib/spa-route.test.ts | 29 +- src/lib/spa-route.ts | 27 +- src/lib/storage.ts | 103 - src/lib/tag-utils.ts | 15 - src/lib/tts.ts | 67 - src/lib/utils.ts | 12 - src/lib/worker-env.ts | 8 - src/pages/AboutPage.tsx | 62 - src/pages/BoardListPage.tsx | 26 - src/pages/BoardPage.tsx | 65 - src/pages/MemoryPage.tsx | 210 -- src/pages/PrivacyPage.tsx | 61 +- src/pages/ReaderPage.tsx | 124 - src/pages/RssPage.tsx | 511 ---- src/pages/SamplePage.tsx | 94 - src/pages/SharedArticlePage.tsx | 54 - src/pages/SharedBoardPage.tsx | 48 - src/pages/WelcomePage.tsx | 142 -- src/router.tsx | 13 - src/styles/globals.css | 260 +- src/types.ts | 173 +- src/worker.test.ts | 4 +- src/worker.ts | 66 +- src/worker/bind-env.ts | 9 - .../routes/__tests__/articles-access.test.ts | 88 +- src/worker/routes/__tests__/mcp.test.ts | 217 +- .../routes/__tests__/misc-snapshot.test.ts | 102 - src/worker/routes/__tests__/rss.test.ts | 95 - src/worker/routes/ai.ts | 250 -- src/worker/routes/articles.ts | 379 +-- src/worker/routes/boards.ts | 119 - src/worker/routes/lists.ts | 108 - src/worker/routes/mcp.ts | 375 ++- src/worker/routes/memories.ts | 87 - src/worker/routes/misc.ts | 388 +-- src/worker/routes/pdf.ts | 129 - src/worker/routes/rss.ts | 150 -- src/worker/routes/share.ts | 45 - tests/login.spec.ts | 19 +- tests/mobile.spec.ts | 148 +- vite.config.ts | 31 +- vitest.account-notes.config.ts | 8 - vitest.config.ts | 2 + 244 files changed, 2116 insertions(+), 31110 deletions(-) delete mode 100644 packages/chrome-extension/side-panel/index.html create mode 100644 packages/chrome-extension/src/__tests__/api.test.ts create mode 100644 packages/chrome-extension/src/api.ts delete mode 100644 packages/chrome-extension/src/background.ts delete mode 100644 packages/chrome-extension/src/content-script.ts delete mode 100644 packages/chrome-extension/src/side-panel/App.tsx delete mode 100644 packages/chrome-extension/src/side-panel/components/Chat.tsx delete mode 100644 packages/chrome-extension/src/side-panel/components/PageHeader.tsx delete mode 100644 packages/chrome-extension/src/side-panel/components/QuickActions.tsx delete mode 100644 packages/chrome-extension/src/side-panel/components/SaveButton.tsx delete mode 100644 packages/chrome-extension/src/side-panel/components/TTSPlayer.tsx delete mode 100644 packages/chrome-extension/src/side-panel/lib/__tests__/importQuality.test.ts delete mode 100644 packages/chrome-extension/src/side-panel/lib/__tests__/types.test.ts delete mode 100644 packages/chrome-extension/src/side-panel/lib/api.ts delete mode 100644 packages/chrome-extension/src/side-panel/lib/importQuality.ts delete mode 100644 packages/chrome-extension/src/side-panel/lib/reading-list-sync.ts delete mode 100644 packages/chrome-extension/src/side-panel/lib/storage.ts delete mode 100644 packages/chrome-extension/src/side-panel/lib/types.ts delete mode 100644 packages/chrome-extension/src/side-panel/main.tsx delete mode 100644 scripts/account-handler-fixture.ts delete mode 100644 scripts/local-ai.mjs delete mode 100644 scripts/memory-capture-demo.ts delete mode 100644 scripts/pdf-browser-fixture.mjs delete mode 100644 scripts/qualify-account-article.test.ts delete mode 100644 scripts/qualify-account-notes.test.ts delete mode 100644 scripts/qualify-account-pdf.mjs delete mode 100644 scripts/qualify-guest-pdf.mjs delete mode 100644 scripts/qualify-import-signin.mjs delete mode 100644 scripts/qualify-local-library.mjs delete mode 100644 src/components/AddArticleDialog.tsx delete mode 100644 src/components/AppearanceToolbar.tsx delete mode 100644 src/components/ArticleCard.tsx delete mode 100644 src/components/ArticleSummary.tsx delete mode 100644 src/components/ArticleTagEditor.tsx delete mode 100644 src/components/ExportDataButton.tsx delete mode 100644 src/components/LibraryEmptyOnboarding.tsx delete mode 100644 src/components/LocalPdfReader.tsx delete mode 100644 src/components/LocalReaderClient.tsx delete mode 100644 src/components/NotesAIChat.tsx delete mode 100644 src/components/PDFReaderClient.tsx delete mode 100644 src/components/PDFViewer.tsx delete mode 100644 src/components/PdfPageNotes.tsx delete mode 100644 src/components/ReaderClient.tsx delete mode 100644 src/components/ReaderView.tsx delete mode 100644 src/components/ResearchBriefPanel.tsx delete mode 100644 src/components/SearchBar.tsx delete mode 100644 src/components/TTSPlayer.tsx delete mode 100644 src/components/TagInput.tsx delete mode 100644 src/components/board/AddWebsiteDialog.tsx delete mode 100644 src/components/board/BoardCanvasClient.tsx delete mode 100644 src/components/board/BoardListClient.tsx delete mode 100644 src/components/board/BoardToolbar.tsx delete mode 100644 src/components/board/ElementPickerPanel.tsx delete mode 100644 src/components/board/ShareDialog.tsx delete mode 100644 src/components/board/edges/LabeledEdge.tsx delete mode 100644 src/components/board/hooks/useBoardArticleSync.ts delete mode 100644 src/components/board/hooks/useBoardAutoSave.ts delete mode 100644 src/components/board/hooks/useBoardData.ts delete mode 100644 src/components/board/nodes/AIChatNode.tsx delete mode 100644 src/components/board/nodes/IframeNode.tsx delete mode 100644 src/components/board/nodes/NoteNode.tsx delete mode 100644 src/components/board/nodes/ReaderNode.tsx delete mode 100644 src/components/board/nodes/WebsiteNode.tsx delete mode 100644 src/components/reader/ArticleShareDialog.tsx delete mode 100644 src/components/reader/NoteCard.tsx delete mode 100644 src/components/reader/NoteMarkerGroup.tsx delete mode 100644 src/components/reader/ReaderCore.tsx delete mode 100644 src/components/reader/SessionReviewPanel.tsx delete mode 100644 src/components/reader/SharedArticleReader.tsx delete mode 100644 src/components/saasmaker-feedback.tsx delete mode 100644 src/components/ui/ShareLinkDialog.tsx delete mode 100644 src/components/ui/badge.tsx delete mode 100644 src/components/ui/dialog.tsx delete mode 100644 src/components/ui/dropdown-menu.tsx delete mode 100644 src/components/ui/label.tsx delete mode 100644 src/components/ui/segmented-control.tsx delete mode 100644 src/hooks/useIsMobileViewport.ts delete mode 100644 src/lib/__fixtures__/browser-memory-snapshots.json delete mode 100644 src/lib/__fixtures__/memory-captures.json create mode 100644 src/lib/__tests__/api-keys.test.ts delete mode 100644 src/lib/__tests__/articles-db-sanitization.test.ts delete mode 100644 src/lib/__tests__/articles-db-search.test.ts delete mode 100644 src/lib/__tests__/browser-memory-import.test.ts delete mode 100644 src/lib/__tests__/category-utils.test.ts create mode 100644 src/lib/__tests__/link-content.test.ts create mode 100644 src/lib/__tests__/links-db.test.ts delete mode 100644 src/lib/__tests__/memories-db.test.ts delete mode 100644 src/lib/__tests__/memory-capture.test.ts delete mode 100644 src/lib/__tests__/note-merge.test.ts delete mode 100644 src/lib/__tests__/reading-time-utils.test.ts delete mode 100644 src/lib/__tests__/research-brief.test.ts delete mode 100644 src/lib/__tests__/rss-parser-performance.test.ts delete mode 100644 src/lib/__tests__/rss-parser.test.ts delete mode 100644 src/lib/__tests__/rss-refresh.test.ts delete mode 100644 src/lib/__tests__/tag-utils.test.ts delete mode 100644 src/lib/ai-cloudflare.test.ts delete mode 100644 src/lib/ai-cloudflare.ts delete mode 100644 src/lib/ai-config.ts delete mode 100644 src/lib/ai-server.ts delete mode 100644 src/lib/ai-vendor-hooks.ts delete mode 100644 src/lib/ai-vendor.ts delete mode 100644 src/lib/annotatable.ts delete mode 100644 src/lib/article-query.ts delete mode 100644 src/lib/articles-db.ts delete mode 100644 src/lib/board-note-sync.ts delete mode 100644 src/lib/boards-db.ts delete mode 100644 src/lib/browser-memory-import.ts delete mode 100644 src/lib/category-utils.ts delete mode 100644 src/lib/import-draft.ts create mode 100644 src/lib/link-content.ts create mode 100644 src/lib/links-db.ts delete mode 100644 src/lib/lists-db.ts delete mode 100644 src/lib/local-library.ts delete mode 100644 src/lib/memories-db.ts delete mode 100644 src/lib/memory-capture-fixtures.ts delete mode 100644 src/lib/memory-capture.ts delete mode 100644 src/lib/note-merge.ts delete mode 100644 src/lib/pdf-service.ts delete mode 100644 src/lib/reading-time-utils.ts delete mode 100644 src/lib/research-brief.ts delete mode 100644 src/lib/rss-db.ts delete mode 100644 src/lib/rss-parser.ts delete mode 100644 src/lib/rss-refresh.ts delete mode 100644 src/lib/save-account-notes.ts delete mode 100644 src/lib/shared-ai-budget.test.ts delete mode 100644 src/lib/shared-ai-budget.ts delete mode 100644 src/lib/storage.ts delete mode 100644 src/lib/tag-utils.ts delete mode 100644 src/lib/tts.ts delete mode 100644 src/pages/AboutPage.tsx delete mode 100644 src/pages/BoardListPage.tsx delete mode 100644 src/pages/BoardPage.tsx delete mode 100644 src/pages/MemoryPage.tsx delete mode 100644 src/pages/ReaderPage.tsx delete mode 100644 src/pages/RssPage.tsx delete mode 100644 src/pages/SamplePage.tsx delete mode 100644 src/pages/SharedArticlePage.tsx delete mode 100644 src/pages/SharedBoardPage.tsx delete mode 100644 src/pages/WelcomePage.tsx delete mode 100644 src/worker/routes/__tests__/misc-snapshot.test.ts delete mode 100644 src/worker/routes/__tests__/rss.test.ts delete mode 100644 src/worker/routes/ai.ts delete mode 100644 src/worker/routes/boards.ts delete mode 100644 src/worker/routes/lists.ts delete mode 100644 src/worker/routes/memories.ts delete mode 100644 src/worker/routes/pdf.ts delete mode 100644 src/worker/routes/rss.ts delete mode 100644 src/worker/routes/share.ts delete mode 100644 vitest.account-notes.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6596a50..43b7c22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,4 @@ jobs: - run: python -m pip install lizard==1.23.0 - run: pnpm quality - run: pnpm exec playwright install --with-deps chromium - - run: pnpm test:local-library - - run: pnpm test:guest-pdf - - run: pnpm test:account-pdf - - run: pnpm test:account-notes + - run: pnpm test:e2e diff --git a/.gitignore b/.gitignore index f0e90f5..dd8f2d1 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,9 @@ dist/ # Private Fleet task evidence .fleet-local/ + +# Local Worker credentials and browser test outputs +.dev.vars +.dev.vars.* +/test-results/ +/playwright-report/ diff --git a/AGENTS.md b/AGENTS.md index 4851356..1d8cb0d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,23 +7,17 @@ ## Purpose -Reader is a personal research library: capture web articles and PDFs, read and -annotate them, organise with tags/lists/boards, search, and AI-chat or -auto-summarise the saved material. Companion Chrome MV3 extension. See -[docs/product/overview.md](docs/product/overview.md). +Reader is a saved-link inbox. Add URLs in the app or Chrome extension; ChatGPT retrieves links and available text and marks them read through MCP. See [docs/product/overview.md](docs/product/overview.md). -## Stack (one-liner) +## Stack -Vite + React 19 SPA (single `app.html` entry) + Hono Worker on Cloudflare -Workers (`src/worker.ts`), Cloudflare D1 via Drizzle ORM, better-auth Google -OAuth, Cloudflare R2 for PDFs, free-ai-gateway + BYOK + local-ai dev bridge. -No SSR, no Next.js, no Firebase. +Vite + React SPA, Hono Cloudflare Worker, D1 via Drizzle, better-auth Google sign-in, and Auth0-backed MCP OAuth. The existing D1 schema and R2 data are preserved. There is no built-in AI, reader, PDF capture, RSS, board, or annotation workflow. ## Essential commands ```bash pnpm install -pnpm dev # Worker (:8787) + Vite SPA (:5173) + local-ai, concurrently +pnpm dev # Worker (:8787) + Vite SPA (:5173), concurrently pnpm dev:worker # wrangler dev only pnpm dev:spa # vite only (proxies /api → 8787) pnpm build # validate env + vite build → dist/ @@ -59,8 +53,7 @@ Full command map: [docs/development/commands.md](docs/development/commands.md). Do not rename without re-provisioning. - **`wrangler.toml` `run_worker_first` list is required** for agent surfaces and `/api/*` to reach the Worker before the `ASSETS` binding. -- **BYOK provider keys live in the browser only** — never persist or log - server-side. `rdr_*` API keys are hashed at rest; plaintext shown once. +- **`rdr_*` API keys are hashed at rest; plaintext shown once.** MCP reads require `reader.read`; read-state writes require `reader.write`. Never treat a browser cookie as an MCP credential. - **Schema changes are additive + deliberate.** Generate and inspect SQL before applying it; read the SQL under `drizzle/` before applying to production. See [docs/operations/runbooks/migrate-schema.md](docs/operations/runbooks/migrate-schema.md). @@ -83,29 +76,17 @@ Full command map: [docs/development/commands.md](docs/development/commands.md). - Runtime agent-indexing surfaces are in [public/](public/); see [docs/product/surfaces.md](docs/product/surfaces.md). -## Repo structure (high level) +## Active source -``` -app.html # Single SPA HTML entry (Vite input) -vite.config.ts # Vite SPA build (React, Tailwind v4, Lightning CSS) -wrangler.toml # Worker config: main=src/worker.ts, ASSETS + PDFS_BUCKET -src/ - worker.ts # Hono Worker entry — security headers, /api/* routing, asset serving - agent-edge.mjs # Generated agent-edge handler (llms.txt, index.md, api/ai) - worker/routes/ # Hono API route modules (articles, boards, lists, ai, keys, pdf, rss, share, memories, misc) - pages/ # Route page components (lazy-loaded via react-router-dom) - components/ # React components (ReaderView, PDFReaderClient, NotesAIChat, board/, reader/, ui/) - hooks/ # Shared React hooks - lib/ # DB, auth, AI, storage, SSRF validation, RSS, memories, etc. -packages/chrome-extension/ # Chrome MV3 extension (separate Vite build) -landing-astro/ # Astro landing page (overlaid into dist/ during cf:build) -docs/ # Canonical documentation (source of truth) -drizzle/ # Migration SQL files + meta -scripts/ # local-ai.mjs, validate-env.mjs, overlay-astro-landing.mjs, check-docs.mjs -public/ # Agent-indexing surfaces (llms.txt, index.md, api-ai.json, robots.txt, sitemap.xml) -``` +- `src/components/HomeClient.tsx`: inbox, URL form, and read-state changes. +- `src/components/ExtensionConnectClient.tsx`: connections and extension keys. +- `src/lib/links-db.ts`: account-scoped link storage over the existing articles table. +- `src/lib/link-content.ts`: bounded web-text retrieval. +- `src/worker/routes/`: links, MCP, keys, and account identity. +- `packages/chrome-extension/`: popup-only URL/title capture. +- `landing-astro/`: landing overlay. -Detailed file map: [docs/architecture/overview.md](docs/architecture/overview.md). +MCP setup and the live verification boundary are in [docs/architecture/overview.md](docs/architecture/overview.md). Legacy schema columns and tables are retained deliberately; do not drop saved data as cleanup. ## Fleet guidance diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md index 9f735ec..e802ff6 100644 --- a/PROJECT_STATUS.md +++ b/PROJECT_STATUS.md @@ -1,111 +1,23 @@ -# PROJECT_STATUS — Reader +# Reader — project status -## Free AI gateway source update — 2 October +## Product scope -Managed AI calls now use the Fleet gateway with canonical `reader` attribution. -Explicit BYOK remains first; production requires the service binding, and -gateway-managed SDK retries are disabled. Existing structured-output parsing, -token limits, and streaming responses are preserved. SDK contract tests and full -local `pnpm quality` pass (152 app tests and 20 extension tests); Cloudflare -build and top-level Wrangler dry-run pass. Pending PR review and -production release; no deployment was performed. Tracked in -[Free AI issue #83](https://github.com/sass-maker/free-ai/issues/83). +Saved links, read/unread state, an add-link form, a one-click Chrome capture extension, and ChatGPT MCP access. Nothing else is in the active product. -This is Reader's durable current and shipped product truth. For the full -product, feature, and architecture record, see [`docs/`](docs/index.md). +## Source implementation -## Why / What +- One account inbox: unread/read/all, title/URL search, pagination, and URL capture. +- Extension popup saves only the active tab’s URL and title. No content script, chat, side panel, or Reading List sync. +- Three MCP tools: `search`, `fetch`, and `set_read`. +- Account isolation and separate OAuth read/write permissions. +- Existing web captures retain their content. No schema migration or saved-data deletion. +- Reader, PDF, annotation, board, RSS, memory, and built-in AI modules removed from the active source. -Reader is a personal research library for capturing, reading, annotating, and -AI-assisted work over saved articles and PDFs. It remains in personal-use, -maintenance-first support. +## Release boundary -## Dependencies +The simplification is a source candidate. Production has not been deployed by this change. +OAuth provider setup and an authenticated ChatGPT retrieval/write-back check remain required for live acceptance. Do not describe the connector as working in production without that evidence. -- Vite + React 19 SPA, Hono Worker, Cloudflare D1 + Drizzle, Cloudflare R2, - better-auth Google OAuth, and optional AI providers. D1 is authoritative; - the retired Turso database was deleted on 2026-08-02. -- Ultracite 7.10.2 is an exact development-only Biome preset dependency. Local - exceptions preserve Reader's established SPA, Worker, Astro, and document - processing style without affecting runtime behavior. +## Operational constraints -## Timeline - -- **2026-09-08:** Repaired Worker dispatch after live session and snapshot GETs - returned discovery `not_found` responses. Product APIs now reach Hono while - `/api/ai` retains discovery GET/HEAD. Entry-point regression tests exercise - session dispatch, protected snapshot/article reads, and discovery. Release - and full hosted qualification remain tracked in - [#55](https://github.com/Significant-Hobbies/reader/issues/55). Guest URL import - now explains sign-in and preserves the URL/category in tab storage for review - after authentication. Restoring a draft never imports automatically; explicit - cancellation clears it. The built-browser regression covers guest handoff, - simulated account return, extraction failure, reload, and cancellation. -- **2026-09-07:** Fixed a reproduced local IndexedDB lost-update bug: concurrent - title and note edits now merge within one readwrite transaction. Isolated - Chromium proves article content/notes/count and synthetic PDF bytes survive - reload; route fixtures verify guest rejection and account-scoped access calls. - [Evidence and limits](docs/development/testing.md#local-library-persistence). - Live journey qualification remains [#55](https://github.com/Significant-Hobbies/reader/issues/55); - guest PDF page notes are now implemented in [#56](https://github.com/Significant-Hobbies/reader/issues/56). - No deployment or live upload was performed. -- **2026-08-12:** Adopted the Fleet code-health contract across the app, - Worker, landing, and Chrome extension with truthful whole-library coverage, - unused-code, cycle, complexity, duplication, dependency, suppression, build, - docs, and repository-hygiene ratchets in CI. Removed the retired Firebase - migration and unused extension/UI surfaces; remaining debt is in GitHub. -- **2026-08-09:** Adopted the verified Ultracite-backed Biome baseline through - the existing non-writing check, with explicit compatibility exceptions and - no source rewrite, production dependency, storage/auth/AI, migration, or - deployment change. -- **2026-07-31:** Kept the public sitemap limited to the four canonical HTML - pages while retaining six machine resources through robots, llms, and the - agent catalog. Explicit tests now enforce sitemap, catalog, and Markdown - parity; production deployment remains separate. -- **2026-07-31:** Added locally verified Open Graph/Twitter image metadata and - SoftwareApplication structured data to the public landing layout; production - deployment remains separate. -- **2026-07-29:** Added an owned `/changelog` with verified release outcomes and - direct GitHub Roadmap and Source links. -- **2026-07-13:** Shipped authenticated RSS/Atom reading and OPML import. - -## Products - -- Public research library at `https://read.significanthobbies.com`. -- Chrome MV3 capture extension. - -## Features (shipped) - -- Guest PDF page notes: local import/render/navigation, note create/edit/delete, - saved page anchors and reload. Existing PDF.js API/worker versions are aligned - to 5.4.624 after a built-browser test exposed a version mismatch. - Notes stay browser-local; they are not text highlights or embedded PDF edits. - Account PDFs now use the same page-note editor with account persistence, - retained page anchors, failed-save draft retention and account-scoped cache/drafts. - A built-browser journey uses real Hono/Drizzle handlers and isolated SQLite to - prove create/edit/delete/reload, a failed save and retry, and Alice/Bob isolation. - Hosted Google/D1/R2 qualification remains #55. Existing background/zoom/page - controls remain supported; mobile panels stack to keep the PDF visible. - -- Account article annotations: cached reopen refreshes clean notes before editing, - autosave runs only for dirty notes and serializes in-flight changes, including - marker reanchoring. Failed writes require retry or a new edit. Account/article - cache keys and reader mounts align. Real-handler/SQLite/browser regression - covers stale-cache data loss, fresh server props during a dirty edit, selection - notes, retry, reanchor, reload/delete and delayed-save account isolation. - Concurrent note saves now merge independent changes with an atomic database comparison. Overlapping edits return a conflict and retain the draft. Linked board notes have stable identities and explicit failed-sync retry; the standalone board canvas has a viewport height. Production qualification remains #55. - -- Articles and PDFs with highlights, notes, search, boards, lists, and - AI-assisted reading. -- Account-backed and device-local capture paths. -- Owned editorial product changelog at `/changelog`. -- HTML-only public sitemap with cataloged Markdown mirrors for agent discovery. -- Exact Ultracite-backed Biome presets with explicit local compatibility - exceptions; `pnpm check` remains non-writing. -- One `pnpm quality` command reproduces the complete hosted code-health gate. - -## Work queue - -Open work is tracked only in [GitHub Issues](https://github.com/Significant-Hobbies/reader/issues). -An open issue is a to-do, a linked pull request is in progress, and merge plus -issue closure makes the work done. +The Worker remains named `reader`. Deployment and migrations require explicit owner approval. Legacy D1 tables and R2 data remain intact. diff --git a/README.md b/README.md index e30ff6a..1beb3c8 100644 --- a/README.md +++ b/README.md @@ -1,297 +1,35 @@ -# Web Annotator +# Reader -**Product:** [read.significanthobbies.com](https://read.significanthobbies.com) +A saved-link inbox for use with ChatGPT. +- Paste a URL in the app or save the current tab with the Chrome extension. +- Search links and keep a simple read/unread state. +- Connect ChatGPT through MCP to find links, retrieve available text, and mark items read or unread. -A modern web application for capturing and annotating articles with a distraction-free reading experience. - -## Deployment & External Services - -| Concern | Service | -| ------------ | -------------------------------------------------------------------------------------------- | -| Hosting | Cloudflare Workers (`reader`) via Hono Worker (`src/worker.ts`) | -| Database | Cloudflare D1 via Drizzle ORM | -| Auth | better-auth + Google OAuth | -| File storage | Cloudflare R2 (`reader-pdfs`, bound as `PDFS_BUCKET`) | -| AI | free-ai-gateway routes managed requests to available providers; explicit BYOK and local AI | -| CI/CD | GitHub Actions checks on push; production deployment is manual | - -## Problem - -Information overload is real. You find valuable articles across the web, but there's no easy way to save them in a clean format, annotate them with your thoughts, and organize them for future reference. Browser bookmarks are cluttered, read-it-later apps lack annotation capabilities, and note-taking tools don't handle web content well. - -Web Annotator solves this by providing a personal research library where you can capture, read, annotate, and organize web content in one place. - -## Features - -### Content Management - -- **Clean Article Extraction**: Save articles from any URL using Mozilla Readability -- **PDF Support**: Guest PDFs render locally with page navigation and page-linked notes. Create, edit, delete, and revisit notes after reload. Notes stay in this browser; they are not text highlights or annotations embedded in the PDF. Account PDFs support page navigation, zoom, viewer background, Listen, and an AI chat entry. Account PDFs also support page-note create/edit/delete and reopen, verified locally against real article handlers and an isolated database. Notes are saved to the account; they are page references, not embedded PDF edits. No placeholder note tab or ineffective typography controls are shown. -- **Rich Annotations**: Add contextual notes with optional DOM anchoring -- **Selection Actions**: After selecting text (mouse up) or selection + right-click, quickly choose `Add note` or `Ask AI` -- **Reading Time Estimates**: Auto-calculated reading time displayed for every article - -### Organization & Discovery - -- **Tags System**: Multi-tag articles with color-coded badges, autocomplete, and filtering -- **Full-Text Search**: Search across article content, notes, and AI chat history with Cmd/Ctrl+K shortcut -- **Project Organization**: Group related articles into projects -- **Reading Progress**: Track which articles you're reading or have completed - -### AI-Powered Features - -- **AI Chat**: Ask questions about your articles and notes using BYOK providers (OpenAI, Anthropic, Gemini, Gateway) or local AI mode -- **Auto-Summaries**: Generate intelligent summaries with one click (short/medium/long options) -- **Key Points Extraction**: Automatically extract 3-5 key takeaways from any article -- **Chat History**: Persistent per-article conversations rendered as markdown - -### Customization - -- **Customizable Reader**: Adjust theme (light/dark/sepia), font family (sans/serif/mono), and text size -- **Secure & Private**: Google Sign-In authentication with per-user data isolation - -## Architecture - -```mermaid -graph TB - subgraph "Client Layer" - UI[React 19 + Vite SPA Frontend] - UI --> |Tailwind CSS| Styling[UI Components] - UI --> |React Query| State[State Management] - end - - subgraph "API Layer" - API["Hono API Routes (/api/*)"] - API --> Articles["articles"] - API --> Projects["projects"] - API --> Auth["auth"] - API --> AI["ai"] - API --> Search["search"] - API --> Tags["tags"] - API --> PDF["pdf"] - API --> Snapshot["snapshot"] - end - - subgraph "Backend Services" - D1[Cloudflare D1] - D1 --> Drizzle[Drizzle ORM] - D1 --> BetterAuth[better-auth - Google OAuth] - - R2[Cloudflare R2 - PDFS_BUCKET] - - External[External Services] - External --> Readability[Mozilla Readability] - External --> AIProviders[AI Providers] - AIProviders --> OpenAI[OpenAI] - AIProviders --> Anthropic[Anthropic] - AIProviders --> Gemini[Google Gemini] - AIProviders --> Gateway[Custom Gateway] - AIProviders --> LocalAI[Local AI] - end - - UI --> API - API --> D1 - API --> R2 - API --> External - - classDef frontend fill:#3b82f6,stroke:#1e40af,color:#fff - classDef backend fill:#10b981,stroke:#047857,color:#fff - classDef external fill:#f59e0b,stroke:#d97706,color:#fff - - class UI,Styling,State frontend - class API,Articles,Projects,Auth,AI,Search,Tags,PDF,Snapshot,D1,Drizzle,BetterAuth,R2 backend - class External,Readability,AIProviders,OpenAI,Anthropic,Gemini,Gateway,LocalAI external -``` - -### Tech Stack - -- **Frontend**: Vite + React 19 SPA (single `app.html` entry, client-side routing via `react-router-dom`), TypeScript, Tailwind CSS v4 -- **Database**: Cloudflare D1 via Drizzle ORM -- **Auth**: better-auth (Google OAuth, Drizzle adapter) -- **Storage**: Cloudflare R2 (PDFs) via Workers binding -- **AI Integration**: Vercel AI SDK + AI Gateway (preferred), BYOK chat providers, local AI support -- **PDF Processing**: react-pdf, pdfjs-dist, pdf-parse for viewing and text extraction -- **Deployment**: Cloudflare Workers via `wrangler deploy` (Hono worker `src/worker.ts`; built SPA served via `ASSETS` binding) - -## Getting Started - -### Prerequisites - -- Node.js 22+ -- Wrangler-managed local D1 (configured in `wrangler.local.toml`) -- A Cloudflare account with an R2 bucket bound as `PDFS_BUCKET` -- A Google OAuth client (Cloud Console > APIs & Services > Credentials) - -### Installation - -1. Clone the repository and install dependencies: - - ```bash - git clone - cd web-annotator - pnpm install - ``` - -2. Configure environment variables: - - ```bash - cp .env.example .env.local - ``` - - Edit `.env.local`: - - ```env - # better-auth - BETTER_AUTH_SECRET=$(openssl rand -base64 32) - BETTER_AUTH_URL=http://localhost:8787 - GOOGLE_CLIENT_ID=... - GOOGLE_CLIENT_SECRET=... - - # Cloudflare R2 (used by `pnpm deploy`; local dev uses the wrangler binding) - CLOUDFLARE_ACCOUNT_ID=... - R2_ACCESS_KEY_ID=... - R2_SECRET_ACCESS_KEY=... - R2_BUCKET_NAME=reader-pdfs - - # Optional - LOCAL_AI_URL=http://127.0.0.1:3456 - ``` - -3. Apply the schema to local D1: - - ```bash - pnpm db:migrate:local - ``` - -4. Run the development server: - - ```bash - pnpm dev - ``` - - `pnpm dev` starts the Hono Worker (port 8787), the Vite SPA dev server (port 5173, proxies `/api` → 8787), and the local AI server concurrently. - Local AI providers are shown only in development mode. - If you only want the SPA: - - ```bash - pnpm dev:spa - ``` - -5. Open [http://localhost:8787](http://localhost:8787) (Worker-served app) or [http://localhost:5173](http://localhost:5173) (Vite SPA only) - -### Development Commands - -```bash -pnpm dev # Start Worker + Vite SPA + local AI server (concurrently) -pnpm dev:worker # wrangler dev only (Worker, port 8787) -pnpm dev:spa # Vite SPA only (port 5173, proxies /api → 8787) -pnpm local-ai # Start only the local AI server -pnpm build # Validate env + Vite build → dist/ -pnpm cf:build # Build SPA + Astro landing + overlay into dist/ -pnpm deploy # validate env + cf:build + wrangler deploy -pnpm lint # Run ESLint -pnpm format # Format code with Biome -pnpm typecheck # tsc --noEmit (app + worker tsconfigs) -pnpm db:generate # Generate a tracked D1 migration -pnpm db:migrate:local # Apply migrations to local D1 only -``` - -## Deployment - -### Cloudflare Workers (Hono Worker) - -```bash -pnpm deploy -``` - -This runs `cf:build` (Vite SPA build + Astro landing overlay into `dist/`) and `wrangler deploy`. -Configure secrets via `wrangler secret put` for `BETTER_AUTH_SECRET`, -`GOOGLE_CLIENT_SECRET`, etc., and bind D1 as `DB` plus R2 as `PDFS_BUCKET` in -`wrangler.toml`. - -## Project Structure - -``` -web-annotator/ -├── app.html # Single SPA HTML entry (Vite input) -├── vite.config.ts # Vite SPA build (React, Tailwind v4, Lightning CSS) -├── wrangler.toml # Worker config: main=src/worker.ts, ASSETS + PDFS_BUCKET -├── src/ -│ ├── worker.ts # Hono Worker entry — /api/* routing, asset serving -│ ├── worker/ -│ │ └── routes/ # Hono API route modules (articles, ai, pdf, auth, etc.) -│ ├── pages/ # Route page components (LibraryPage, ReaderPage, etc.) -│ ├── components/ # React components (ReaderView, PDFReaderClient, etc.) -│ ├── hooks/ # Shared React hooks -│ ├── lib/ -│ │ ├── auth.ts # better-auth server config -│ │ ├── auth-client.ts# better-auth browser client -│ │ ├── db/ # Drizzle schema + D1 client -│ │ └── storage.ts # R2 helpers -│ └── types.ts # TypeScript definitions -├── packages/ -│ └── chrome-extension/ # Chrome MV3 extension (separate Vite build) -├── landing-astro/ # Astro landing page (built into deploy via cf:build) -└── agents.md # Development guide -``` +Vite + React, a Hono Cloudflare Worker, D1, and Google sign-in. No built-in AI, article reader, PDF uploads, boards, annotations, memories, or RSS. ## Development -This project uses automated pre-commit hooks for code quality: - -- Prettier (formatting) -- ESLint (linting) -- TypeScript (type checking) - -Commit convention follows [Conventional Commits](https://www.conventionalcommits.org/): - +```sh +pnpm install +pnpm dev +pnpm quality +pnpm cf:build +pnpm test:e2e ``` -feat(reader): add PDF export -fix(auth): resolve token refresh issue -chore: update dependencies -``` - -For comprehensive development documentation, see [AGENTS.md](./AGENTS.md). - -## Security - -- All HTML content is sanitized before storage -- User authentication required for all operations -- Per-user data isolation enforced at the database level -- Ownership verification on all operations -- BYOK model for AI providers (API keys stored in browser only) - -## License - -This project is private and not licensed for public use. - +The extension is built with `pnpm --filter web-annotator-extension build` and loaded from `packages/chrome-extension/dist` as an unpacked Chrome extension. Create a key in Reader’s Connections page, paste it into the popup once, then click Save link. -## Task reconciliation (2026-09-07) +## MCP -The initial audit found no prior open GitHub Issues or PRs. -Remaining work is [#55: actual import/read/annotate/reopen qualification](https://github.com/Significant-Hobbies/reader/issues/55). -Account article selection notes now have a real-handler browser receipt for create/retry/edit/reanchor/reload/delete and account isolation. Cached reopen refreshes clean notes; pending writes preserve newer drafts. Note saves merge independent changes against the editor's original snapshot; overlapping edits preserve the server version and the draft for explicit comparison. See [the save contract and qualification limits](docs/development/testing.md#concurrent-note-saves). -[#56: guest PDF page notes](https://github.com/Significant-Hobbies/reader/issues/56) is implemented with a built-browser synthetic import/render/note/reload/edit/delete journey. -These preserve the full product journey; local persistence tests are not a -hosted shareability receipt. See [testing evidence and limits](docs/development/testing.md#local-library-persistence). +The stateless Streamable HTTP endpoint is `/api/mcp`. Its three tools are `search`, `fetch`, and `set_read`. Fetching never marks an item read. Unavailable source text is reported explicitly. -### Historical Active AI task log +Google-backed Auth0 OAuth maps the connection to the same Reader account. Reads require `reader.read`; read-state changes require `reader.write`. Existing extension keys remain valid. See [the architecture and connection setup](docs/architecture/overview.md). -This section is maintained by the SaaS Maker Active-AI product/design loop so future agents do not reopen duplicate UI tasks. +## Existing data and rollout -- Business lane: P0 Can make money -- Rule: do not create another broad "improve the UI" task unless the acceptance criteria differ materially from the tasks listed here. -- Source of truth for current task status: this repository's GitHub Issues. The historical rows below retain earlier reports, not fresh runtime qualification. +The database schema and saved data remain unchanged. Legacy web articles appear as links and their captured content remains available through MCP. Local browser data and stored PDFs are not deleted. -| Task | Status | Priority | Last known note | -| ----------------------------------------------------------------------- | ------ | -------- | ------------------- | -| `cad24fee` reader: add empty-source import checklist | done | medium | 2026-05-26 | -| `c346ed01` reader: add annotation export preview before signup | done | high | 2026-05-26 | -| `87ef7ce1` reader: add sample reading loop proof above the fold | done | high | 2026-05-26 | -| `907a1c6e` reader: review and ship local first-run UI change | done | high | 2026-05-25 18:52:12 | -| `07045aff` reader: library empty state should explain value + focus CTA | done | high | 2026-05-25 17:07:15 | -| `0babffde` reader: make mobile import CTA impossible to miss | done | medium | 2026-05-27 | +This simplification requires a manual deployment and OAuth configuration before it can be used in ChatGPT. Source verification is separate from deployment and an authenticated ChatGPT end-to-end check. - +[Documentation](docs/index.md) · [Current status](PROJECT_STATUS.md) diff --git a/STATUS.md b/STATUS.md index 5aa135e..92c6976 100644 --- a/STATUS.md +++ b/STATUS.md @@ -1,5 +1,5 @@ -# Status +# Reader status -This legacy filename is retained as a compatibility pointer. Durable current and -shipped product truth lives in [PROJECT_STATUS.md](PROJECT_STATUS.md). Open work -is tracked only in [GitHub Issues](https://github.com/Significant-Hobbies/reader/issues). +Reader is being reduced to a saved-link inbox with a Chrome capture extension and ChatGPT MCP retrieval/read-state updates. + +Source scope and the rollout boundary are recorded in [PROJECT_STATUS.md](PROJECT_STATUS.md). Deployment and live OAuth/ChatGPT verification are separate from local checks. diff --git a/app.html b/app.html index ff476e3..de73912 100644 --- a/app.html +++ b/app.html @@ -3,326 +3,15 @@ - - Library Reader — save, read, highlight, and listen - - - - - - - - - - + + Reader — your saved-link inbox + - - - - - - - - - - -
- - - - - - - -
+ + + +
Loading Reader…
+ diff --git a/biome.json b/biome.json index 95b05e3..d8f06e7 100644 --- a/biome.json +++ b/biome.json @@ -5,7 +5,11 @@ "ultracite/biome/react", "ultracite/biome/vitest" ], - "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }, + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, "files": { "ignoreUnknown": true, "includes": [ @@ -35,11 +39,23 @@ "lineEnding": "lf" }, "css": { - "formatter": { "enabled": false }, - "parser": { "tailwindDirectives": true } + "formatter": { + "enabled": false + }, + "parser": { + "tailwindDirectives": true + } + }, + "html": { + "formatter": { + "enabled": false + } + }, + "json": { + "formatter": { + "enabled": false + } }, - "html": { "formatter": { "enabled": false } }, - "json": { "formatter": { "enabled": false } }, "javascript": { "formatter": { "quoteStyle": "single", @@ -106,7 +122,9 @@ "useOptionalChain": "off", "useSimplifiedLogicExpression": "off" }, - "nursery": { "useSortedClasses": "off" }, + "nursery": { + "useSortedClasses": "off" + }, "performance": { "noAwaitInLoops": "off", "noDelete": "off", @@ -155,5 +173,20 @@ "useSortedProperties": "off" } } - } + }, + "overrides": [ + { + "includes": [ + "**/*.astro" + ], + "linter": { + "rules": { + "correctness": { + "noUnusedImports": "off", + "noUnusedVariables": "off" + } + } + } + } + ] } diff --git a/docs/architecture/data-flow.md b/docs/architecture/data-flow.md index b06fd1e..98ef0e1 100644 --- a/docs/architecture/data-flow.md +++ b/docs/architecture/data-flow.md @@ -1,3 +1,5 @@ +> Historical context from before the saved-link simplification. For the active product and setup, see [architecture](overview.md). + # Data Flow How a request moves through the system. Read alongside diff --git a/docs/architecture/decisions/0001-vite-spa-hono-worker.md b/docs/architecture/decisions/0001-vite-spa-hono-worker.md index 9d8d41f..bf40f40 100644 --- a/docs/architecture/decisions/0001-vite-spa-hono-worker.md +++ b/docs/architecture/decisions/0001-vite-spa-hono-worker.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0001: Vite + React 19 SPA + Hono Worker (migrate off Next.js + OpenNext) **Date:** ~2026-05 (Wave 2 migration landed; Worker name `reader` preserved) diff --git a/docs/architecture/decisions/0002-turso-drizzle.md b/docs/architecture/decisions/0002-turso-drizzle.md index 1d03908..5db2198 100644 --- a/docs/architecture/decisions/0002-turso-drizzle.md +++ b/docs/architecture/decisions/0002-turso-drizzle.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0002: Turso (libSQL) via Drizzle ORM **Date:** 2026-04-25 (Firebase → Turso migration); carried forward post-Vite migration diff --git a/docs/architecture/decisions/0003-r2-pdfs.md b/docs/architecture/decisions/0003-r2-pdfs.md index 7a5663b..a72b0bb 100644 --- a/docs/architecture/decisions/0003-r2-pdfs.md +++ b/docs/architecture/decisions/0003-r2-pdfs.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0003: Cloudflare R2 for PDF Storage **Date:** 2026-04-25 (migrated from GCS/Firebase Storage); native binding adopted 2026-04-27 diff --git a/docs/architecture/decisions/0004-better-auth-google.md b/docs/architecture/decisions/0004-better-auth-google.md index f42756e..31ac2ce 100644 --- a/docs/architecture/decisions/0004-better-auth-google.md +++ b/docs/architecture/decisions/0004-better-auth-google.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0004: better-auth (Google OAuth via Drizzle Adapter) **Date:** 2026-04-25 (replaced Firebase Auth; brief Auth.js v5 detour settled on better-auth) diff --git a/docs/architecture/decisions/0005-ai-gateway-byok.md b/docs/architecture/decisions/0005-ai-gateway-byok.md index 5de2705..e9f924e 100644 --- a/docs/architecture/decisions/0005-ai-gateway-byok.md +++ b/docs/architecture/decisions/0005-ai-gateway-byok.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0005: AI SDK + free-ai-gateway + BYOK (no server-side key storage) **Date:** 2026-02-13 (AI SDK integrated); gateway pattern formalised ~2026-04-27 diff --git a/docs/architecture/decisions/0006-mv3-side-panel.md b/docs/architecture/decisions/0006-mv3-side-panel.md index a18ab8d..12b974c 100644 --- a/docs/architecture/decisions/0006-mv3-side-panel.md +++ b/docs/architecture/decisions/0006-mv3-side-panel.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0006: Chrome MV3 Side Panel + hashed `rdr_*` API keys **Date:** 2026-04-04 (extension scaffolded with side panel from the start) diff --git a/docs/architecture/decisions/0007-content-extraction.md b/docs/architecture/decisions/0007-content-extraction.md index 4ecc49e..f349589 100644 --- a/docs/architecture/decisions/0007-content-extraction.md +++ b/docs/architecture/decisions/0007-content-extraction.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0007: Content Extraction Stack **Date:** 2026-02-13 (`linkedom` adopted replacing Playwright); pdfjs added 2026-02-14 diff --git a/docs/architecture/decisions/0008-rss-inbox.md b/docs/architecture/decisions/0008-rss-inbox.md index 673e3e5..877480a 100644 --- a/docs/architecture/decisions/0008-rss-inbox.md +++ b/docs/architecture/decisions/0008-rss-inbox.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0008: RSS/Atom Inbox (manual refresh, no scheduled triggers) **Date:** 2026-07-13 diff --git a/docs/architecture/decisions/0010-cloudflare-d1.md b/docs/architecture/decisions/0010-cloudflare-d1.md index 699a5ec..06c8555 100644 --- a/docs/architecture/decisions/0010-cloudflare-d1.md +++ b/docs/architecture/decisions/0010-cloudflare-d1.md @@ -1,3 +1,5 @@ +> Historical decision from the previous research-library product. See [current architecture](../overview.md). + # ADR-0010: Cloudflare D1 for structured data **Status:** Accepted for migration; production cutover remains operator-gated. diff --git a/docs/architecture/how-it-works.md b/docs/architecture/how-it-works.md index 268777a..e3318da 100644 --- a/docs/architecture/how-it-works.md +++ b/docs/architecture/how-it-works.md @@ -1,3 +1,5 @@ +> Historical context from before the saved-link simplification. For the active product and setup, see [architecture](overview.md). + --- title: "How Reader Works, End to End" description: "A code-grounded walkthrough of Reader's components and the primary flow: capture an article, read and annotate it, then chat with it." diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index b7a7b07..58b1f31 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -1,94 +1,37 @@ -# Architecture Overview +# Architecture -Reader is a Vite + React 19 single-page application served from a Hono Worker -on Cloudflare Workers. No SSR, no Next.js. The browser loads `app.html` (one -Vite entry) and routes client-side via `react-router-dom`; the Worker handles -`/api/*` and serves built assets via the `ASSETS` binding. +Reader is a Vite/React SPA backed by a Hono Worker and Cloudflare D1. The Astro landing is overlaid into the same build. Google sign-in uses better-auth. Existing database tables and R2 data are retained unchanged. -## Shape +## Active paths -``` - ┌──────────────────────── Cloudflare Worker (reader) ────────────────────────┐ - │ │ - browser ──────► src/worker.ts │ - │ ├── handleAgentEdge(request) ← /llms.txt, /index.md, /api/ai, … │ - │ ├── api.fetch() ← Hono router under /api/* │ - │ │ ├── /api/auth/* ← better-auth (Google OAuth, Drizzle) │ - │ │ ├── /api/articles ← articles.ts │ - │ │ ├── /api/boards ← boards.ts │ - │ │ ├── /api/lists ← lists.ts │ - │ │ ├── /api/memories ← memories.ts │ - │ │ ├── /api/ai ← ai.ts (chat / summarize / models) │ - │ │ ├── /api/keys ← keys.ts (rdr_* API keys) │ - │ │ ├── /api/pdfs ← pdf.ts (R2-backed) │ - │ │ ├── /api/rss ← rss.ts (feeds + entries + OPML) │ - │ │ ├── /api/share ← share.ts (public share) │ - │ │ └── /api/* ← misc.ts (search, tags, snapshot, proxy, │ - │ │ data-export, ext chat, browser-mem)│ - │ └── env.ASSETS.fetch() ← built SPA + landing (dist/) │ - │ │ - │ Bindings: DB (D1), PDFS_BUCKET (R2), ASSETS (dist/) │ - └────────────────────────────────┬─────────────────────────────────────────┘ - │ - ┌──────────────────────────────┼──────────────────────────────┐ - ▼ ▼ ▼ - Cloudflare D1 Cloudflare R2 free-ai-gateway - via Drizzle ORM reader-pdfs bucket (AI_BASE_URL) - (articles, boards, (PDF binaries, + BYOK providers - lists, memories, rss, proxied downloads) + local-ai (dev) - api_keys, better-auth) -``` +- `src/components/HomeClient.tsx`: the link inbox and URL form. +- `src/components/ExtensionConnectClient.tsx`: extension keys and MCP connection information. +- `src/lib/links-db.ts`: account-scoped capture, search, pagination, retrieval, and read states over the existing `articles` table. +- `src/lib/link-content.ts`: bounded source-text extraction with URL and redirect validation. +- `src/worker/routes/articles.ts`: `/api/links`; `/api/articles` is a compatibility alias for capture clients. +- `src/worker/routes/mcp.ts`: stateless JSON-RPC over Streamable HTTP at `/api/mcp`. +- `packages/chrome-extension/src/popup`: explicit current-tab capture. No background worker or content script. -## Key files +New links store URLs and titles. Existing web articles retain captured text. `in_progress` in legacy storage maps to `unread`; `read` remains `read`. New IDs are a deterministic hash of account and normalized URL to deduplicate concurrent captures without a migration. Fragments are removed; query parameters remain intact. -- `src/worker.ts` — Hono Worker entry. Security headers, `/api/*` routing, - asset serving, SPA fallback, agent-edge handler. -- `src/worker/routes/*.ts` — one Hono router per resource; mounted under - `/api/`. -- `src/lib/db/schema.ts` — Drizzle schema (app tables + better-auth tables + - legacy NextAuth tables kept for reference). -- `src/lib/db/client.ts` — D1 Drizzle client. Lazy proxy so the client is - not created at module load (required for the Workers runtime). -- `src/lib/auth.ts` — better-auth server config (`createAuth`), Drizzle - adapter, Google OAuth, `oneTap` plugin, rate limiting disabled. -- `src/lib/auth-api.ts` — `getAuthenticatedUserId()` resolves either a - `Bearer rdr_*` API key (extension) or a better-auth session cookie (web). -- `src/lib/storage.ts` — R2 helpers for `PDFS_BUCKET`. -- `src/lib/ai-cloudflare.ts` — builds a `LanguageModel` from an OpenAI-compatible - endpoint, routed through the free-ai gateway with `x-gateway-project-id: reader`. -- `src/lib/url-validation.ts` + `src/lib/safe-fetch.ts` — SSRF protection and - redirect-safe fetch used by snapshot/proxy/RSS refresh. -- `src/router.tsx` — client-side routes (lazy-loaded pages). -- `wrangler.toml` — Worker config: `main = src/worker.ts`, `DB` + `ASSETS` + `PDFS_BUCKET` - bindings, `placement.mode = "smart"`, `nodejs_compat_v2`, custom domain. -- `vite.config.ts` — Vite SPA build (React, Tailwind v4, Lightning CSS). -- `app.html` — single SPA HTML entry (Vite input; carries inline shell CSS). +MCP reads do not change read state. The `set_read` tool requires a boolean and a write-authorized credential. Every storage operation is account-scoped. MCP source content is data, never instructions. -## Build & deploy pipeline +## ChatGPT connection setup -``` -pnpm deploy - → validate:env:deploy (scripts/validate-env.mjs) - → cf:build - → pnpm build (validate env + vite build → dist/) - → pnpm --filter ./landing-astro build - → node scripts/overlay-astro-landing.mjs (overlay landing → dist/) - → wrangler deploy (Worker + ASSETS binding serves dist/) -``` +The source endpoint is `https://read.significanthobbies.com/api/mcp`. Live use requires an approved deployment and provider configuration; adding an endpoint to the code does not provision OAuth. -The landing page (`landing-astro/`) is an **overlay**, not a separate product. -It overwrites `dist/index.html` and merges `_headers`; the SPA lives at -`dist/app.html` and is served at `/app`. SPA fallback uses -`not_found_handling = single-page-application` semantics via the Worker's -explicit fallback to `/app`. +Use the existing Google-backed Auth0 integration: -## Decisions +1. Configure a resource/API identifier equal to the direct MCP endpoint. Set `AUTH0_ISSUER` to the exact Auth0 issuer with a trailing slash and `AUTH0_MCP_AUDIENCE` to the endpoint identifier. +2. Define and grant `reader.read` and `reader.write`. Tokens must use RS256, the exact issuer and audience, the stable `google-oauth2|` identity, and a lifetime of at most one hour. +3. Configure an OAuth authorization-code client with PKCE S256 for ChatGPT. Use the exact redirect URI shown by ChatGPT’s connection-management page; do not guess it. Ensure the provider honors the OAuth resource parameter in the access-token audience and advertises S256 in discovery. +4. Add a custom MCP connection in ChatGPT with OAuth and this server URL. Static OAuth client credentials can be supplied through ChatGPT’s connection UI when the provider does not support dynamic registration. +5. Sign in to Reader first with the same Google account. Then verify listing unread links, fetching a saved item, marking it read, and observing the updated inbox. -The why behind this shape is in [decisions/](decisions/). Start with -[0001-vite-spa-hono-worker.md](decisions/0001-vite-spa-hono-worker.md) for the -migration off Next.js + OpenNext. +The linking challenge points to `/api/mcp/.well-known/oauth-protected-resource`, keeping discovery inside the existing Worker-first API routing. A standard alias also exists at `/.well-known/oauth-protected-resource/api/mcp`. The tools declare their OAuth scopes and return linking challenges. Read-only tokens never gain write access. The older `/reader/mcp` audience and `/api/mcp/reading` projections remain compatible with the existing external bridge; adapting that bridge’s tool catalog is separate from this repository. -## Data flow +Official references: [ChatGPT custom MCP connections](https://developers.openai.com/api/docs/guides/custom-mcp-server), [OAuth requirements](https://developers.openai.com/plugins/build/auth), [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports). -See [data-flow.md](data-flow.md) for the request lifecycle, auth resolution, -storage paths, and AI routing. +## Rollout + +No database migration or saved-data removal is needed. Worker name, production bindings, and secrets remain unchanged. Deploy and provider/account changes require owner approval. Test an authenticated ChatGPT connection after deployment before calling the live workflow complete. diff --git a/docs/development/commands.md b/docs/development/commands.md index f130dfb..ef5f57c 100644 --- a/docs/development/commands.md +++ b/docs/development/commands.md @@ -1,65 +1,24 @@ # Commands -Source of truth: `scripts` in `package.json`. This page annotates intent and -ordering; run `pnpm run` to see the live list. - -## Web app (root workspace) - -| Command | Purpose | -| --- | --- | -| `pnpm dev` | Worker (`wrangler dev`, :8787) + Vite SPA (:5173) + `local-ai.mjs`, concurrently | -| `pnpm dev:worker` | `wrangler dev` only (Worker, :8787) | -| `pnpm dev:spa` | `vite` only (SPA dev server, :5173, proxies `/api` → 8787) | -| `pnpm local-ai` | Local AI bridge (`scripts/local-ai.mjs` spawns `../local-ai/index.mjs` or legacy `../cli-bridge/index.mjs`) | -| `pnpm cli-bridge` | Alias for `pnpm local-ai` | -| `pnpm build` | `validate-env.mjs build` + `vite build` → `dist/` | -| `pnpm cf:build` | `pnpm build` + `landing-astro` build + `overlay-astro-landing.mjs` | -| `pnpm preview` | `vite preview` | -| `pnpm deploy` | `validate:env:deploy` + `cf:build` + `wrangler deploy` | -| `pnpm lint` | `biome check .` | -| `pnpm type-check` / `pnpm typecheck` | `tsc --noEmit -p tsconfig.app.json` + `tsc --noEmit -p tsconfig.worker.json` | -| `pnpm validate:env:build` | `node scripts/validate-env.mjs build` | -| `pnpm validate:env:runtime` | `node scripts/validate-env.mjs runtime` | -| `pnpm validate:env:deploy` | `node scripts/validate-env.mjs deploy` | -| `pnpm test` | `vitest run` | -| `pnpm test:watch` | `vitest` | -| `pnpm test:coverage` | `vitest run --coverage` | -| `pnpm quality` | Complete CI code-health gate across the app, Worker, landing, and extension | -| `pnpm test:e2e` | `playwright test` | -| `pnpm memory:demo` | `tsx scripts/memory-capture-demo.ts` | -| `pnpm db:generate` | Generate a tracked D1 migration from `src/lib/db/schema.ts` | -| `pnpm db:migrate:local` | Apply tracked migrations to isolated local D1 | -| `pnpm db:migrate:remote` | Explicitly apply tracked migrations to the configured remote D1 | -| `pnpm prepare` | `husky` (installs pre-commit hook) | -| `pnpm format` | `biome format --write .` | -| `pnpm format:check` | `biome format .` | -| `pnpm check` | `biome check .` | -| `pnpm docs:check` | `node scripts/check-docs.mjs` — validate docs/ links + structure | - -## Chrome extension (`packages/chrome-extension/`) - -Separate Vite build; excluded from root Biome/ESLint tooling. +Use pnpm and the tracked lockfile. | Command | Purpose | | --- | --- | -| `pnpm dev` | `vite build --watch` → `dist/` | -| `pnpm build` | `vite build` (production) | -| `pnpm type-check` | `tsc --noEmit` | -| `pnpm test` | `vitest run` | -| `pnpm pack:zip` | `pnpm build` + zip `dist/` → `web-annotator-extension-.zip` | - -## Landing (`landing-astro/`) - -| Command | Purpose | -| --- | --- | -| `pnpm dev` | `astro dev` | -| `pnpm build` | `astro build` → `landing-astro/dist/` (overlaid onto `dist/` by `cf:build`) | -| `pnpm preview` | `astro preview` | - -## Build pipeline ordering - -``` -pnpm build = validate-env(build) → vite build -pnpm cf:build = pnpm build → landing-astro build → overlay-astro-landing.mjs -pnpm deploy = validate-env(deploy) → cf:build → wrangler deploy -``` +| `pnpm dev` | Worker and Vite concurrently | +| `pnpm dev:worker` | Local Worker | +| `pnpm dev:spa` | SPA with API proxy to the Worker | +| `pnpm build` | SPA production build | +| `pnpm cf:build` | SPA plus Astro landing overlay | +| `pnpm typecheck` | App and Worker TypeScript checks | +| `pnpm test` | Unit and storage tests | +| `pnpm test:coverage` | Unit tests and coverage gates | +| `pnpm test:e2e` | Built-browser inbox checks at phone, tablet, and desktop widths | +| `pnpm quality` | Complete local/CI gate, including extension checks and builds | +| `pnpm lint` | Biome through the code-health wrapper | +| `pnpm docs:check` | Documentation links and structure | + +Build with `pnpm cf:build` before running `pnpm test:e2e`. Browser tests use synthetic accounts and links; no production data is changed. + +Extension: `pnpm --filter web-annotator-extension build`, `type-check`, or `test`. + +Deployment remains manual and needs owner approval. Schema commands remain available for deliberate, approved migration work, but the saved-link simplification requires none. diff --git a/docs/development/setup.md b/docs/development/setup.md index c8a7a83..855a61e 100644 --- a/docs/development/setup.md +++ b/docs/development/setup.md @@ -1,3 +1,5 @@ +> Historical context from before the saved-link simplification. For the active product and setup, see [architecture](../architecture/overview.md). + # Development Setup ## Prerequisites diff --git a/docs/development/testing.md b/docs/development/testing.md index eb1854b..a004343 100644 --- a/docs/development/testing.md +++ b/docs/development/testing.md @@ -1,193 +1,15 @@ # Testing -## Vitest (unit) +`pnpm quality` is the complete source gate. It includes TypeScript, lint, coverage, dependency/code-health checks, documentation checks, the combined app/landing build, and extension checks/build. -- Config: `vitest.config.ts`. -- Run: `pnpm test` (one-shot) or `pnpm test:watch`. -- Coverage: `pnpm test:coverage`. -- DOM env: `happy-dom`. -- Test discovery: `src/lib/**/__tests__/**/*.test.ts` and - `src/worker/routes/__tests__/**/*.test.ts`. -- Examples: `src/lib/__tests__/browser-memory-import.test.ts`, - `src/lib/__tests__/category-utils.test.ts`, - `src/lib/__tests__/memory-capture.test.ts`, - `src/worker/routes/__tests__/` (route-level tests). +Unit tests exercise real in-memory SQLite storage for account isolation, duplicate saves, literal title/URL searches, pagination, preserved legacy content, and read/unread state. They do not use the owner’s databases or apply migrations. -Coverage includes the complete `src/lib/**/*.{ts,tsx}` denominator. The -ratchet starts at the result the suite proves: 37% lines, 35% functions, 28% -branches, and 34% statements. Thresholds may move up, never silently down. +MCP route tests verify protocol initialization, the three-tool catalog, retrieval without read-state changes, explicit boolean writes, missing credentials, write scopes, hostile Origins, missing items, and unavailable source content. Signed JWT fixtures verify read-only tokens cannot write. -## Playwright (e2e) +Source extraction tests cover SSRF rejection, bounded response streams, supported content types, and extraction failure. -- Config: `playwright.config.ts`. -- Run: `pnpm test:e2e`. -- Specs: `tests/login.spec.ts`, `tests/mobile.spec.ts`. -- `PLAYWRIGHT_BROWSERS_PATH=0` is recommended in serverless environments (see - `.env.example`). +Run `pnpm cf:build` and then `pnpm test:e2e` to check the built inbox and landing at phone, tablet, and desktop widths. Synthetic API responses cover URL capture, search, read/unread transitions, and the guest sign-in boundary. Screenshots stay in the ignored `.fleet-local/screenshots/` directory. -## Local library persistence +The extension has a separate test runner. API tests verify its retained key slot, authenticated URL/title capture, and rejection when no connection exists. -`pnpm test:local-library` launches isolated Playwright Chromium and serves only -synthetic in-memory responses. It runs the actual `local-library.ts` module with -real IndexedDB and FileReader, saves a synthetic article and PDF byte fixture, -applies concurrent title/note patches, reloads the page, and checks content, -notes/count, and PDF bytes. The prior implementation reloaded with `notes: []`; -the single-transaction repair preserves both edits. CI installs the existing -Playwright Chromium runtime and runs this command after quality checks. - -This is storage integration evidence, not PDF-rendering or Reader UI evidence. -The PDF payload is a byte-storage fixture, not a document rendering benchmark. -Guest data is browser-local and is not automatically transferred into an account. -Article API tests use mocked identity/database boundaries: they prove guest -rejection and correct ownership arguments, not deployed Google auth or D1/R2. -Real import/selection/annotation UI, pending-save navigation, hosted persistence, -and session changes remain tracked in [#55](https://github.com/Significant-Hobbies/reader/issues/55). -Guest PDF page notes are implemented in [#56](https://github.com/Significant-Hobbies/reader/issues/56); see the separate browser evidence below. - -## Type-checking - -`pnpm typecheck` runs `tsc --noEmit` against both `tsconfig.app.json` (SPA) -and `tsconfig.worker.json` (Worker + server libs). This is the canonical -type-check; CI runs it on every push/PR. - -## Chrome extension tests - -`packages/chrome-extension/` has its own Vitest config -(`packages/chrome-extension/vitest.config.ts`). The complete root `pnpm quality` -gate runs its type check, 20 tests, and production build in addition to the app -and Worker checks. - -## CI - -CI (`.github/workflows/ci.yml`) runs `pnpm quality` on pushes and PRs to -`main`/`master`. In addition to formatting, lint, types, tests, docs, and builds, -the command blocks regressions in coverage, unused code, complexity, exact -duplication, dependency advisories, import cycles, suppressions, and repository -hygiene. Existing debt is recorded in GitHub issue #42 as checked ceilings, not -described as clean. See [../operations/ci-cd.md](../operations/ci-cd.md). - -Biome currently reports 39 established warnings. `pnpm lint` rejects errors or -any increase in that count; each cleanup should lower the baseline. - -## Documentation checks - -`pnpm docs:check` (`scripts/check-docs.mjs`) validates `docs/` link integrity -and structure. CI runs it in `.github/workflows/docs.yml`. See -[../operations/ci-cd.md](../operations/ci-cd.md). - -## Guest PDF page-note journey - -After `pnpm cf:build`, run `pnpm test:guest-pdf`. It serves the actual built app -on an isolated loopback port and imports a valid two-page synthetic PDF through -the library dialog. The test verifies rendered page text, page navigation, a -page-2 note, a failed IndexedDB write with the draft retained, retry, reload, -return-to-page anchor, edit, reopen, delete, and reload without the deleted note. -It blocks external requests and asserts zero API writes. Screenshots and -overflow checks cover 390, 768, and 1440 pixels. CI runs this after the build. - -This exposed and fixed a pre-existing mismatch between PDF.js API 5.4.296 and -worker 5.4.624. An override aligns react-pdf with the already-declared 5.4.624 -package; no new production package was added. The worker remains bundled locally. - -The page-note contract does not claim selection highlights, embedded PDF export, -account PDF persistence, large-document performance, or hosted qualification. -Those broader live/article/account journeys remain #55. No real documents or -production upload/storage were used. - -## Account PDF supported controls - -`pnpm test:account-pdf` serves the built app with a synthetic signed-in session -and synthetic article response, while blocking all external requests and API -writes. It verifies rendered PDF text, page navigation, zoom, a computed sepia -background, absence of inert Notes/font controls, and desktop/mobile overflow. -Listen passes the current page text to a stubbed speech-synthesis sink; this -checks text wiring, not device audio. AI chat entry is available, but no provider -request or model response is tested. The before mobile screenshot reproduces -the fixed-width sidebar hiding the PDF; final screenshots cover 390/768/1440. - -Account page-note persistence is covered separately below. Real Google/D1/R2/provider -qualification remains actionable in #55. No hosted account or document is used. - -## Account PDF notes through real handlers - -After `pnpm build` and installing Playwright Chromium, run `pnpm test:account-notes`. -This separate Vitest suite serves the built SPA and routes its requests through -unchanged Hono article handlers and Drizzle queries, backed by isolated in-memory -SQLite using a small D1 adapter. Only authentication and synthetic PDF bytes are -fixtures. No production database, credentials, migration or hosted upload is used. - -The handler test verifies persisted page anchors, plain-text sanitization, -invalid page numbers, note counts, delete, and Bob/guest rejection of Alice reads -and writes. The browser test creates a page-two note, injects one failed PUT, -checks the retained draft and untouched database, retries, reloads, follows the -page reference, edits, reopens and deletes. It switches Alice to Bob in the same -SPA via Better Auth's visibility refresh while PUT and GET responses are held, -then releases both late responses, proving cached content/drafts stay isolated, -rejects Bob's write to Alice's PDF, and independently saves/reopens Bob's note. -Desktop/mobile screenshots and document overflow are checked. External requests -are blocked; only known analytics attempts are permitted by the test assertion. - -Concurrent note changes are covered by the save contract below. -Text-selection highlights, embedded annotations/export, live OAuth/R2/D1, -large-document behavior and actual listening/AI quality remain unqualified. - -## Account article annotation and reconciliation - -`pnpm test:account-notes` also runs two built-browser article tests through the -same real Hono/Drizzle/SQLite fixture. Authentication is synthetic; auxiliary -research/provider services explicitly return unavailable and external requests -are blocked. Article bodies are synthetic HTML; no hosted import is performed. - -The cached-reopen regression stays within the same `AppProvidersLayout` by -visiting `/extension`, so QueryClient survives. After updating the isolated -database, reopening must show both fresh notes without a write. Adding a note -must preserve them and allocate a unique ID. Before repair, editing the stale -note replaced both newer database notes with a single old-cache edit. - -The lifecycle test makes a genuine DOM text selection, opens Add note, injects -a failed PUT, verifies no automatic retry after the debounce, retries, reloads, -edits and reopens. While a PUT is held, another edit and a physical marker drag -are queued; a fresh server GET cannot replace the dirty draft, no second write -starts, and a conflicting server edit is preserved after releasing the first write. -The draft and marker remain available; retry cannot overwrite the newer note. -The test then explicitly reloads, compares, and reapplies the copied draft. -A second delayed save crosses an Alice-to-Bob session refresh in the same SPA; -Alice's editor disappears and Bob cannot mutate her document. Bob independently -creates/reopens a note; Alice's deletion survives reload. Desktop and mobile -reading/sidebar screenshots verify reachable content and controls. - -These tests prove scoped source and local persistence behavior. Hosted capture, -OAuth/D1/R2, extension capture, provider responses and broader editing journeys -remain #55. - - -## Concurrent note saves - -Account note PUTs require `notes` and `baseNotes`: the desired notes and the -snapshot from which the editor made its changes. The server normalizes both, -compares each changed note against current storage, and preserves unrelated -concurrent additions or edits. The database update also compares the original -stored notes atomically, retrying a bounded intervening write. HTTP 409 means -an overlapping edit; HTTP 400 rejects missing snapshots or duplicate/invalid -IDs. A successful response includes canonical `notes`. Old clients must reload -before saving notes; unversioned replacement is deliberately rejected. - -Article and PDF editors keep drafts on conflict and explain copying changes -before reload/comparison. Successful acknowledgements advance the saved -baseline; opening a page or refreshing clean data does not write annotations. -The real-handler suite exercises simultaneous saves, conflicting edits, -edit/delete races, lost-acknowledgement retry and deletion preserving another -editor's additions. Pure merge tests cover the note-level invariants. - -Linked board notes use identities derived from board/node IDs, with `sourceKey` -provenance preserved in the existing JSON note field. Array order is not an -identity. Only acknowledged writes advance synchronization, and failed writes -have an explicit retry. Legacy notes without provenance are retained: the -repair never guesses which old notes to delete from their text or position. -Board query/cache mounts are account-scoped. The standalone canvas uses the -viewport height so its nodes remain visible and clickable. - -This contract covers notes. Board-document arrays and AI conversations retain -their existing separate persistence contracts; this is not a claim of a -collaborative board editor or concurrent chat merging. No database schema, -provider configuration, or production dependency changed. +Local browser and synthetic OAuth tests do not establish that production is deployed or that ChatGPT has completed a live OAuth connection. The acceptance check for that is described in [architecture](../architecture/overview.md). diff --git a/docs/index.md b/docs/index.md index 7162719..2496240 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,6 +5,8 @@ operations, and durable knowledge. Markdown here is authoritative. For a fast agent briefing, read [AGENTS.md](../AGENTS.md) first, then this index. +The active product is the [saved-link inbox](product/overview.md). Use [current architecture and MCP setup](architecture/overview.md), [commands](development/commands.md), and [testing](development/testing.md). Research-library walkthroughs and prior decisions are historical context. + ## Where to start - **New to the codebase?** → [product/overview.md](product/overview.md) → [product/features.md](product/features.md) → [architecture/how-it-works.md](architecture/how-it-works.md) → [architecture/overview.md](architecture/overview.md) → [development/setup.md](development/setup.md) diff --git a/docs/knowledge/failed-approaches.md b/docs/knowledge/failed-approaches.md index e0b22c9..ef395c8 100644 --- a/docs/knowledge/failed-approaches.md +++ b/docs/knowledge/failed-approaches.md @@ -1,3 +1,5 @@ +> Historical context from before the saved-link simplification. For the active product and setup, see [architecture](../architecture/overview.md). + # Failed Approaches — Reader Approaches tried and abandoned, with reasons. Each entry links to the diff --git a/docs/knowledge/learnings.md b/docs/knowledge/learnings.md index 5a6d5de..43afa10 100644 --- a/docs/knowledge/learnings.md +++ b/docs/knowledge/learnings.md @@ -1,3 +1,5 @@ +> Historical context from before the saved-link simplification. For the active product and setup, see [architecture](../architecture/overview.md). + # Engineering Lessons — Reader (current) Concrete lessons evidenced by current code, scripts, or git history. Each diff --git a/docs/operations/env.md b/docs/operations/env.md index f32d952..b486bf9 100644 --- a/docs/operations/env.md +++ b/docs/operations/env.md @@ -1,3 +1,5 @@ +> Historical context from before the saved-link simplification. For the active product and setup, see [architecture](../architecture/overview.md). + # Environment Variables Validated by `scripts/validate-env.mjs`. The script takes a mode argument diff --git a/docs/operations/jobs.md b/docs/operations/jobs.md index 3034bd9..23f3cfe 100644 --- a/docs/operations/jobs.md +++ b/docs/operations/jobs.md @@ -1,3 +1,5 @@ +> Historical context from before the saved-link simplification. For the active product and setup, see [architecture](../architecture/overview.md). + # Scheduled Jobs The only scheduled job is the GitHub Actions weekly quality check. diff --git a/docs/product/features.md b/docs/product/features.md index c1dd32e..776e5c9 100644 --- a/docs/product/features.md +++ b/docs/product/features.md @@ -1,95 +1,11 @@ -# Feature Inventory (shipped) +# Features -Current feature surface. Source of truth for "what does the app do today"; -update when behaviour changes. For the API route map, see -[architecture/data-flow.md](../architecture/data-flow.md). +The active product scope is defined in [overview.md](overview.md). -## Reading & capture +- URL capture in the app and Chrome extension. +- Read/unread/all inbox, title/URL search, and pagination. +- Explicit read/unread updates in the app or ChatGPT. +- MCP search, source-text retrieval, and read-state updates. +- Account isolation and revocable extension keys. -- **Article capture from URL** via `@mozilla/readability` + `linkedom` running - server-side in the `/api/snapshot` flow. HTML is sanitised before storage and - re-sanitised on read for defence-in-depth. URL extraction requires sign-in. - Guest import keeps the URL/category in this tab for up to 24 hours, then - returns to an editable draft after sign-in; it never imports automatically. - Explicit cancellation or successful import clears that draft. Local PDFs - and outside links remain available without an account. -- **PDF upload, view, annotate, text extraction.** PDFs are stored in - Cloudflare R2 (`PDFS_BUCKET`); downloads are proxied through - `/api/pdfs/:id/download` so auth + ownership are enforced server-side. PDF - MIME is validated by magic bytes (`%PDF-`); 10 MB per-file limit - (`src/lib/pdf-service.ts`). PDFs use a `blob://` sentinel as the - article `url` to avoid colliding with the user-URL uniqueness index. -- **Link-type articles.** `/reader/:id` redirects link-type articles to their - canonical URL; cards in the library open the URL in a new tab with a distinct - visual treatment and context menu. -- **Rich annotations** with optional DOM anchoring; selection actions - (mouse-up or selection + right-click) expose `Add note` and `Ask AI`. -- **Reading-time estimates** auto-calculated; customisable reader (theme - light/dark/sepia, font sans/serif/mono, text size). - -## RSS / Atom inbox (`/rss`) - -- OPML import that recursively reads outlines with `xmlUrl`, deduplicates per - user, and reports imported/existing/rejected counts. -- Direct feed add/remove with SSRF-validated HTTP(S) URLs. -- Manual refresh with bounded concurrency (4 feeds at a time, 15 s timeout per - feed), per-feed success/error reporting, `ETag` / `Last-Modified` support, - and a response-size + entry cap. One bad feed does not abort the others. -- Unread/read inbox state; opening an entry marks it read and opens the - canonical URL in a new tab. -- Save an entry to the library exactly once (idempotent); creates an article - record when content is available, otherwise a link-type article. -- See [architecture/decisions/0008-rss-inbox.md](../architecture/decisions/0008-rss-inbox.md) - and the repository's [GitHub Issues](https://github.com/Significant-Hobbies/reader/issues) - for current operational follow-up. - -## Organisation & search - -- **Tags** with colour badges, autocomplete, and filtering. -- **Lists** (grouping) and **Boards** (Kanban-style view via `@xyflow/react`). - Boards and lists have shareable share-link endpoints. -- **Full-text search** across article content, notes, and AI chat history - (Cmd/Ctrl+K). Search is in-memory `LIKE`-style today, not FTS5 — see - [knowledge/learnings.md](../knowledge/learnings.md) for the trade-off. -- **Reading progress** tracking (`in_progress` / `completed` status). -- **Session review** per article (`POST /api/articles/:id/session-review`). - -## AI features - -- **Per-article AI chat** with persistent markdown history. -- **Auto-summaries** (short/medium/long) and **key points** extraction (3–5 - bullets) via `POST /api/ai/summarize`. -- **BYOK providers** (OpenAI/Anthropic/Gemini) + free-ai gateway + local AI - mode. BYOK keys are sent per-request from the browser and never persisted - server-side. See [architecture/decisions/0005-ai-gateway-byok.md](../architecture/decisions/0005-ai-gateway-byok.md). -- **Model listing** via `POST /api/ai/models` (proxies `/models` on the - configured endpoint). - -## Memory capture - -- `/memory` page with persisted, authenticated captures (`memories` D1 - table, `/api/memories` CRUD + `/api/memories/search`). -- `POST /api/browser-memory/import` for browser-memory imports. -- Global SearchBar routes memory hits to `/memory`. - -## Chrome extension (MV3) - -- Side panel (persistent chat surface) + popup (ephemeral one-click capture). -- Content script runs `@mozilla/readability` in the page context on demand. -- Chrome Reading List sync (URLs, titles, read state). -- Authenticates with `rdr_*` API keys via `/api/keys` (hashed at rest). -- See [architecture/decisions/0006-mv3-side-panel.md](../architecture/decisions/0006-mv3-side-panel.md) - and `packages/chrome-extension/README.md`. - -## Security & audit fixes (carried forward from the Firebase era) - -- Auth on snapshot routes; SSRF validation (`src/lib/url-validation.ts`) and - redirect-safe fetch (`src/lib/safe-fetch.ts`) on all server-side URL fetches. -- PDFs accessed only through authenticated, ownership-checked proxy routes - (no public R2 URLs). -- HTML sanitised at ingestion and re-sanitised on read. -- Security headers applied in `src/worker.ts` (`X-Content-Type-Options`, - `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`, HSTS). -- Residual / deferred items: no explicit CORS config (acceptable same-origin), - no rate limiting on AI/snapshot/proxy (deferred pending evidence). See - [archive/security-audit-2026-03-29.md](../archive/security-audit-2026-03-29.md). +Source implementation does not establish live rollout. See [project status](../../PROJECT_STATUS.md). diff --git a/docs/product/overview.md b/docs/product/overview.md index f3efb28..67f8afd 100644 --- a/docs/product/overview.md +++ b/docs/product/overview.md @@ -1,59 +1,19 @@ # Product Overview -## What - -Reader is a personal research library: capture web articles and PDFs, read them -in a distraction-free reader, annotate with notes and highlights, organise with -tags/lists/boards, search across everything, and AI-chat or auto-summarise the -saved material. A companion Chrome MV3 extension captures pages from the -browser and syncs with Chrome's native Reading List. - -## Who - -- **End users:** individual readers saving articles and PDFs. Sign-in is Google - OAuth via better-auth; data is per-user isolated at the database level. -- **Operators:** the maintainer running D1 schema migrations and Cloudflare - Workers deploys. Currently single-user in production. - -## Where - -- Production app: `https://read.significanthobbies.com` (Cloudflare Worker - `reader`, custom domain). See [surfaces.md](surfaces.md) for the full list. -- Source: this repository. -- Landing page: built from `landing-astro/` and overlaid onto `dist/index.html` - during `cf:build`; the SPA lives at `dist/app.html` and is served at `/app`. - -## Scope - -**In scope:** article/PDF capture, rich annotations, tags/lists/boards, -full-text search, AI chat and summaries, RSS/Atom inbox with OPML import, -memory capture, D1 persistence, R2 PDF storage, free-ai gateway + BYOK + -local-ai dev bridge. - -**Out of scope (deliberate):** - -- Browser-extension distribution (deferred until web import/capture is - reliable). -- Full personal knowledge-base automation behind strong capture, retrieval, and - trust primitives. -- Paid team/library workflows. -- `landing-astro` as a separate deployable product — it is an overlay only. -- RSS background refresh / scheduled triggers / notifications / feed discovery - (current RSS refresh is manual). -- Rate limiting on AI/snapshot/proxy endpoints (deferred until endpoint-specific - evidence; see [operations/env.md](../operations/env.md) and the residual - audit notes in [archive/security-audit-2026-03-29.md](../archive/security-audit-2026-03-29.md)). - -## Operating posture - -Personal-use support (closure decision 2026-07-10): keep Reader available for -direct use. No roadmap expansion; accept only maintenance, reliability, or -personally requested workflow fixes. See [STATUS.md](../../STATUS.md) for the -current objective and active work. - -## Branding note - -The product is named **Reader** and served at -`read.significanthobbies.com`. The package name and Chrome extension still use -the legacy `web-annotator` / "Web Annotator" string in places; the canonical -product name in new docs is **Reader**. +Reader stores links you choose to save. Add a URL in the web app or click Save link in the Chrome extension. ChatGPT handles reading and discussion through MCP. + +The app has an inbox and a Connections page. Links have a title, URL, creation date, and read/unread state. Search matches titles and URLs. Opening or fetching a link does not silently mark it read. + +The MCP tools find links, retrieve available text, and update read state when the user asks. Source text can be unavailable because a site blocks extraction or is not a web document; the original URL remains available. + +## Boundaries + +No RSS, built-in AI, annotations, reader view, PDF capture, boards, lists, or memories. The Chrome extension is a URL/title capture popup, with no background page scanning or native Reading List sync. + +Existing account data remains in D1 and R2. Legacy web articles appear as links; their stored text remains retrievable. Local browser data is not deleted. No schema migration is required for the simplification. + +## Access + +Google sign-in identifies the app account. Extension keys are created in Connections and stored hashed on the server. MCP uses Google-backed Auth0 OAuth and maps to the existing account’s Google subject. + +See [architecture](../architecture/overview.md) for connection setup and [project status](../../PROJECT_STATUS.md) for the deployment boundary. diff --git a/docs/product/surfaces.md b/docs/product/surfaces.md index c6b4d3c..587a93b 100644 --- a/docs/product/surfaces.md +++ b/docs/product/surfaces.md @@ -1,56 +1,15 @@ -# Production Surfaces +# Surfaces -## App - -| Surface | URL | Notes | +| Surface | Path | Access | | --- | --- | --- | -| Production app | `https://read.significanthobbies.com` | Cloudflare Worker `reader`, custom domain | -| Landing page | `https://read.significanthobbies.com/` | Static Astro page overlaid onto `dist/index.html` during `cf:build` | -| SPA entry | `https://read.significanthobbies.com/app` | Vite SPA built from `app.html`; served via the `ASSETS` binding | -| Login | `https://read.significanthobbies.com/login` | Google OAuth via better-auth | -| Library | `https://read.significanthobbies.com/library` | Auth-walled | -| RSS inbox | `https://read.significanthobbies.com/rss` | Auth-walled | -| Memory | `https://read.significanthobbies.com/memory` | Auth-walled | -| Boards | `https://read.significanthobbies.com/board` | Auth-walled | -| Reader | `https://read.significanthobbies.com/reader/:id` | Auth-walled; link-type articles 302 to their URL | -| Share | `https://read.significanthobbies.com/share/:shareId` | Public board share | -| Shared article | `https://read.significanthobbies.com/share/article/:shareId` | Public article share | - -Auth-walled routes are not agent-indexed. - -## Agent / crawler surfaces - -Served from `public/` and the `agent-edge.mjs` handler in `src/worker.ts` -(before the SPA/ASSETS fallback). The Worker `run_worker_first` config in -`wrangler.toml` ensures `/api/*`, `/`, `/sitemap.xml`, `/index.md`, -`/llms-full.txt`, and `/llms.txt` hit the Worker first. - -| Surface | Path | Purpose | -| --- | --- | --- | -| `llms.txt` | `/llms.txt` | Concise agent index (links to product + machine surfaces) | -| `llms-full.txt` | `/llms-full.txt` | Full agent brief | -| `index.md` | `/index.md` | Product brief in Markdown (no JS) | -| `api/ai` | `/api/ai` | JSON catalog of public surfaces | -| `robots.txt` | `/robots.txt` | Allows all + lists agent surfaces | -| `sitemap.xml` | `/sitemap.xml` | Canonical public HTML page inventory | -| IndexNow key | `/fa7259e2e0d942f1a1267b344a75a143.txt` | Bing/Yandex URL submission key | - -The agent-edge payload is generated into `src/agent-edge.mjs` by the fleet -`apply-agent-surfaces` tooling; the Markdown sources in `public/` are the -human-editable mirrors. When updating agent copy, edit the `public/` files -and regenerate `agent-edge.mjs` per the fleet standard -(`fleet-ops/docs/agent-indexing-standard.md`). - -## Internal fleet services used - -| Service | Role | -| --- | --- | -| `free-ai` gateway | Default AI chokepoint via `AI_BASE_URL` (`https://ai-gateway.sassmaker.com/v1`) with `x-gateway-project-id: reader` | -| `local-ai` | Dev bridge for authenticated local CLI models (`pnpm local-ai`) | -| SaaS Maker feedback widget | In-app feedback capture (`@saas-maker/feedback`) | +| Landing | `/` | Public | +| Link inbox | `/library` | Signed-in account | +| Connections | `/extension` | Account keys; public sign-in prompt | +| Sign-in | `/login` | Public | +| Privacy | `/privacy` | Public | +| MCP | `/api/mcp` | OAuth for private tools | +| OAuth resource metadata | `/.well-known/oauth-protected-resource/api/mcp` | Public when configured | -## CI/CD +Public product information is also available as Markdown and through the existing `/api/ai` discovery catalog. These public surfaces never expose account links. -GitHub Actions: CI on push/PR, manual deploy (`workflow_dispatch`), manual AI -review, and a weekly quality cron. See -[operations/ci-cd.md](../operations/ci-cd.md). +See [project status](../../PROJECT_STATUS.md) for deployment readiness and [architecture](../architecture/overview.md) for MCP setup. diff --git a/knip.jsonc b/knip.jsonc index 4ea36b4..973fc5b 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -12,7 +12,6 @@ "project": ["src/**/*.{ts,tsx,mjs}", "scripts/*.{mjs,ts}", "*.config.{js,ts,mjs,cjs}"], "ignoreDependencies": [ // Loaded through Tailwind CSS directives rather than JavaScript imports. - "@tailwindcss/typography", // Optional documentation presentation layer; Markdown remains authoritative. // Spawned by the code-health checker rather than imported. "jscpd", @@ -29,16 +28,12 @@ }, "packages/chrome-extension": { "entry": [ - "src/background.ts", - "src/content-script.ts", "src/popup/main.tsx", - "src/side-panel/main.tsx", "*.config.{js,ts,mjs,cjs}" ], "project": ["src/**/*.{ts,tsx}", "*.config.{js,ts,mjs,cjs}"], "ignoreDependencies": [ // CSS/PostCSS integrations are not visible in the TypeScript graph. - "@tailwindcss/typography", "autoprefixer", "tailwindcss" ] diff --git a/landing-astro/src/layouts/Layout.astro b/landing-astro/src/layouts/Layout.astro index 35535ce..9ad1efa 100644 --- a/landing-astro/src/layouts/Layout.astro +++ b/landing-astro/src/layouts/Layout.astro @@ -89,114 +89,5 @@ const SITE_URL = 'https://read.significanthobbies.com'; data-identity="persistent" > - {Astro.props.showStandaloneProjectStrip !== false && } - - - - - diff --git a/landing-astro/src/pages/changelog/index.astro b/landing-astro/src/pages/changelog/index.astro index 1c766c8..15993fc 100644 --- a/landing-astro/src/pages/changelog/index.astro +++ b/landing-astro/src/pages/changelog/index.astro @@ -1,155 +1,11 @@ --- import Layout from '@/layouts/Layout.astro'; - -const repository = 'https://github.com/Significant-Hobbies/reader'; -const releases = [ - { - date: '2026-07-13', - title: 'RSS and Atom reading joined the library', - outcomes: [ - 'Authenticated readers can import OPML, add or remove feeds, refresh them on demand, and track unread items.', - 'A feed item can be saved directly into the same article and PDF library for annotation and later research.', - ], - }, - { - date: '2026-07-03', - title: 'Memory capture became durable', - outcomes: [ - 'Saved research memories gained authenticated persistence, search, and a dedicated reading surface.', - 'Existing browser memories can be imported into the account-backed collection.', - ], - }, - { - date: '2026-07-02', - title: 'Safer failure recovery', - outcomes: [ - 'Unhandled API and Worker errors now return a controlled response instead of breaking the request path.', - 'A React error boundary gives the library a recovery surface when a page fails to render.', - ], - }, - { - date: '2026-06-20', - title: 'Reader moved to a faster app shell', - outcomes: [ - 'The product moved to a Vite and React SPA backed by a focused Hono Worker while preserving its production identity.', - 'Articles, PDFs, highlights, notes, boards, lists, search, and AI-assisted reading stayed together in one library.', - ], - }, -]; --- - - -
-
- -
- -
-
- Product history -

Changelog

-

- Verified improvements to saving, reading, annotating, and returning to useful sources. -

- -
- -
    - { - releases.map((release) => ( -
  1. -
    - -

    {release.title}

    -
      - {release.outcomes.map((outcome) =>
    • {outcome}
    • )} -
    -
    -
  2. - )) - } -
-
- - - -
-
- Reader -

A maintained personal research library for turning saved sources into working knowledge.

-
- - -
-
-
+ +
+

Product direction

A smaller Reader.

+

The active product is a saved-link inbox, a one-click capture extension, and MCP tools for ChatGPT to retrieve links and update read state.

+

Existing saved data remains intact. Deployment and an authenticated ChatGPT connection are verified separately from source changes.

+ Source history ↗ +
diff --git a/landing-astro/src/pages/faq.astro b/landing-astro/src/pages/faq.astro index c24a0e9..004d638 100644 --- a/landing-astro/src/pages/faq.astro +++ b/landing-astro/src/pages/faq.astro @@ -1,155 +1,12 @@ --- import Layout from '@/layouts/Layout.astro'; - -const TITLE = 'Reader FAQ — sources, privacy, AI, and current access'; -const DESCRIPTION = - 'Answers about saving articles and PDFs in Reader, local and account-backed use, annotations, AI, sharing, export, and the source-built extension.'; - -const faqs = [ - { - q: 'What is Reader for?', - a: 'Reader turns a saved article or PDF into a focused place to read, annotate, revisit, and discuss it. It is useful when a browser tab or bookmark is too easy to forget and the source deserves more deliberate attention.', - }, - { - q: 'What can I save?', - a: 'Paste a web article URL or upload a PDF. Reader uses Mozilla Readability to prepare web pages for a cleaner reading view, while PDF text is extracted so the document can join the same search and discussion flow.', - }, - { - q: 'Do I need an account?', - a: 'No account is required to start with the browser-local path. Google sign-in opens the account-backed library, where saved material is isolated per user and PDFs are stored behind an ownership-enforcing proxy.', - }, - { - q: 'How do highlights and notes work?', - a: 'Select a passage in the reader view to highlight it or add a note. Reader keeps the annotation anchored to the text that prompted it, so the source and your interpretation remain close when you return.', - }, - { - q: 'How does AI work in Reader?', - a: 'Reader can summarize an open article or PDF and answer questions about it. The app supports the Fleet AI gateway and bring-your-own OpenAI, Anthropic, or Gemini credentials. BYOK credentials are held in the browser, used for the request, and not persisted server-side.', - }, - { - q: 'Is my library public?', - a: 'No. Saved articles, PDFs, annotations, lists, boards, and AI conversations are private by default. Reader creates a public surface only when you explicitly share an article or board.', - }, - { - q: 'Can I install the Chrome extension?', - a: 'The MV3 companion exists in the source repository and can be loaded as an unpacked extension for local use. Public browser-store distribution is deferred, so the landing page does not present it as a generally available install.', - }, - { - q: 'Can I organize and retrieve older material?', - a: 'Yes. Full-text search covers saved sources and notes. Tags provide cross-cutting labels, lists group related material, and boards help arrange a research set or reading stage.', - }, - { - q: 'Can I export my data?', - a: 'Yes. Reader includes a JSON export for the articles, boards, and lists scoped to the signed-in account.', - }, - { - q: 'Is Reader a paid product?', - a: 'There is currently no public Reader plan or checkout. The repository also does not establish a permanent free promise, so the product page states the present access model without inventing future pricing.', - }, -]; - -const faqJsonLd = { - '@context': 'https://schema.org', - '@type': 'FAQPage', - mainEntity: faqs.map((faq) => ({ - '@type': 'Question', - name: faq.q, - acceptedAnswer: { - '@type': 'Answer', - text: faq.a, - }, - })), -}; --- - - -
-
- -
- -
-
-

Reader / Practical questions

-

What happens to a source after you bring it inside?

-

- The useful details about capture, privacy, AI, organisation, sharing, export, and the - current product boundary. -

-
- -

Reader questions and answers

-
- {faqs.map((faq) => ( -
- {faq.q} -

{faq.a}

-
- ))} -
- - -
- - - -
-
- Reader -

A maintained personal research library for turning saved sources into working knowledge.

-
- - -
-
-
- - - - diff --git a/packages/chrome-extension/src/__tests__/api.test.ts b/packages/chrome-extension/src/__tests__/api.test.ts new file mode 100644 index 0000000..d447513 --- /dev/null +++ b/packages/chrome-extension/src/__tests__/api.test.ts @@ -0,0 +1,29 @@ +// @vitest-environment node +import { beforeEach, expect, it, vi } from 'vitest'; +import { checkKey, getApiKey, saveLink, setApiKey } from '../api'; +const storage = { get: vi.fn(), set: vi.fn(), remove: vi.fn() }; +const fetchMock = vi.fn(); +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal('chrome', { storage: { local: storage } }); + vi.stubGlobal('fetch', fetchMock); +}); +it('keeps the existing local key slot and sends only the selected link', async () => { + storage.get.mockResolvedValue({ 'api-key': 'rdr_synthetic-fixture' }); + fetchMock.mockResolvedValue(Response.json({ id: 'one', existing: false })); + expect(await getApiKey()).toBe('rdr_synthetic-fixture'); + await setApiKey('rdr_synthetic-fixture'); + expect(storage.set).toHaveBeenCalledWith({ 'api-key': 'rdr_synthetic-fixture' }); + await saveLink('https://example.com/post', 'A post'); + const [url, request] = fetchMock.mock.calls[0]; + expect(url).toMatch(/\/api\/links$/u); + expect(JSON.parse(request.body)).toEqual({ url: 'https://example.com/post', title: 'A post' }); + expect(request.headers.Authorization).toBe('Bearer rdr_synthetic-fixture'); +}); +it('does not send a save without a connection and reports rejected keys', async () => { + storage.get.mockResolvedValue({}); + await expect(saveLink('https://example.com', 'Example')).rejects.toThrow('Connect Reader first.'); + expect(fetchMock).not.toHaveBeenCalled(); + fetchMock.mockResolvedValue(Response.json({}, { status: 401 })); + expect(await checkKey('rdr_synthetic-fixture')).toBe(false); +}); diff --git a/packages/chrome-extension/src/api.ts b/packages/chrome-extension/src/api.ts new file mode 100644 index 0000000..16cbe01 --- /dev/null +++ b/packages/chrome-extension/src/api.ts @@ -0,0 +1,25 @@ +const API_BASE = import.meta.env.VITE_API_BASE || 'https://read.significanthobbies.com'; +export function getApiBase() { return API_BASE; } +export async function getApiKey(): Promise { + const result = await chrome.storage.local.get('api-key'); + return typeof result['api-key'] === 'string' ? result['api-key'] : null; +} +export async function setApiKey(key: string) { await chrome.storage.local.set({ 'api-key': key }); } +export async function clearApiKey() { await chrome.storage.local.remove('api-key'); } +export async function checkKey(key: string): Promise { + const response = await fetch(`${API_BASE}/api/auth/me`, { + headers: { Authorization: `Bearer ${key}` }, cache: 'no-store', + }); + return response.ok; +} +export async function saveLink(url: string, title: string) { + const key = await getApiKey(); + if (!key) throw new Error('Connect Reader first.'); + const response = await fetch(`${API_BASE}/api/links`, { + method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, + body: JSON.stringify({ url, title }), + }); + const body = await response.json(); + if (!response.ok) throw new Error(body.error || 'Could not save this link.'); + return body as { id: string; existing: boolean }; +} diff --git a/packages/chrome-extension/src/background.ts b/packages/chrome-extension/src/background.ts deleted file mode 100644 index 40d5f8d..0000000 --- a/packages/chrome-extension/src/background.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { - syncAllChromeReadingListToReader, - syncChromeReadingListEntryToReader, - syncChromeReadingListRemovalToReader, -} from './side-panel/lib/reading-list-sync'; - -chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false }); - -async function getActiveTab(): Promise { - const tabs = await chrome.tabs.query({ active: true, currentWindow: true }); - return tabs[0]; -} - -async function sendPageContentRequest(tabId: number, message: unknown) { - return chrome.tabs.sendMessage(tabId, message); -} - -async function extractPageContent(tabId: number, message: unknown) { - try { - return await sendPageContentRequest(tabId, message); - } catch { - try { - await chrome.scripting.executeScript({ - target: { tabId }, - files: ['content-script.js'], - }); - return await sendPageContentRequest(tabId, message); - } catch { - const tab = await chrome.tabs.get(tabId).catch(() => null); - const url = tab?.url || ''; - const title = tab?.title || url || 'Unsupported page'; - - return { - type: 'PAGE_CONTENT', - data: url - ? { - title, - byline: null, - content: '', - textContent: '', - siteName: null, - url, - canImport: false, - } - : null, - fallback: true, - }; - } - } -} - -// Relay messages between content script and side panel -chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { - if (message.type === 'GET_PAGE_CONTENT') { - // Forward to the active tab's content script - getActiveTab().then(async (tab) => { - const tabId = tab?.id; - if (!tabId) { - sendResponse({ type: 'PAGE_CONTENT', data: null, fallback: true }); - return; - } - const response = await extractPageContent(tabId, message); - sendResponse(response); - }); - return true; // Keep channel open for async response - } - - if (message.type === 'GET_ACTIVE_TAB') { - getActiveTab().then((tab) => { - sendResponse({ tabId: tab?.id, url: tab?.url }); - }); - return true; - } - - if (message.type === 'OPEN_URL_IN_ACTIVE_TAB') { - getActiveTab().then((tab) => { - const tabId = tab?.id; - if (!tabId || typeof message.url !== 'string') { - sendResponse({ ok: false }); - return; - } - - chrome.tabs.update(tabId, { url: message.url }, () => { - sendResponse({ ok: !chrome.runtime.lastError }); - }); - }); - return true; - } - - if (message.type === 'OPEN_SIDE_PANEL') { - getActiveTab().then((tab) => { - const tabId = tab?.id; - if (!tabId) { - sendResponse({ ok: false }); - return; - } - - chrome.sidePanel.open({ tabId }, () => { - sendResponse({ ok: !chrome.runtime.lastError }); - }); - }); - return true; - } -}); - -// Re-extract content when user navigates within a tab -chrome.tabs.onUpdated.addListener((tabId, changeInfo) => { - if (changeInfo.status === 'complete') { - chrome.runtime - .sendMessage({ - type: 'TAB_UPDATED', - tabId, - }) - .catch(() => { - // Side panel may not be open yet - }); - } -}); - -chrome.runtime.onInstalled.addListener(() => { - void syncAllChromeReadingListToReader().catch(() => { - // Reader may not be connected yet. - }); -}); - -chrome.runtime.onStartup.addListener(() => { - void syncAllChromeReadingListToReader().catch(() => { - // Reader may not be connected yet. - }); -}); - -if (chrome.readingList) { - chrome.readingList.onEntryAdded.addListener((entry) => { - void syncChromeReadingListEntryToReader(entry).catch(() => { - // Keep native Reading List changes non-blocking. - }); - }); - - chrome.readingList.onEntryUpdated.addListener((entry) => { - void syncChromeReadingListEntryToReader(entry).catch(() => { - // Keep native Reading List changes non-blocking. - }); - }); - - chrome.readingList.onEntryRemoved.addListener((entry) => { - void syncChromeReadingListRemovalToReader(entry).catch(() => { - // Keep native Reading List changes non-blocking. - }); - }); -} diff --git a/packages/chrome-extension/src/content-script.ts b/packages/chrome-extension/src/content-script.ts deleted file mode 100644 index 98d1fc6..0000000 --- a/packages/chrome-extension/src/content-script.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { Readability } from '@mozilla/readability'; - -interface ExtractionResult { - title: string; - byline: string | null; - content: string; - textContent: string; - siteName: string | null; - url: string; - canImport?: boolean; -} - -interface ExtractionResponse { - type: 'PAGE_CONTENT'; - data: ExtractionResult | null; - fallback: boolean; -} - -function extractWithReadability(): ExtractionResult | null { - try { - const clone = document.cloneNode(true) as Document; - const article = new Readability(clone).parse(); - if (!article) return null; - - return { - title: article.title || document.title, - byline: article.byline || null, - content: article.content || '', - textContent: article.textContent || '', - siteName: article.siteName || null, - url: location.href, - }; - } catch { - return null; - } -} - -function extractFallback(): ExtractionResult { - return { - title: document.title, - byline: null, - content: document.body?.innerText?.slice(0, 8000) || '', - textContent: document.body?.innerText?.slice(0, 8000) || '', - siteName: null, - url: location.href, - }; -} - -chrome.runtime.onMessage.addListener( - ( - message: { type: string }, - _sender: chrome.runtime.MessageSender, - sendResponse: (response: ExtractionResponse) => void - ) => { - if (message.type === 'GET_PAGE_CONTENT') { - const article = extractWithReadability(); - if (article) { - sendResponse({ type: 'PAGE_CONTENT', data: article, fallback: false }); - } else { - sendResponse({ - type: 'PAGE_CONTENT', - data: extractFallback(), - fallback: true, - }); - } - } - return true; - } -); diff --git a/packages/chrome-extension/src/popup/App.tsx b/packages/chrome-extension/src/popup/App.tsx index b35690e..f5f45f0 100644 --- a/packages/chrome-extension/src/popup/App.tsx +++ b/packages/chrome-extension/src/popup/App.tsx @@ -1,509 +1,95 @@ -import { useCallback, useEffect, useState } from 'react'; -import { - AlertTriangle, - BookmarkPlus, - CheckCircle2, - ExternalLink, - KeyRound, - Loader2, - MessageCircle, - User, -} from 'lucide-react'; -import type { AuthState, PageContent } from '../side-panel/lib/types'; -import { - checkAuth, - clearApiKey, - findLibraryItemByUrl, - getApiBase, - getApiKey, - saveLinkToLibrary, - saveToLibrary, - setApiKey, - updateLibraryItemCategory, - verifyApiKeyForUser, - type ReaderLibraryItem, -} from '../side-panel/lib/api'; -import { canImportPage, getImportNotice, type ImportNotice } from '../side-panel/lib/importQuality'; -import { - syncAllChromeReadingListToReader, - upsertChromeReadingListEntry, -} from '../side-panel/lib/reading-list-sync'; +import { useEffect, useState } from 'react'; +import { BookmarkPlus, Check, ExternalLink, Loader2 } from 'lucide-react'; +import { checkKey, clearApiKey, getApiBase, getApiKey, saveLink, setApiKey } from '../api'; -type LoadState = 'loading' | 'ready'; -type ActionState = 'idle' | 'working' | 'error'; -type LookupState = 'idle' | 'checking' | 'found' | 'missing' | 'error'; - -const CATEGORY_SUGGESTIONS = [ - 'Read later', - 'Research papers', - 'Blogs', - 'Products to try', - 'AI and ML', - 'Engineering', -]; - -async function getCurrentPage(): Promise<{ - page: PageContent | null; - notice: ImportNotice | null; -}> { - const response = await chrome.runtime.sendMessage({ type: 'GET_PAGE_CONTENT' }).catch(() => null); - const page = response?.data ?? null; - const usedFallback = Boolean(response?.fallback); - return { - page: page ? { ...page, canImport: canImportPage(page, usedFallback) } : null, - notice: getImportNotice(page, usedFallback), - }; -} - -async function openUrlInActiveTab(url: string): Promise { - const response = await chrome.runtime - .sendMessage({ type: 'OPEN_URL_IN_ACTIVE_TAB', url }) - .catch(() => null); - return Boolean(response?.ok); -} - -async function openChatPanel(): Promise { - if (chrome.sidePanel?.open) { - const tabs = await chrome.tabs.query({ active: true, currentWindow: true }); - const tabId = tabs[0]?.id; - if (tabId) { - await chrome.sidePanel.open({ tabId }); - return true; - } - } - - const response = await chrome.runtime.sendMessage({ type: 'OPEN_SIDE_PANEL' }).catch(() => null); - return Boolean(response?.ok); -} - -async function doConnect(ctx: { - keyValue: string; - setAuth: (a: AuthState) => void; - setShowConnect: (v: boolean) => void; - setKeyValue: (v: string) => void; - setActionState: (s: ActionState) => void; - setError: (e: string | null) => void; -}) { - const trimmed = ctx.keyValue.trim(); - if (!trimmed.startsWith('rdr_')) { - ctx.setError('Key must start with rdr_'); - return; - } - - ctx.setActionState('working'); - ctx.setError(null); - const result = await verifyApiKeyForUser(trimmed); - if (result.ok) { - await setApiKey(trimmed); - await syncAllChromeReadingListToReader().catch(() => null); - ctx.setAuth({ isAuthenticated: true, user: result.user }); - ctx.setShowConnect(false); - ctx.setKeyValue(''); - ctx.setActionState('idle'); - return; - } - - await clearApiKey(); - ctx.setError(result.error); - ctx.setActionState('error'); -} - -async function doOpenInAnnotator(ctx: { - page: PageContent | null; - notice: ImportNotice | null; - category: string; - setActionState: (s: ActionState) => void; - setError: (e: string | null) => void; -}) { - if (!ctx.page) { - ctx.setError('No readable page detected.'); - return; - } - if (ctx.page.canImport === false || ctx.notice?.blocking) { - ctx.setError('This page cannot be imported directly.'); - return; - } - - ctx.setActionState('working'); - ctx.setError(null); - try { - const trimmedCategory = ctx.category.trim(); - const article = await saveToLibrary({ - url: ctx.page.url, - title: ctx.page.title, - byline: ctx.page.byline, - content: ctx.page.content, - category: trimmedCategory || undefined, - }); - if (trimmedCategory) { - await updateLibraryItemCategory(article.id, trimmedCategory); - } - await upsertChromeReadingListEntry({ - url: ctx.page.url, - title: ctx.page.title || ctx.page.url, - articleId: article.id, - itemType: 'article', - }); - const opened = await openUrlInActiveTab(`${getApiBase()}/reader/${article.id}`); - if (!opened) { - chrome.tabs.create({ url: `${getApiBase()}/reader/${article.id}` }); - } - window.close(); - } catch (err) { - ctx.setError(err instanceof Error ? err.message : 'Failed to open page.'); - ctx.setActionState('error'); - } -} - -async function doSaveLink(ctx: { - page: PageContent | null; - category: string; - setActionState: (s: ActionState) => void; - setError: (e: string | null) => void; -}) { - if (!ctx.page) { - ctx.setError('No page detected.'); - return; - } - - ctx.setActionState('working'); - ctx.setError(null); - try { - const trimmedCategory = ctx.category.trim(); - const result = await saveLinkToLibrary({ - url: ctx.page.url, - title: ctx.page.title || ctx.page.url, - category: trimmedCategory || undefined, - }); - if (trimmedCategory) { - await updateLibraryItemCategory(result.id, trimmedCategory); - } - await upsertChromeReadingListEntry({ - url: ctx.page.url, - title: ctx.page.title || ctx.page.url, - articleId: result.id, - itemType: 'link', - }); - ctx.setActionState('idle'); - window.close(); - } catch (err) { - ctx.setError(err instanceof Error ? err.message : 'Failed to save link.'); - ctx.setActionState('error'); - } -} - -async function doChatWithThis(setError: (e: string | null) => void) { - const opened = await openChatPanel(); - if (opened) { - window.close(); - return; - } - setError('Could not open chat.'); -} - -function usePopupState() { - const [loadState, setLoadState] = useState('loading'); - const [auth, setAuth] = useState({ isAuthenticated: false, user: null }); - const [pageState, setPageState] = useState(null); - const [noticeState, setNoticeState] = useState(null); - const [showConnect, setShowConnect] = useState(false); - const [keyValue, setKeyValue] = useState(''); - const [category, setCategory] = useState(''); - const [lookupState, setLookupState] = useState('idle'); - const [existingItem, setExistingItem] = useState(null); - const [actionState, setActionState] = useState('idle'); - const [error, setError] = useState(null); - - const refresh = useCallback(async () => { - setLoadState('loading'); - const [storedKey, currentPage] = await Promise.all([getApiKey(), getCurrentPage()]); - setPageState(currentPage.page); - setNoticeState(currentPage.notice); - - if (storedKey) { - const user = await checkAuth(); - setAuth(user ? { isAuthenticated: true, user } : { isAuthenticated: false, user: null }); - } else { - setAuth({ isAuthenticated: false, user: null }); - } - - setLoadState('ready'); - }, []); - - useEffect(() => { - void refresh(); - }, [refresh]); +export function App() { + const [tab, setTab] = useState(null); + const [connected, setConnected] = useState(false); + const [loading, setLoading] = useState(true); + const [working, setWorking] = useState(false); + const [key, setKey] = useState(''); + const [error, setError] = useState(''); + const [saved, setSaved] = useState(''); useEffect(() => { - if (!auth.isAuthenticated || !pageState?.url) { - setLookupState('idle'); - setExistingItem(null); - return; - } - let cancelled = false; - setLookupState('checking'); - setExistingItem(null); - - findLibraryItemByUrl(pageState.url) - .then((item) => { - if (cancelled) return; - setExistingItem(item); - setLookupState(item ? 'found' : 'missing'); - }) - .catch(() => { - if (cancelled) return; - setLookupState('error'); - }); - - return () => { - cancelled = true; - }; - }, [auth.isAuthenticated, pageState?.url]); - - const connect = () => - doConnect({ keyValue, setAuth, setShowConnect, setKeyValue, setActionState, setError }); - const openInAnnotator = () => - doOpenInAnnotator({ - page: pageState, - notice: noticeState, - category, - setActionState, - setError, - }); - const saveLink = () => - doSaveLink({ page: pageState, category, setActionState, setError }); - const chatWithThis = () => doChatWithThis(setError); - - return { - loadState, - auth, - page: pageState, - importNotice: noticeState, - showConnect, - keyValue, - category, - lookupState, - existingItem, - actionState, - error, - setKeyValue, - setCategory, - setShowConnect, - connect, - openInAnnotator, - saveLink, - chatWithThis, - }; -} - -type PopupState = ReturnType; - -function PopupHeader(props: { page: PageContent | null; auth: AuthState }) { - const { page, auth } = props; - return ( -
-
-

{page?.title || 'No page detected'}

-

{page?.siteName || page?.url || ''}

-
- {auth.isAuthenticated && ( -
- {auth.user?.photoURL ? ( - - ) : ( - - )} -
- )} -
- ); -} - -function ImportNoticeBanner(props: { notice: ImportNotice }) { - const { notice } = props; - return ( -
- -
-

{notice.title}

-

{notice.message}

-
-
- ); -} + async function load() { + try { + const [[active], storedKey] = await Promise.all([ + chrome.tabs.query({ active: true, currentWindow: true }), getApiKey(), + ]); + const valid = storedKey ? await checkKey(storedKey) : false; + if (!cancelled) { setTab(active ?? null); setConnected(valid); } + } catch { + if (!cancelled) setError('Could not reach Reader. Try reopening the extension.'); + } finally { + if (!cancelled) setLoading(false); + } + } + void load(); + return () => { cancelled = true; }; + }, []); -function ConnectForm(props: PopupState) { - const { showConnect, setShowConnect, keyValue, setKeyValue, actionState, connect } = props; - if (!showConnect) { - return ( - - ); + async function connect(event: React.FormEvent) { + event.preventDefault(); setWorking(true); setError(''); + try { + const token = key.trim(); + if (!token.startsWith('rdr_') || !await checkKey(token)) throw new Error('Reader rejected this key. Create a new extension key.'); + await setApiKey(token); setKey(''); setConnected(true); + } catch (err) { setError(err instanceof Error ? err.message : 'Could not connect Reader.'); } + finally { setWorking(false); } } - return ( -
- - Create extension key - - - setKeyValue(event.target.value)} - placeholder="rdr_..." - className="h-9 w-full rounded-lg border border-gray-700 bg-gray-900 px-2 text-xs text-gray-100 outline-none focus:ring-2 focus:ring-blue-500" - /> - -
- ); -} + async function save() { + if (!tab?.url) return; + setWorking(true); setError(''); + try { + const result = await saveLink(tab.url, tab.title || tab.url); + setSaved(result.existing ? 'Already in your inbox.' : 'Saved to your inbox.'); + } catch (err) { setError(err instanceof Error ? err.message : 'Could not save this link.'); } + finally { setWorking(false); } + } -function AuthenticatedActions(props: PopupState) { - const { - page, - importNotice, - category, - setCategory, - lookupState, - existingItem, - actionState, - saveLink, - openInAnnotator, - chatWithThis, - } = props; return ( -
-
- - setCategory(event.target.value)} - placeholder={existingItem?.category || 'Read later, papers, products...'} - className="h-9 w-full rounded-lg border border-gray-700 bg-gray-900 px-2 text-xs text-gray-100 outline-none placeholder:text-gray-500 focus:ring-2 focus:ring-blue-500" - /> - - {CATEGORY_SUGGESTIONS.map((suggestion) => ( - -
- {lookupState === 'checking' && ( -

- Checking Reader Library... -

- )} - {lookupState === 'found' && existingItem && ( - - - - Already in Library{existingItem.category ? ` · ${existingItem.category}` : ''} - - - +
+
+

Reader

+ Inbox +
+ {loading ?

Loading…

: connected ? ( + void save()} + onDisconnect={() => { void clearApiKey().then(() => { setConnected(false); setSaved(''); }).catch(() => setError('Could not disconnect.')); }} /> + ) : ( +
void connect(event)} className="space-y-3"> +

Connect once, then save the current page in one click.

+ Get an extension key ↗ + + setKey(event.target.value)} placeholder="rdr_…" required disabled={working} className="min-h-11 w-full rounded-lg border border-gray-700 bg-gray-900 px-3 text-sm" /> + +
)} - - - -
+ {error &&

{error}

} + ); } -export function App() { - const state = usePopupState(); - const { loadState, auth, page, importNotice, error } = state; - - if (loadState === 'loading') { - return ( -
- -
- ); - } - +function SavedPage({ tab, working, saved, onSave, onDisconnect }: { + tab: chrome.tabs.Tab | null; working: boolean; saved: string; + onSave: () => void; onDisconnect: () => void; +}) { + const canSave = Boolean(tab?.url && /^https?:\/\//u.test(tab.url)); return ( -
- - {importNotice && } - {!auth.isAuthenticated ? ( -
- -
- ) : ( - - )} - {error && ( -

- {error} -

- )} -
+<> +

{tab?.title || 'Current page'}

+

{tab?.url}

+ + {saved &&

{saved}

} + {!canSave &&

Open a web page to save its link.

} + + ); } diff --git a/packages/chrome-extension/src/side-panel/App.tsx b/packages/chrome-extension/src/side-panel/App.tsx deleted file mode 100644 index 542563c..0000000 --- a/packages/chrome-extension/src/side-panel/App.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { useCallback, useEffect, useState } from 'react'; -import type { PageContent, AIChatMessage, AuthState } from './lib/types'; -import { DEFAULT_AI_CONFIG } from './lib/types'; -import { loadChatHistory, saveChatHistory as saveChatToStorage } from './lib/storage'; -import { checkAuth, getApiKey } from './lib/api'; -import { getImportNotice, type ImportNotice } from './lib/importQuality'; -import { Chat } from './components/Chat'; -import { PageHeader } from './components/PageHeader'; -import { TTSPlayer } from './components/TTSPlayer'; - -export function App() { - const [page, setPage] = useState(null); - const [loading, setLoading] = useState(true); - const [messages, setMessages] = useState([]); - const [importNotice, setImportNotice] = useState(null); - const [auth, setAuth] = useState({ isAuthenticated: false, user: null }); - - const extractPage = useCallback(async () => { - setLoading(true); - try { - const response = await chrome.runtime.sendMessage({ type: 'GET_PAGE_CONTENT' }); - if (response?.data) { - setPage(response.data); - setImportNotice(getImportNotice(response.data, Boolean(response.fallback))); - const cached = await loadChatHistory(response.data.url); - setMessages(cached); - } else { - setPage(null); - setImportNotice(getImportNotice(null, Boolean(response?.fallback))); - } - } catch { - setPage(null); - setImportNotice(getImportNotice(null)); - } finally { - setLoading(false); - } - }, []); - - useEffect(() => { - // Load config; if an API key is stored, verify it and hydrate user. - getApiKey().then((key) => { - if (!key) return; - checkAuth().then((user) => { - if (user) { - setAuth({ isAuthenticated: true, user }); - } - }); - }); - - extractPage(); - }, [extractPage]); - - // Listen for tab navigation - useEffect(() => { - const listener = (message: { type: string }) => { - if (message.type === 'TAB_UPDATED') { - extractPage(); - } - }; - chrome.runtime.onMessage.addListener(listener); - return () => chrome.runtime.onMessage.removeListener(listener); - }, [extractPage]); - - // Persist chat history - useEffect(() => { - if (page?.url && messages.length > 0) { - saveChatToStorage(page.url, messages); - } - }, [messages, page?.url]); - - const handleAuthChange = useCallback((next: AuthState) => { - setAuth(next); - }, []); - - if (loading) { - return ( -
-
-
- ); - } - - return ( -
- - { - if (!page) return ''; - const title = page.title?.trim(); - const body = (page.textContent ?? '').trim(); - return title ? `${title}.\n\n${body}` : body; - }} - /> - -
- ); -} diff --git a/packages/chrome-extension/src/side-panel/components/Chat.tsx b/packages/chrome-extension/src/side-panel/components/Chat.tsx deleted file mode 100644 index 09087f8..0000000 --- a/packages/chrome-extension/src/side-panel/components/Chat.tsx +++ /dev/null @@ -1,376 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { AlertTriangle, Bot, Loader2, Send, Square, Trash2 } from 'lucide-react'; -import ReactMarkdown from 'react-markdown'; -import remarkGfm from 'remark-gfm'; -import type { PageContent, AIChatMessage, AIConfig, AuthState } from '../lib/types'; -import type { ImportNotice } from '../lib/importQuality'; -import { streamChat } from '../lib/api'; -import { QuickActions } from './QuickActions'; -import { SaveButton } from './SaveButton'; - -interface ChatProps { - page: PageContent | null; - messages: AIChatMessage[]; - setMessages: (messages: AIChatMessage[]) => void; - config: AIConfig; - auth: AuthState; - importNotice: ImportNotice | null; -} - -const stripHTML = (html: string) => - html - .replace(/<[^>]+>/g, ' ') - .replace(/\s+/g, ' ') - .trim(); - -function buildSystemPrompt(page: PageContent | null): string { - if (!page) { - return 'You are an AI assistant. The user has not loaded a page yet.'; - } - - const textExcerpt = (page.textContent || stripHTML(page.content)).slice(0, 4000); - - return [ - 'You are an AI reading assistant embedded in a Chrome extension.', - 'Help the user understand the current webpage.', - 'Keep responses concise and practical.', - 'If you are unsure, explicitly say so.', - '', - `Page title: ${page.title || 'Untitled'}`, - `Page URL: ${page.url}`, - page.byline ? `Byline: ${page.byline}` : '', - '', - `Page content excerpt:\n${textExcerpt}`, - ] - .filter(Boolean) - .join('\n'); -} - -function ChatMessage(props: { - msg: AIChatMessage; - isLast: boolean; - isStreaming: boolean; -}) { - const { msg, isLast, isStreaming } = props; - return ( -
-
- {msg.role === 'assistant' ? ( -
- {msg.content} -
- ) : ( - {msg.content} - )} - {isStreaming && isLast && msg.role === 'assistant' && ( - - )} -
-
- ); -} - -function MessageList(props: { - messages: AIChatMessage[]; - isStreaming: boolean; - chatEndRef: React.RefObject; -}) { - const { messages, isStreaming, chatEndRef } = props; - return ( -
- {messages.map((msg, i) => ( - - ))} -
-
- ); -} - -function ChatInput(props: { - input: string; - setInput: (v: string) => void; - sendMessage: () => void; - stopStreaming: () => void; - isStreaming: boolean; - page: PageContent | null; - error: string | null; -}) { - const { input, setInput, sendMessage, stopStreaming, isStreaming, page, error } = props; - return ( -
- {error && ( -

- {error} -

- )} -
-