1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-12-04 18:56:44 +01:00
Commit graph

242 commits

Author SHA1 Message Date
github-actions[bot]
5628e9d421
chore(nix): yt-dlp 2026.10.21 → 2026.10.26 (#51)
Co-authored-by: thegeneralist01 <180094941+thegeneralist01@users.noreply.github.com>
2026-11-03 20:31:09 +01:00
85b3c958bc fix(flake): update x86_64-linux frontendDepsHash 2026-11-03 19:52:57 +01:00
github-actions[bot]
e6c34c0694
chore(nix): yt-dlp 2026.08.19 → 2026.10.21 (#50)
Co-authored-by: thegeneralist01 <180094941+thegeneralist01@users.noreply.github.com>
2026-10-26 19:11:37 +01:00
3a6dca66d2
fix(llm): saved provider per account, codex trust check, UI-configured OpenAI-compatible endpoint (#49) 2026-10-25 01:01:30 +02:00
ece485539b
feat(frontend): import pasted cookies (extension JSON, Netscape, header string) into cookie rules (#48) 2026-10-24 23:50:25 +02:00
4c85297b74
feat(frontend): dark mode (#47) 2026-10-24 23:15:15 +02:00
f41697c800 fix(twitter): use Cow for tweet metadata to deserialize escaped JSON strings
When tweet text contains JSON escape sequences (such as newlines \n,
escaped quotes \", or unicode escapes), serde_json cannot borrow a &str
slice from the input string because unescaping requires allocation.
Deserializing to borrowed &str returned an error which caused
tweet_metadata_from_json to silently fall back to Default::default(),
producing titles like "Thread by @unknown" or "Tweet — @unknown".

Using std::borrow::Cow<\x27a, str> allows serde_json to borrow unescaped
slices with zero allocation while cleanly allocating for strings with
escaped characters.
2026-10-21 20:45:42 +02:00
8973a514cc perf(twitter): optimize tweet and thread archiving pipeline
Accelerates tweet and thread archiving times by up to 11x on live
Twitter and reduces processing overhead across Python and Rust:

- In-memory GraphQL thread caching: parse and cache all tweets returned
  in TweetDetail conversation timeline (threaded_conversation_with_injections_v2),
  resolving parent/replied-to tweets in threads immediately without
  redundant network round-trips.
- Proactive rate limiting: replace blind 2.0s post-save sleep with proactive
  throttling prior to outgoing HTTP requests, eliminating trailing sleep on
  single tweets and intermediate sleep for cached thread tweets.
- HTTP keep-alive connection reuse: reuse scraper session for downloading
  media assets and avatars, avoiding fresh TCP/TLS handshakes per asset.
- Avatar & media deduplication: skip avatar download if target file already
  exists on disk.
- Lightweight client startup: introduce SimpleTwitterScraper using direct
  httpx.Client with authenticated headers and lazy twitter.scraper fallback,
  eliminating ~30ms of module imports at startup.
- Fast JSON I/O: use orjson for binary JSON parsing and indented serialization.
- Rust database batching: wrap entry creation, blob upserts, artifact
  registration, and run completion in a single SQLite transaction, reducing
  fsyncs from ~19 down to 1.
- In-memory blob caching: cache blob records across tweet artifacts to
  avoid repeated filesystem metadata stats and duplicate upserts.
- Single-pass staging: rewrite and move staged JSON files directly to
  raw_tweets/ in a single pass without intermediate staging writes.
- Zero-copy metadata deserialization: use borrowed TweetJsonMetadata struct
  to extract title/metadata without dynamic Value heap allocations.
- Regex fast paths: add substring gates before compiling/iterating asset regexes.
2026-10-21 20:28:53 +02:00
af6ff514ed
fix: extract titles from large SingleFile pages (#46) 2026-10-15 14:12:32 +02:00
f900d7e0ef
fix: classify HTML pages and reuse probe downloads (#45)
Classify pages when a HEAD response omits Content-Type by probing GET headers. Reuse that GET response for file captures so single-use download URLs are requested only once.
2026-10-14 17:26:47 +02:00
19718cee22
feat: capture browser cookies and localStorage from extension (#44)
Add an optional browser session to captures and the shared in-page dialog. Validate localStorage against the exact page origin, preserve cookie and storage keys, and clean up temporary secret files on failure. Companion extension PR: thegeneralist01/archivr-extension#1.
2026-10-14 16:51:15 +02:00
7c5b4c033c
feat: PUT /summary endpoint for agent-written and hand-edited summaries (#43)
Adds PUT /api/archives/:id/entries/:uid/summary so agents (via the MCP)
and humans (via the web UI) can write or edit entry summaries without
going through a server-side LLM provider.

Core (archivr-core)
- summarizer.rs: EXTERNAL_SUMMARY_KINDS, external_summary_text,
  normalize_external_model — full validation (trim, dedupe+lowercase tags,
  control-char checks, per-field length limits) + 13 unit tests.
- database.rs: extract new_summary_uid(); add insert_completed_entry_summary
  — single-row INSERT with status='completed', prompt_version='external',
  input_sha256='external', all timestamps set to now.

Server (archivr-server)
- routes.rs: ExternalSummaryBody, put_entry_summary_handler. Checks: role
  (USER), entry visibility (hidden→404), kind in [agent|manual], model
  validation, text validation, manual-requires-existing-summary (409).
  Returns 201 + the new EntrySummaryRecord. Route registered alongside
  existing GET+POST.
- entry_access.rs: PUT /summary added to the hidden-entry gate test.
- Three new tokio tests: agent creates and becomes latest, manual requires
  existing summary, body and role validation.

Frontend
- api.js: saveEntrySummary (PUT, kind:'manual').
- ContextRail.jsx: SUMMARY_SOURCE_LABEL (agent/manual labels), three new
  state vars, handleSaveSummary (scoped to selected entry), edit form
  (TL;DR/summary/tags + Save/Cancel), provider controls hidden while editing.
- styles.css: rail-summary-edit-btn, rail-summary-editor and sub-classes.

Companion MCP PR: thegeneralist01/archivr-mcp#1
2026-10-13 19:01:50 +02:00
1c8abddf93
Merge pull request #42 from thegeneralist01/entry-export
feat: entry export (HTML/PDF/Markdown), shared capture progress, and __Host- cookie fix
2026-10-13 15:58:33 +02:00
3779053f53
Bundle extracted fonts in page exports 2026-10-13 15:49:00 +02:00
0ec242e31d
fix: scope active capture jobs to their creator 2026-10-13 15:00:00 +02:00
8c8c084e9c
fix: fence plain text in Markdown exports 2026-10-13 14:55:40 +02:00
cfc87e9859
fix: stop thread export traversal at visited posts 2026-10-13 14:52:40 +02:00
e8767d221e
fix: close entry export dialog for public sessions 2026-10-13 14:49:09 +02:00
b4bce15f66
fix: preserve SRT subtitles in entry export bundles 2026-10-13 14:42:35 +02:00
bf8ef34a7a
Revert "fix: keep generated static assets out of entry export PR"
This reverts commit 78d003fb12.
2026-10-13 14:35:19 +02:00
78d003fb12
fix: keep generated static assets out of entry export PR 2026-10-13 14:31:41 +02:00
b8397ad8f8
feat: remove PDF from export (HTML and Markdown only) 2026-10-12 21:40:09 +02:00
f7e9a0ef25
fix: move Export to Actions section, fix Export\u2026 text rendering 2026-10-12 21:10:54 +02:00
2115a70343
fix: handle __Host- cookies correctly for single-file captures
Chrome's CDP Network.setCookies rejects __Host- prefixed cookies that
carry a domain attribute — the prefix semantically forbids domain binding.
The previous Netscape cookie file always emitted a domain column, causing
setCookies to fail with "Invalid cookie fields" and the capture to
produce no output file.

Switch single-file's cookie file to JSON format (single-file tries
JSON.parse first, falls back to Netscape text parsing). JSON gives
per-cookie field control:

- __Host- cookies: {url, path: "/", secure: true}, no domain field.
  url is the https page URL (synthesised as https://hostname/ when the
  page URL is non-https, since __Host- requires https anyway).
- __Secure- cookies: {domain, path: "/", secure: true}.
- All other cookies: {domain, path: "/"} — unchanged behaviour.

yt-dlp still receives the existing Netscape file; only the single-file
path is affected.

Add four unit tests covering __Host-, __Secure-, regular cookies, and
the http→https url fallback.
2026-10-12 20:00:06 +02:00
e40312734d
feat: entry export (HTML / PDF / Markdown) with quiet Archivr credit
Adds a self-contained export feature across core, server, CLI, and frontend.
Users can export one or more archived entries as a shareable bundle without
exposing the Archivr instance. A small 'Preserved with archivr' credit is
included by default and can be toggled off per export.

Core (crates/archivr-core/src/export/):
- brand.rs   — export CSS (palette from style-guide), CREDIT_HTML,
               CREDIT_INLINE_HTML (for snapshot injection)
- model.rs   — ExportEntry / ExportBody / Asset loading; tweet thread
               reconstruction (reply-graph DFS, sibling ordering)
- html.rs    — full HTML document renderer: all body kinds, AssetMode
               Bundle vs Print, render_cover for PDF cover pages
- markdown.rs — Markdown renderer with poster-linked video, blockquoted
               quote tweets, credit sub-tag
- bundle.rs  — ZIP writer (Deflated for text, Stored for binary,
               large_file for >= 4 GiB assets)
- pdf.rs     — print_pdf (headless Chrome), merge_documents (lopdf
               ID-offset merge), entry_pdf (snapshot injection,
               PDF-merge, HTML fallback)
- mod.rs     — export_entries, prune_stale_export_dirs, ExportFile,
               ffmpeg poster generation, full assembly dispatch

summarizer.rs: extract pub(crate) article_parts so the export module
reuses the article title/body logic without duplication.

Server (crates/archivr-server/src/exports.rs):
- GET /api/archives/:archive_id/export?entries=&format=&layout=&credit=
- Auth required (guests -> 401); per-UID ensure_entry_visible check
- Blocking spawn_blocking task; streaming response via ReaderStream
- ARCHIVR_EXPORT_PDF_TIMEOUT added to ENV_VARS (default 120 s)
- ARCHIVR_CHROME description updated to mention PDF export
- prune_stale_export_dirs called at startup (6 h TTL)

CLI (crates/archivr-cli/src/main.rs):
  archivr export <UIDs...> [--format html|pdf|markdown]
                           [--separate] [--no-credit] [-o DIR]

Frontend:
- api.js: downloadEntryExport (blob + filename from Content-Disposition)
- ExportDialog.jsx: native <dialog>; format selector; Combine toggle
  (>= 2 entries); credit toggle (on by default); error display
- ContextRail.jsx: single-entry Export... button after Preview; bulk
  Export N entries... section before delete zone; orderedSelection
  helper for DOM-order UIDs; ExportDialog mounted once per rail
- styles.css: .rail-export-btn, .export-dialog .export-format rules

Tests:
- 9 new cargo tests in export/mod.rs (HTML, Markdown, PDF merge,
  parent-child dedupe, separate layout, credit on/off, validation)
- 4 new cargo tests in exports.rs (401 no-auth, 200 ZIP, 400 bad
  format, 400 too many entries)
- 4 new bun tests in ExportDialog.test.jsx (single/multi uid, credit
  default, closed state)
- 2 new bun tests in api.test.js (query string, error propagation)

All 247 Rust tests and 50 frontend tests pass.

MCP follow-up: archivr-mcp export_entries tool (GET /api/.../export,
read-scope tokens accepted) — not built here.
2026-10-12 19:51:15 +02:00
64ef4ca313
feat: show in-progress captures to all authorized users
Store the locator in notes_json immediately on job creation so other
users have a display label. Add list_active_capture_jobs (no creator
scoping) and a status=active shorthand on the job list endpoint so any
ROLE_USER can poll pending+running jobs for the current archive.

Frontend polls GET /api/archives/:id/capture_jobs?status=active every
3 s, injects SkeletonEntryRow for foreign jobs (not in local
pendingCaptures), and refreshes the entry list when a foreign job
settles.
2026-10-12 15:54:58 +02:00
151c18eb61
feat: improve archived X thread rendering (#41)
* ui: render archived X threads as conversations

* fix: keep related thread posts accessible offline
2026-10-11 13:13:18 +02:00
63b0480fd8
docs: add ecosystem change review guidance 2026-10-10 17:39:30 +02:00
3b748fb1d7
feat: Chrome extension capture and MCP management APIs (#40)
Add authenticated capture options and manual text-title generation, reusable capture dialogs and URL-prefilled captures, and X status-URL parsing and whole-tweet capture fixes.

Extend user/role administration, sessions, expiring read/full API tokens, capture job/run listing, archive information and effective configuration for MCP clients. Add frontend session, token and user-deletion controls.

Enforce entry/blob visibility and staged-upload restrictions. Retire custom-role bits, serialize last-owner checks with writes, protect collection deletion against self-lockout, and revalidate media-token issuer access on use.

Re-reviewed at 5516506ea9: all four prior findings resolved, independent auth/access reviews report no remaining blockers. Validation: 738 Rust tests, 34 frontend tests and production frontend build passed.
2026-10-10 11:31:05 +02:00
094f1b0457
feat: add YouTube subtitles, local transcription, self-updating yt-dlp/Deno, X Article and thread titles (#39)
- Capture YouTube subtitles by default (opt-out in UI, API, CLI --no-subtitles)
- Summarize YouTube videos from subtitles; fetch on demand, then local transcription, then error
- Local transcription fallback: Whisper, Parakeet, Phonon-2 (English only)
- Runtime-resolved, self-updating yt-dlp and Deno JS runtime (fixes YouTube 403s)
- Settings > Instance > yt-dlp: status and in-app update without restart
- X Article titles from article.title, with idempotent startup backfill
- Thread title generation (single and bulk) with per-provider cheap models
- Per-provider title model settings in Settings > Instance
- Docs, mental model, AGENTS.md and transcription spec updated
2026-10-05 19:41:06 +02:00
4f3b2968b6 build: build frontend in Nix, remove static from git tracking
Add frontendDeps (FOD) and frontendStatic derivations to flake.nix so
that nix build handles the Vite bundle automatically. The archivr_server
derivation now copies from ${frontendStatic} instead of
${./crates/archivr-server/static}.

crates/archivr-server/static/ is excluded from git tracking (.gitignore);
the aarch64-darwin node_modules hash is included. Other systems use a
placeholder hash — run `nix build 2>&1 | grep 'got:'` to obtain theirs.

Update AGENTS.md and docs/README.md to reflect the new workflow.
2026-10-04 22:53:49 +02:00
699eb7f62d feat: reorder child entries with a configurable role permission
- Persist sibling order for child entries (archived_entries.position):
  backfilled to the previous archived_at order, new children appended
  (initial playlist order kept; sync appends after user order).
- PUT /api/archives/:id/entries/:uid/children/order takes the full child
  UID list in one IMMEDIATE transaction (401 guest, 403 role not allowed,
  404 unknown or invisible parent, 400 unless exactly the current children).
- Reorder permission is a role mask in the auth instance settings
  (reorder_children_role_bits, default Admin|Owner). Only the Owner can
  change it, built-in or custom roles, never Guest. /api/auth/me and login
  expose can_reorder_children. Settings PATCH is now one IMMEDIATE txn.
- Main page: drag handle for mouse/trackpad on viewports >640px, up/down
  arrows otherwise (pure CSS, arrows are the fallback), Alt+Up/Down
  everywhere; optimistic with revert. Settings > Instance > Permissions
  for the Owner (read-only for admins).
- Fix: renaming a child entry now updates its row immediately.
- Remove Storybook (deps, config, stories, docs).
2026-10-04 20:55:37 +02:00
8fc6754e28
feat(capture): route x.com status URLs to Source::Tweet
Full https://x.com/{user}/status/{id} URLs now go through the Twitter
JSON scraper (Source::Tweet) instead of yt-dlp (Source::X), consistent
with the x:tweet:ID shorthand. Non-status x.com URLs are unchanged.

tweet_id_from_archive_path extended to extract the numeric ID from full
status URLs, not just colon-separated shorthands.

x:media:ID remains the explicit opt-in for yt-dlp media-only capture.
2026-10-04 18:33:48 +02:00
c68469783c
chore(docker): pin yt-dlp and twitter-api-client versions to match Nix
- yt-dlp: pip install yt-dlp → yt-dlp==2026.8.19 (matches flake.nix pin)
- twitter-api-client: unpinned → 0.10.22 (matches flake.nix)
- docs: add Docker subsection to 'Keeping yt-dlp fresh' explaining that
  rebuilding the image is the Docker equivalent of the Nix/self-update
  paths, and that there is no in-container yt-dlp update path
2026-10-04 17:55:46 +02:00
archivr-qa
9b2ecb8d7b
fix: guard detailMatchesSelection against null detail/selectedEntry
When both detail and selectedEntry are null (initial render or mid-navigation
while a detail fetch is in flight), detail?.summary?.entry_uid and
selectedEntry?.entry_uid both evaluate to undefined, making the equality
true and causing a crash on detail.latest_summary.

Add selectedEntry?.entry_uid != null guard so the condition short-circuits
false whenever there is no real selection.
2026-08-28 20:25:41 +02:00
79ac44834e
feat: capture, summaries, search, and yt-dlp reliability (#38)
* ui: show spinner for pending captures

* feat(core): add text capture path with title + Markdown/plain body

- Add downloader/text.rs module with save() function that stages and hashes text content
- Support text/markdown and text/plain MIME types with .md and .txt extensions
- Add perform_text_capture() function for capturing user-supplied text
- Validates title (non-empty, max 500 chars) and body (non-empty, max 2 MiB)
- Creates blob records and entries with source_kind='text', entity_kind='document'
- Includes comprehensive unit tests for markdown, plain text, and validation

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* feat(server): add POST /api/archives/:archive_id/captures/text

- Add CaptureTextBody struct for title, body, and optional MIME type
- Implement capture_text_handler with validation for empty fields and MIME type
- Route text submissions to perform_text_capture() in background
- Reuse existing capture job tracking and polling infrastructure
- Default MIME type to text/markdown when not specified
- Include route tests covering happy path, validation, auth, and error cases

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* feat(frontend): add text-capture form to CaptureDialog

- Add submitTextCapture API client function with same error handling as submitCapture
- Create makeTextItem() factory for text capture state
- Implement CaptureTextRow component with title, body textarea, and MIME selector
- Add 'Add text' button in capture dialog toolbar
- Update handleArchive to filter and route text submissions
- Modify submitBgJob to detect and submit text items via submitTextCapture
- Skip probe and conflict checks for text items
- Reuse job tracking and batch settlement for text captures

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* feat(core): add entry_summaries schema + summarizer trait/providers

Per-entry LLM summaries as a regenerable child record, not a column on
archived_entries and not an on-disk artifact: an entry may carry several
summaries (one per provider/model/prompt version), any of which can be
discarded and recomputed. Generation is manual-only — nothing in capture.rs
calls into this module.

- database.rs: entry_summaries table + index, EntrySummaryRecord, and
  upsert/update/find/latest helpers mirroring the capture_jobs style.
  provider_model is stored as '' rather than NULL because SQLite treats
  NULLs as distinct inside a UNIQUE index, which would stop the CLI
  providers (no model) from ever deduping on the cache key.
- summarizer.rs: SummaryProvider trait with four implementations —
  Anthropic Messages API, OpenAI-compatible chat completions, `claude -p`
  and `codex exec -`. Configuration comes from env vars only (never TOML),
  matching how yt-dlp / single-file / tweet-scraper are resolved, which
  also keeps API keys out of anything the archive persists.
- archive.rs: EntryDetail gains latest_summary, populated by one extra
  LIMIT 1 query in get_entry_detail. EntrySummaryView aliases the DB row
  rather than duplicating it.

Implementation notes:
- No tokio in core. CLI timeouts are enforced structurally: stdout is
  drained on its own thread and handed back over a channel so the calling
  thread can recv_timeout and kill an overrunning child; stdin is written
  on a third thread so a 48 KB prompt cannot deadlock against a child
  waiting for us to read.
- HTML is reduced with regex rather than a parser: html5ever is not in the
  tree, and a model tolerates imperfect whitespace. Paired tags are spelled
  out per tag because Rust's regex engine has no backreferences by design.
- reqwest is declared with only the `blocking` feature here, so bodies are
  serialized via .body(value.to_string()) instead of widening the
  workspace dependency for .json().
- input_sha256 holds a SHA3-256 digest via hash::hash_bytes, the tree's one
  hashing primitive; the content is truncated to 48 KB *before* hashing so
  the cache key describes exactly the bytes the model saw.

Tests: no mockito/wiremock in dev-deps, and adding a mock HTTP server for
one JSON shape is a poor trade, so the two halves that can actually break
are tested directly — request-body builders and response parsers — leaving
only reqwest's own transport uncovered. Plus schema idempotency, cache-key
dedupe, cascade-on-delete, provider_from_env happy/missing-var paths, HTML
and tweet extraction, output normalization, and the CLI runner's stdin
round-trip, timeout kill, and nonzero-exit paths.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(server): add GET/POST /api/archives/:id/entries/:uid/summary

GET is read-only and gated exactly like entry detail, so a guest can read a
summary only for an entry whose content they could already read. POST
requires ROLE_USER, matching capture / tags / patch / rearchive; no auth
roles change.

Both the provider config and the content extraction resolve on the request
thread, before spawn_blocking. That is what lets a missing env var come back
as a synchronous 400 naming the exact variable, and an unsummarizable
artifact (video, audio) as a 400 saying so, rather than becoming a
background job the caller must poll only to learn about a config typo.

The pending row is claimed before spawning so the 202 can name a summary_uid
the client can poll immediately. summarize_entry owns the
pending → running → completed/failed transitions for that same row — the
cache key is identical, so both upserts resolve to one row — leaving the
handler to catch only the case where it fails before recording anything.
When !force and an identical cache key already completed, the existing row
comes back as a 200 with no new work.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(frontend): render Summary rail section + provider selector

New "Summary" rail section between the URL/Preview controls and .meta-list.
A completed summary renders as bold tl;dr, body paragraph, tag chips, and a
provider · model footer; missing or failed shows Generate; pending/running
shows an inline spinner and polls GET every 1500 ms until terminal.

- api.js: fetchEntrySummary + requestEntrySummary. The POST helper unwraps
  ApiError's { "error": ... } body so the missing-env-var message reaches
  the user verbatim rather than as a bare status code.
- ContextRail.jsx: state seeds from detail.latest_summary so the section
  renders immediately on selection. Polling is anchored on the summary
  status rather than started inside the click handler, so a job still
  running when the user navigates away and back is picked up again. A
  transient poll failure is swallowed — the next tick retries, and a real
  failure arrives as status === 'failed'.
- Regenerate passes force:true only when a completed summary is already
  shown; otherwise the request can take the server's 200 cache-hit path.
- Provider choice persists in sessionStorage under archivr:summary:provider,
  with try/catch around both accessors for private-mode browsers.
- Public sessions never see the selector or the Generate button, and the
  section renders at all only when a completed summary made it through the
  server's visibility gate.
- styles.css: .rail-summary-* only; spacing and the action button reuse
  .rail-section and .rail-rearchive-btn. The spinner honours
  prefers-reduced-motion — the text alone conveys the state.
- AGENTS.md: document the summary env vars alongside the existing
  external-tool convention.

Smoke-tested end to end against a scratch archive with a seeded markdown
entry: claude_cli produced a real summary (pending → running → completed in
~11s); a local mock server exercised the openai_compatible transport and
confirmed the Bearer header, model, and system/user role split on the wire;
unconfigured providers return 400 naming the exact variable; a video entry
returns 400 "v1 unsupported"; a repeat POST returns 200 from cache without
adding a row.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(core): codex_cli — auto-discover binary + use --output-last-message

Two related fixes for the codex_cli summary provider:

1. Executable discovery. `ARCHIVR_CODEX_CLI` was already respected, but
   without it the code resolved to bare `codex` and relied on PATH.
   The ChatGPT desktop app installs codex at
   `/Applications/ChatGPT.app/Contents/Resources/codex` and does not
   put it on PATH, so users who only have the desktop app saw
   'No such file or directory' with no hint. `resolve_cli` now walks
   env override → a small set of well-known absolute paths → HOME
   /.local/bin/<bare> → bare fallback. Same treatment applied to
   claude_cli for symmetry (/opt/homebrew/bin/claude, /usr/local/bin/
   claude, HOME/.local/bin/claude).

2. Clean output. `codex exec -` writes a runtime header ("OpenAI
   Codex vX", session id, sandbox, model), the assistant reply, and a
   footer ("tokens used", replay of the reply) to stdout. The JSON
   extractor took the first '{' from the *user prompt echo* and the
   last '}' from the trailing replay, producing invalid text that
   fell through to the "raw text under summary" fallback path. Now
   uses `--output-last-message <tempfile>` and reads only the final
   assistant message. Fallback (positional prompt) uses the same
   flag. Tempfile is cleaned up on all paths, incl. spawn failure.

* fix(frontend): give text-capture row real CSS

The text row shipped with semantic classnames (`capture-text-inputs`,
`capture-text-title`, `capture-text-body`, `capture-text-mime`,
`capture-text-icon`) but no CSS rules. Falling through to the parent
`.capture-row-main` flex-row (`display: flex; align-items: center`)
meant the title, textarea, and mime-select stacked as intrinsic-width
boxes centered on the tall body, producing a layout where the body
floated to the top-right, the title box appeared BELOW it, and the mime
selector rendered as an unstyled OS dropdown.

Fix:
- `.capture-text-row .capture-row-main` uses `align-items: flex-start`
  so the leading icon and trailing × pin to the top of the block.
- `.capture-text-inputs` is now a full-width column-flex container with
  proper gaps.
- `.capture-text-title` reuses the 44px input height and typography of
  `.capture-input`; `.capture-text-body` gets a 140px min-height,
  vertical resize, and matching border/focus treatment.
- `.capture-text-mime` is styled as a small chip with a custom caret
  so it matches `.capture-quality` and stops looking like a raw
  `<select>`. Sits in a right-aligned footer under the body.
- `.capture-text-icon` gets a 44px column so it aligns with the title
  input; remove button gets a small top-margin for the same reason.

Rebuilt static bundle bumped as well (`index-BLxoi9rt.css`,
`index-CQcpPA_I.js`).

* chore(static): rebuild bundle after text-row CSS merge

* fix(core): summarize tweets + walk all tweets in a thread

Tweet and tweet_thread entries store their payload under artifact_role
`raw_tweet_json`, not `primary_media`. `build_summary_input` filtered
strictly for `primary_media LIMIT 1`, so both cases silently failed
with 'entry X has no primary_media artifact to summarize'.

Threads compound the problem: the tweet scraper writes ONE json file
per status, so even a fixed lookup that took the first row would
summarize only the initial tweet and lose the rest of the conversation.

Fixes:
- New `load_summary_artifacts` helper returns every artifact for a
  role in insertion order.
- For entity_kind `tweet` / `tweet_thread`, load all
  `raw_tweet_json` artifacts (falling back to `primary_media` for
  archives predating that role convention).
- Iterate artifacts, extract text per file with the existing
  markdown/html/json branches, then join thread pieces with a
  `---` separator so the model sees a real paragraph break between
  statuses instead of one flowing document.

Single-tweet entries produce one piece and the separator never
renders. Non-tweet entries behave exactly as before.

* feat(frontend): preview text-capture entries (.md / .txt)

Text captures land as `.md` (Markdown) or `.txt` (plain) blobs, but
PreviewPanel only dispatched on video/audio/image/pdf/html extensions,
so opening a text entry hit the 'No preview available' fallback with
the raw artifact path exposed.

- New `TextPreview` component fetches the primary artifact as text,
  renders it in a monospace `<pre>` with word-wrap, and shows the
  entry title on top and the MIME as a small trailing tag. Handles
  loading/error states.
- `PreviewPanel` gains a `TEXT_EXTS` set + a branch that dispatches
  to `TextPreview` for `md` / `markdown` / `txt`.
- CSS is padded and centered to ~780px so a text note reads like a
  document rather than an edge-to-edge terminal dump.

v1 intentionally does NOT parse Markdown: keeping frontend deps at
react+react-dom only. Bump to a real Markdown renderer if we start
capturing Markdown-authored notes.

* fix(nix): pin yt-dlp from its own release + wire into server wrapper

Two independent problems, one commit:

1. Stale binary. nixpkgs-provided `pkgs.yt-dlp` on the pinned
   nixos-unstable rev is 2026.03.17 (Mar 2026). yt-dlp itself
   releases days-to-weeks, and YouTube frequently rotates the
   player-signature / client surfaces the older builds request
   (`android_vr` is the current casualty), which returns HTTP 403
   mid-download for the format specs archivr passes (`-f
   bestvideo+bestaudio/best`). Even bumping the nixpkgs input would
   leave us dependent on that channel's yt-dlp cadence.

   Fetch the upstream zipapp directly instead
   (github.com/yt-dlp/yt-dlp/releases/download/<ver>/yt-dlp), wrap so
   `python3` and `ffmpeg` are on PATH, and pin version+hash in one
   place. Bumping is: change version, replace hash from
   `nix hash file <url>`.

2. Missing pin in server wrapper. `archivr-cli` was already wrapped
   with `--set ARCHIVR_YT_DLP` + a PATH prefix; `archivr-server`
   was NOT — it only pinned single-file, chrome, and the tweet
   scraper, silently falling back to whatever `yt-dlp` the user
   happened to have on PATH. Server captures therefore inherited
   the user's (often stale) system yt-dlp regardless of the flake
   pin. Same wrapper flags now apply to both binaries.

devShell keeps `pkgs.yt-dlp` for now: the dev shell is a
convenience, not a release surface, and matching wouldn't fit in this
commit without duplicating the derivation across let-scopes.

* chore(static): rebuild bundle for round-3 fixes

* chore(nix): pin python 3.12 for yt-dlp zipapp (avoid py3.14 libffi crash on darwin/arm64)

* feat(core): resolve_yt_dlp picks the newer of pinned vs state-dir

The nix flake wrapper pins a yt-dlp via ARCHIVR_YT_DLP, but yt-dlp rots
fast — extractors break within weeks of a pin. Add a resolver that probes
`--version` on both the pinned binary and a user-installed copy under the
mutable state dir, and runs whichever is newer.

Version strings are YYYY.MM.DD, so plain string ordering is chronological.
Ties resolve toward the state dir: a user who installed it there did so
deliberately. ARCHIVR_YT_DLP_FORCE bypasses the comparison entirely, and
with no candidate at all we fall back to bare `yt-dlp` on PATH — exactly
the previous behaviour.

Resolution is cached in a OnceLock so `--version` costs one subprocess per
process, and all four inline env::var lookups now go through it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* ci: bump yt-dlp from upstream releases, not nixpkgs

The flake no longer takes yt-dlp from nixpkgs; a dedicated `ytDlp`
derivation fetches the upstream release binary directly and pins both
`version` and an SRI `hash`. That makes the previous workflow inert: it
ran `nix flake update nixpkgs` and compared `nixpkgs#yt-dlp.version`
before and after, so it could churn the lockfile forever without ever
moving the version we actually ship.

The workflow now reads the pinned version straight out of the `ytDlp`
block in flake.nix, asks the GitHub API for yt-dlp's latest release tag,
short-circuits when they already match, downloads the new release to
recompute its SRI hash (required — the hash is part of the derivation's
identity, so the URL cannot be changed alone), and rewrites the three
pinned fields under a sed range address scoped to that block so sibling
pins like ublockLite and isdcac are untouched. It asserts only flake.nix
changed and that the new version appears exactly twice before opening
the PR.

* feat(cli): add `archivr yt-dlp update|status` subcommand

`update` fetches the latest release tag from the GitHub API (or takes
--version), downloads the cross-platform python zipapp, and installs it
into archivr's state dir. The install is atomic — staged as yt-dlp.new,
chmod +x'd, then renamed over the target — so a concurrently running
capture never sees a half-written binary. A sibling .version file makes a
repeat update a no-op instead of a 3MB re-download.

The download is checked for the python3 shebang before install, which
catches the usual failure mode of getting an HTML error page back. python3
itself is only warned about, not required: the server may run under a nix
wrapper with its own PATH.

`status` prints all three candidates (env / state-dir / PATH fallback) with
their versions and stars whichever the resolver picks, so it is obvious
which yt-dlp a capture will actually use.

reqwest is pulled from the existing workspace dependency; the GitHub JSON is
parsed with serde_json so the "json" feature is not needed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(maintainer): document summarizer, text capture, and yt-dlp lifecycle

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(readme): document LLM summaries, text notes, yt-dlp resolver + bump paths

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(plan): specify X Article, image summaries, summary search

* fix: summarize X Article text

* feat: search completed summary tags

* fix: preserve X Article block order

* feat: model opt-in summary images

* feat: attach opted-in images to summaries

* feat: accept image summary requests

* feat: add summary image consent control

* docs: explain X Article, image summaries and summary search

* chore(static): rebuild bundle for summary image consent

* fix: show civilized unsupported summary errors

* chore(static): rebuild bundle for civilized summary errors

* fix: keep text previews and summary state scoped to entry

* fix: show forced yt-dlp candidate in status

* fix: infer trusted MIME for tweet images

* fix: preserve text capture bytes and hide synthetic URL

* fix: recover and preserve summary attempts

* fix: bound codex fallback and record resolved model

* fix: protect public summary diagnostics

* fix: guard summary callbacks during entry render

* fix: scope summary callbacks to selected entry

* test: cover terminal newline in text capture

* fix: preserve missing summary entry status

* test: cover tweet image summary selection

* docs: record summary lifecycle and review hardening

* chore(static): rebuild bundle for Sol review fixes

* fix: retain completed summary during regeneration display

* fix: hide superseded summary attempts

* chore(static): rebuild bundle after regeneration display fix

* fix: allow full-size text capture requests

* fix: allow escaped full-size text captures

* fix: preserve text draft whitespace in capture UI

* chore(static): rebuild bundle for text whitespace fix
2026-08-24 18:30:01 +02:00
github-actions[bot]
b4b4e67157
chore: yt-dlp 2026.07.04 → 2026.08.19 (#37)
Co-authored-by: thegeneralist01 <180094941+thegeneralist01@users.noreply.github.com>
2026-08-24 14:59:35 +02:00
bf5f95397f
fix: exclude child entries from collection listing
list_entries_for_collection was missing AND e.parent_entry_id IS NULL,
causing child entries (playlist/channel videos) to appear alongside
their parent in the flat archive view. list_root_entries and
search_entries already had this guard; the collection path did not.

Also removes garnix from flake.nix nixConfig.
2026-08-02 11:23:13 +02:00
95cd46978d
feat(core): add more Freedium domains + restrict Freedium routing to supported domains (#36)
Previously, any WebPage capture with via_freedium=true was routed
through the Freedium mirror regardless of the URL's host. This caused
non-paywall sites like borretti.me to be fetched through Freedium,
which is wrong — Freedium only knows how to handle a specific set of
publications.

Add is_freedium_supported_url() with a static allowlist of the 7 hosts
Freedium explicitly supports per its homepage announcement:

  Medium, NYT, WaPo, Bloomberg, Reuters, Economist, Financial Times

The gate matches on the bare domain or any subdomain (e.g.
towardsdatascience.medium.com). Unparseable URLs fall through to a
direct fetch. The existing freedium-mirror.cfd re-wrap guard is kept
as a belt-and-suspenders check after the new allowlist test.

Fixes: https://borretti.me/article/notes-on-managing-adhd archived via
Freedium despite not being a Medium article.
2026-07-29 17:40:07 +02:00
6a0f59ea94
docs: tighten wordmark tracking (24→10px, 0.14→0.06em) 2026-07-26 16:27:54 +02:00
eb5c774d0d
docs: scale banner to fill GitHub 838×279px display
Measured actual GitHub display: 838×279px at 1365px viewport.
Previous content (mark=216px, wordmark=132px) rendered at 83px/51px —
too small for the available space.

New target sizes calibrated to display dimensions:
  mark       216 → 285px target  →  110px at 838px display  (+32%)
  wordmark   132 → 170px target  →   55px height at display  (+35%)
  tagline     62 →  78px target  →   30px at display         (+26%)
  A in mark  160 → 210px target

Reduced inter-element gaps to keep content within 724px height;
fills ~84% of banner, leaving ~23px display margin each side.
2026-07-25 22:01:02 +02:00
cab544c76f
docs: scale up banner content for GitHub display size
At GitHub's ~840px README width, 2172×724 renders at 840×280px.
Previous element sizes (mark 130px, wordmark 80px) became 50px and 31px
at display — too small to read clearly.

Scale everything ~1.65× to fill ~80% of banner height:
  mark       130 → 216px at target  (≈ 83px at 840px display)
  wordmark    80 → 132px at target  (≈ 51px at display)
  tagline     38 →  62px at target  (≈ 24px at display)
  A in mark   96 → 160px at target

Proportional gap increases maintain the same visual rhythm.
2026-07-25 21:52:56 +02:00
13b22bc6f8
docs: redesign banners — logo mark, flat bg, no chrome artifacts
Previous version had three inelegancies visible on GitHub:
- Full-width ghost rule read as an artifact dividing the banner in half
- Top terracotta bar looked like site header chrome
- Radial gradient created compression banding at CDN quality

v5 design:
- Terracotta rounded-rect logo mark (130px) with Paper 'A' inside —
  the actual brand element per the style guide, not a floating letter
- Flat Shell / Paper background — compresses losslessly, zero banding
- No top bar, no ghost rule, no gradient gimmicks
- Same crisp Cormorant Garamond SemiBold + 2x supersample + Lanczos
- Both dark and light variants updated with identical layout
2026-07-25 21:42:49 +02:00
820260bc9c
docs: redesign banners with Cormorant Garamond + 2x supersample
Dark banner:
- Replace Georgia with Cormorant Garamond SemiBold (actual brand font)
- 2x supersample render → Lanczos downsample for crisp edges at all
  display densities
- Shell (#141d18) background with layered radial warmth
- Editorial stacked colophon layout: large 'A' / thin parchment rule /
  wide-tracked wordmark / amber italic tagline
- Ghost full-width hairline rule anchors the horizontal composition
- Terracotta dash ornaments flank the tagline (composited on separate
  RGBA layer for correct alpha blending)

Light banner (new PNG, replacing SVG):
- Same font, supersample, and layout
- Paper (#f5f0e7) background with subtle warm edge shadow
- Ink wordmark, Muted tagline — all brand palette

README: switch light-mode fallback from banner-light.svg to banner-light.png
2026-07-25 21:21:32 +02:00
1ff85f53c4
docs: redesign dark banner — editorial colophon layout
Replace app-icon-style horizontal lockup with centered stacked
composition: large standalone terracotta 'A' mark → thin parchment
rule → wide-tracked cream wordmark → amber italic tagline.

Edge-darkening vignette clears the center and frames the bokeh
atmosphere without muddying the text zone.
2026-07-25 21:01:38 +02:00
221f6cccce
docs: composite bokeh library background into dark-mode banner
Render generated-image.png (blurred library bokeh, prompt 3) as the
dark-mode README banner with logo mark, wordmark, tagline, and
terracotta top rule composited on top via Pillow.

Switch README dark-mode <source> from banner-dark.svg to banner-dark.png.
Light-mode banner stays as the clean Paper SVG.
2026-07-25 20:49:24 +02:00
0e18b294dd
docs: rewrite README with brand identity and proper project structure
- Add logo (SVG lockup), tagline, and brand-colored badges at top
- Replace dev checklist with prose Features section
- Add Architecture section with binary overview and on-disk layout
- Consolidate Supported Inputs into a table with inline shorthand examples
- Rewrite env vars as a scannable table
- Restructure into clear Quick Start → Architecture → Inputs → Config → Deployment → Development flow
- Remove personal motivation text and developer-facing in-progress notes
2026-07-25 20:36:16 +02:00
fa0340cef2
chore: add brand identity, style guide, and favicon (#35)
* Add Archivr brand identity and favicon

- Brand style guide (docs/branding/style-guide.html): logo, clear
  space, don'ts, color palette, typography, in-context mockup
- Logo assets (docs/branding/assets/): lockup SVGs for dark/light
  backgrounds, standalone mark, favicon.svg, multi-size favicon.ico
- Wire favicon into frontend/index.html (SVG + ICO fallback);
  frontend/public/ seeded so Vite copies assets on next build
- Revert display strings archivr back to Archivr in UI
  (Topbar, LoginPage, SetupPage, index.html titles, flake.nix)
- Update .gitignore to allow docs/branding/

* Build frontend with favicon links and assets

* Fix static file serving: serve all of static/ with SPA index.html fallback

Previously only /assets/* was served from disk; all other paths
(including /favicon.ico, /favicon.svg) hit the index.html fallback.
Replace nest_service("/assets") + fallback_service(index.html) with
ServeDir on the full static dir and not_found_service(index.html),
so any file that exists in static/ is served directly.
2026-07-25 15:31:25 +02:00
e1ee05bd41
feat(collections): public collections, per-collection auth, UX improvements (#34)
* feat(core): add requires_auth to collections; include name in entry-collection memberships

- Add `requires_auth INTEGER NOT NULL DEFAULT 1` column to the
  collections DDL and as an idempotent ALTER TABLE migration in
  initialize_schema (archive DB), not initialize_auth_schema.
- CollectionRecord and CollectionSummary gain `requires_auth: bool`.
- create_collection() and update_collection() accept the new field.
- get_entry_collection_memberships() now returns collection name as the
  third tuple element; EntryCollectionMembership gains a `name` field
  so the sidebar can show human-readable names instead of raw UIDs.

* feat(server): conditional auth for public collections; add requires_auth + original_url to API

- CreateCollectionBody gains requires_auth (default true).
- PatchCollectionBody gains requires_auth: Option<bool>.
- get_collection_handler: load record first, then skip auth.require_auth()
  when record.requires_auth == false so public collections are accessible
  to unauthenticated callers; caller_bits falls back to ROLE_GUEST (1)
  so only visibility_bits=3 entries are returned to guests.
- Collection JSON response includes requires_auth and each entry now
  includes original_url for use by the public collection page.
- list_collections_handler keeps require_auth (management UI).

* feat(frontend): public collection page at /c/:archiveId/:collUid

- Detect PUBLIC_COLL_ROUTE at module load time (like PREVIEW_ROUTE) and
  return <PublicCollectionPage> before any auth checks so unauthenticated
  users can view public collections without hitting the login gate.
- PublicCollectionPage fetches via getCollection() and renders the
  server-filtered entry list (no client-side bitmask filtering - the
  server already applies caller_bits=GUEST for unauthenticated requests).
  Entry titles link to original_url when present; fall back to plain
  text when original_url is null.
- api.js createCollection() gains requiresAuth param (default true),
  sent as requires_auth in the request body.
- Storybook story covers WithEntries, Empty, and LoadError states.

* feat(frontend): collections view improvements

- addVis in the 'Add entry' form now syncs to the selected collection's
  default_visibility_bits via useEffect on collDetail, so the default
  matches the collection's configured entry visibility.
- Rename 'Default visibility' label to 'Entries\' default visibility'
  in both the detail pane and the create form to distinguish it from
  the new collection-level access setting.
- Add 'Require authentication to view' checkbox in the detail pane
  backed by a PATCH to requires_auth; reads collDetail?.requires_auth
  with fallback to the list-level selected record.
- Create form gains a matching requires_auth checkbox (default: true),
  passed as 5th arg to createCollection().

* feat(frontend): context rail collection improvements

- Show collection name (c.name) instead of raw UID in the sidebar
  Collections section; names now come from the updated
  EntryCollectionMembership API response.
- Fix horizontal overflow on long collection names: coll-name gains
  overflow:hidden + text-overflow:ellipsis + white-space:nowrap +
  min-width:0; coll-row gets overflow:hidden.
- Single-entry 'Add to collection' UI: dropdown + button inside the
  Collections rail section lets users add the current entry to any
  non-default collection without multi-selecting. After add, the
  membership list refreshes automatically.
- Collections section now shows even when entryCollections is empty,
  as long as non-default collections exist (so the add form is
  accessible for un-membered entries).
- Bulk 'Add to collection' now uses the target collection's
  default_visibility_bits instead of hardcoded 2 (Users only).
- Both bulk and single-entry dropdowns filter out slug='_default_'
  to match the backend rejection in add_entry_to_collection_handler.
- Collections list is now fetched on archiveId change (not just on
  bulk mode entry) so it is available for single-entry mode too.

* build(frontend): update static assets

* feat(frontend): public collection link UX + app-styled public page

CollectionsView:
- When a collection has requires_auth=false, show a read-only URL input
  and Copy button below the auth checkbox so the public link is
  immediately discoverable. The input auto-selects on focus so manual
  copy always works. Copy button tries navigator.clipboard.writeText
  first; falls back to execCommand('copy') for HTTP deployments where
  the Clipboard API is unavailable in non-secure contexts.

PublicCollectionPage:
- Rewritten to use the app's CSS classes and variables instead of
  bare inline styles, so it visually matches the main archive UI.
  Dark topbar (.pub-coll-topbar) with brand + collection name, paper
  background body, entry list via .coll-entries-list / .coll-entry-row /
  .coll-entry-info / .coll-entry-kind — the same classes used in the
  authenticated Collections view.

styles.css:
- .coll-public-link-row / -wrap / -input / .coll-copy-btn for the
  new link field in CollectionsView detail pane.
- .pub-coll-* classes for the public page layout and typography.

* feat(core): add get_collection_by_slug; scope search to active collection

- get_collection_by_slug(): new function mirroring get_collection_by_uid
  but matching on slug, used to resolve the _default_ collection when no
  ?collection param is supplied.
- SearchEntriesQuery gains collection_id: Option<i64>. When set, the
  search SQL adds an EXISTS subquery that checks collection_entries cef
  for both membership (cef.collection_id = ?) and visibility bits in
  that specific collection — preventing cross-collection visibility
  leaks where an entry is public in one collection but private in the
  current one. Without collection_id the original cross-collection
  visibility fallback is kept.

* feat(server): collection-scoped entries/search with uniform auth gate

All entry listing and search now route through the active collection:

list_entries (?collection=<uid>|main|<omitted>):
- Resolves the target collection; omitted or 'main' resolves to _default_.
- Checks requires_auth on that collection; gates auth conditionally.
- Returns list_entries_for_collection() — same EntrySummary shape.

search_entries_handler:
- Same collection resolution + conditional auth as list_entries.
- Sets search_query.collection_id so SQL scopes membership + visibility
  to the specific collection, not cross-collection fallback.

list_collections_handler:
- Dropped require_auth() — collection summaries (name/slug/uid/
  requires_auth/default_visibility_bits) are public metadata needed for
  the guest collection-switcher dropdown.

Tests:
- list_collections_requires_auth → list_collections_is_public (200).
- list_entries_requires_auth and search coverage still pass.

* feat(frontend): integrate collection switching into main Archive view

Replaces the standalone /c/:archiveId/:collUid public page with a
unified main-view approach where all collection logic lives at /.

URL param:
- ?collection=<uid> selects a collection; omitted or 'main' = default.
- 'main' is normalized to null in parseLocation() so the dropdown shows
  'All entries' and the URL stays clean.

Collection switcher (Topbar):
- Dropdown always visible (guests need it to navigate public collections).
- Non-default collections only (All entries = no param = _default_).
- Guest selecting an auth-required collection calls onSignInClick().
- handleCollectionChange checks both named and _default_ requires_auth
  before proceeding, redirecting guests to login if needed.

listCollections fetched for all users (guests too) since the endpoint
is now public; used to populate the switcher without auth.

Public-session mode (authenticated state, no currentUser):
- Auth gate: fetchArchives() + fetchEntries() with collection param;
  401 falls through to login, 200 proceeds as guest.
- auth:expired suppressed when !currentUser.
- fetchEntryDetail skipped; ContextRail shows entry summary + sign-in prompt.
- ContextRail selection effect skips tag/collection API calls.
- runs/tags not fetched in guest mode.
- Child row expansion disabled in EntryRow (hasChildren = false).

api.js:
- fetchEntries/searchEntries both thread ?collection=<uid> to server.

Deleted: PublicCollectionPage.jsx, PublicCollectionPage.stories.jsx,
copy-link UI from CollectionsView, pub-coll-*/copy-link CSS.

* build(frontend): update static assets

* feat(core): add is_entry_publicly_accessible; checks entry+parent vs public collections

* feat(server): allow guests to fetch detail/children/artifacts for public entries

* feat(frontend): guest collection dropdown filtering; public entry detail without auth wall

* build(frontend): update static assets

* test(server): public entry detail/artifact/children contract for guests

* feat(server): filter auth-required collections from guest list_collections response
2026-07-24 20:16:17 +02:00
1af920eb63
feat: share videos to TV (Chromecast + AirPlay) (#33)
* server: add scoped media-token endpoint for Cast/AirPlay auth bypass

Chromecast and Apple TV fetch media URLs as independent HTTP clients
with no session cookie. The existing serve_artifact handler requires
auth_user.require_auth(), so those devices always received 401.

Changes:
- MediaToken struct stored in AppState (Arc<Mutex<HashMap>>), scoped to
  a single (archive_id, entry_uid, artifact_index) tuple with a 2-hour TTL
- POST /api/archives/:id/entries/:uid/artifacts/:idx/media-token
  requires an authenticated session, verifies the artifact exists,
  prunes expired tokens, mints a 43-char URL-safe token, and returns
  { url, expires_in_secs }
- serve_artifact now accepts an optional ?token= query param; a valid
  scoped token bypasses require_auth() while a missing/invalid/expired
  token falls through to the normal 401 path
- CSP script-src extended to include https://www.gstatic.com so the
  Cast sender SDK script (injected lazily by VideoPreview) is not blocked
- 4 new tests: bare-URL still 401, tokenized fetch succeeds without
  session cookie, bogus token 401, wrong-artifact-index 401

* frontend: Cast/AirPlay overlay in VideoPreview

When the user opens a video archive entry, VideoPreview now:

1. Issues a signed media token (POST .../artifacts/:idx/media-token) and
   uses the returned signed URL as <video src>. This ensures the video
   element's src is one that Cast devices and Apple TV can fetch without a
   session cookie.

2. Lazily injects the Google Cast SDK script (cast_sender.js from
   gstatic.com, now allowed by the updated CSP). Once the SDK reports
   available, a <google-cast-launcher> web component appears as an overlay
   button in the top-right corner of the video. Selecting a Cast device
   triggers loadMedia() with the signed URL and the artifact's MIME type.

3. Detects AirPlay support (webkitShowPlaybackTargetPicker on
   HTMLVideoElement) and shows an AirPlay icon button alongside Cast.
   The <video> element carries x-webkit-airplay='allow', so Safari's native
   controls also surface the AirPlay option. The explicit overlay button
   calls webkitShowPlaybackTargetPicker() for consistent placement.

Both buttons are hidden when the respective APIs are unavailable (HTTP
pages, non-Safari for AirPlay, no Cast extension/devices), so there is no
UI regression for users who don't cast.

PreviewPanel now passes contentType (derived from artifact extension) to
VideoPreview so Cast receives a correct MIME type.

New CSS: .video-tv-controls (absolute overlay), .video-tv-btn (frosted
glass icon button), .video-tv-loading (placeholder during token fetch).

* server: fix serve_artifact auth OR logic — bogus token falls back to session

Previously a request carrying ?token=<expired> was immediately rejected
with 401, even if the user held a valid session cookie. This broke
logged-in browser playback after the 2-hour signed-URL window expired,
because VideoPreview uses the signed URL as <video src>.

Fix: compute token_valid first; if the token is absent or invalid, fall
through to auth_user.require_auth() instead of returning early.
Effect: valid token skips session check, invalid/missing token checks
session, both invalid → 401 as before.

Updated the bogus-token-no-session test docstring to clarify it tests
the no-auth path specifically. Added new test:
  media_token_bogus_token_with_session_returns_200 — verifies a logged-in
  user can still fetch the artifact via a URL carrying a stale token.

* frontend: guard token-fetch effect against stale async resolution

A slow issueMediaToken() response for video A could resolve after the
user selected video B and call setSignedSrc(urlA), making the
preview/Cast play the wrong file.

Add a cancelled flag set in the effect cleanup; both .then and .catch
check it before touching state, so only the most recent src wins.

* frontend: load Cast media immediately if session already exists

Previously the effect only sent video to the TV on SESSION_STARTED /
SESSION_RESUMED events. Two gaps:

1. If a Cast session was already active when signedSrc became ready
   (e.g. the SDK resumed a session before the token fetch finished, or
   the user switches videos while already casting), nothing was sent.

2. Same gap if castReady fired after an already-established session.

Fix: extract loadMedia(session) and call it against
ctx.getCurrentSession() immediately when castReady + signedSrc are both
truthy, in addition to keeping the event listener for future connects.

* server: staged file-upload endpoint

POST /api/archives/:id/uploads streams a multipart body to a temp file
under the archive's store/temp/ directory and returns a staged_path the
capture pipeline can move into place.

- Routes: /api/archives/:id/uploads (POST, requires auth)
- Body cap: 10 GiB; chunk-streamed to disk, never buffered in memory
- Path-traversal sanitised on the filename field
- Temp files are cleaned up on error paths (disk-leak fix)
- main.rs wires the new route into the server startup
- Cargo: adds the multipart dependency

* frontend: file upload in Capture dialog

Drag-and-drop or 'Upload file' button stages files for archiving:

- File items sit alongside URL rows in the same list; each shows the
  original filename, a live progress bar during upload, and a check badge
  when ready.  The locator input is replaced entirely — no editable field.
- Archive button is disabled until all uploads finish; each file item
  contributes to the Archive N count once its upload is done.
- File items are excluded from sessionStorage persistence (they are
  transient — the staged server path would be invalid after a reload).

Staged-file cleanup is handled at every exit path so temp/uploads/ does
not accumulate:
  • removeRow on an in-progress item aborts the XHR; removeRow on a done
    item calls DELETE /archives/:id/uploads.
  • Dialog cancel (Escape / Cancel button) aborts all in-flight XHRs and
    DELETEs all completed staged files via the close-event handler.
  • handleArchive sets isSubmittingRef=true before dialog.close() so the
    close handler skips cleanup — the background capture job handles
    staged-file removal on success instead.
  • uploadFile() returns { promise, abort } so the component can cancel
    the XHR without any visible fetch.

api.js additions: uploadFile (XHR with progress + abort), deleteUpload.

(Static assets rebuilt from combined source to include screensharing
changes from this branch.)

* fix: collection enrollment with default_visibility_bits

Two related fixes from feat-file-uploading:

core: fix collection enrollment using default_visibility_bits instead of
entry.visibility — entries were being enrolled with the entry-level
visibility rather than the collection's configured default.

server: allow changing default_visibility_bits on the default collection
— the PATCH handler was incorrectly blocking updates to the default
collection's visibility configuration.

* server: fix unbounded staged-upload disk growth

Two review findings:

P2 — delete staged file on capture failure (routes.rs)
When perform_capture returns Err, the job was marked failed but
staged_upload_path was never removed. With a 10 GiB body cap a few
failed imports could exhaust archive storage before the next restart.
Mirror the success-path cleanup into the Err arm so the file is removed
immediately regardless of outcome.

P1 — periodic staged-upload pruning (main.rs)
The startup prune of temp/uploads/ only ran once, so uploads abandoned
mid-session (browser crash, navigation away) accumulated forever on a
long-running server. Folded the pruning logic into the existing 24 h
maintenance task alongside session cleanup, so stale dirs are swept
continuously without requiring a restart.

* server+frontend: fix staged-upload disk-growth and prune safety

Server (main.rs + routes.rs):

- Extract prune_stale_upload_dirs() helper called by both startup and
  the periodic 24h task, eliminating the duplicated loop.

- Sentinel (.uploading) created in the UUID dir before streaming begins;
  removed on successful completion; error path uses remove_dir_all so
  the partial file and sentinel are cleaned up together.
  The periodic prune skips any dir containing .uploading (active XHR).

- Startup prune passes cleanup_stale_sentinels=true: the server has not
  started accepting connections yet so any sentinel is a crash remnant —
  it is removed and the dir proceeds to the age check, preventing leaked
  dirs from a previous crash accumulating forever.

- Staleness measured from the newest non-sentinel child file mtime so a
  just-finished slow upload (dir mtime stale, file mtime fresh) is not
  pruned before the user can submit it for capture. Empty dirs fall back
  to dir mtime.

- Failed captures (Err branch in spawn_blocking) now also delete the
  staged file and UUID dir immediately, matching the success path.

Frontend (api.js + CaptureDialog.jsx):

- submitCapture attaches err.status = res.status on non-2xx responses
  so callers can distinguish a definite HTTP rejection from a network
  error where the response may have been lost.

- submitBgJob catch deletes the staged file only when e.status is set
  (server definitively rejected the POST /captures request). A network
  error leaves the file in place because the server may have accepted
  the job and the response was lost — deleting would race the capture.
2026-07-23 20:12:22 +02:00