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

Compare commits

...

3 commits

26 changed files with 2255 additions and 144 deletions

View file

@ -133,9 +133,9 @@ No CI is configured; no rustfmt.toml/clippy.toml — default `cargo fmt`/`clippy
no restart; `resolve_js_runtime()` returns an owned `Option<JsRuntime>`. Never cache a resolved path across
operations. Never spawn bare yt-dlp — build every command with
`yt_dlp_command()` so the resolver-chosen binary *and* `--js-runtimes` args are applied.
- **LLM summaries by env var**: `ARCHIVR_ANTHROPIC_API_KEY` / `ARCHIVR_ANTHROPIC_URL` / `ARCHIVR_ANTHROPIC_MODEL`, `ARCHIVR_OPENAI_API_KEY` / `ARCHIVR_OPENAI_URL` / `ARCHIVR_OPENAI_MODEL`, `ARCHIVR_CLAUDE_CLI` / `ARCHIVR_CLAUDE_MODEL`, `ARCHIVR_CODEX_CLI` / `ARCHIVR_CODEX_MODEL`, plus `ARCHIVR_SUMMARY_HTTP_TIMEOUT` (default 120s) and `ARCHIVR_SUMMARY_CLI_TIMEOUT` (default 300s). Thread titles use `ARCHIVR_ANTHROPIC_TITLE_MODEL` (default `claude-haiku-4-5`), `ARCHIVR_OPENAI_TITLE_MODEL` (`gpt-4o-mini`), `ARCHIVR_CLAUDE_TITLE_MODEL` (`haiku`), `ARCHIVR_CODEX_TITLE_MODEL` (`gpt-6-luna`, override if unavailable) — never the summary model; `thread_title.rs` reuses provider transports via `summarizer::complete_plain`. The one exception to env-only config: admins may override the title model per provider in the auth DB (`instance_settings.title_model_{anthropic_http,openai_compatible,claude_cli,codex_cli}`; PATCH `/api/admin/instance-settings` trims, blank clears, rejects overlong or whitespace/control chars; GET returns `title_models.<kind>` with `model`/`source`/`fallback`). Precedence instance > `ARCHIVR_*_TITLE_MODEL` > default; the server passes the instance value to core as an `Option<&str>` override — core never reads the auth DB. Same convention as above — never TOML, which also keeps API keys out of anything the archive persists. Summaries are manual-only: nothing in `capture.rs` triggers them. The two CLI vars are optional overrides: unset, `resolve_cli()` auto-discovers well-known absolute installs first (`/opt/homebrew/bin/claude`, `/usr/local/bin/claude`; `/Applications/ChatGPT.app/Contents/Resources/codex`, `/opt/homebrew/bin/codex`, `/usr/local/bin/codex`), then `$HOME/.local/bin/<name>`, then the bare name on PATH — the absolute defaults matter because the ChatGPT desktop app ships `codex` off PATH. Frontend static output is generated; never hand-edit `crates/archivr-server/static/`.
- **LLM summaries by env var**: `ARCHIVR_ANTHROPIC_API_KEY` / `ARCHIVR_ANTHROPIC_URL` / `ARCHIVR_ANTHROPIC_MODEL`, `ARCHIVR_OPENAI_API_KEY` / `ARCHIVR_OPENAI_URL` / `ARCHIVR_OPENAI_MODEL`, `ARCHIVR_CLAUDE_CLI` / `ARCHIVR_CLAUDE_MODEL`, `ARCHIVR_CODEX_CLI` / `ARCHIVR_CODEX_MODEL`, plus `ARCHIVR_SUMMARY_HTTP_TIMEOUT` (default 120s) and `ARCHIVR_SUMMARY_CLI_TIMEOUT` (default 300s). Thread titles use `ARCHIVR_ANTHROPIC_TITLE_MODEL` (default `claude-haiku-4-5`), `ARCHIVR_OPENAI_TITLE_MODEL` (`gpt-4o-mini`), `ARCHIVR_CLAUDE_TITLE_MODEL` (`haiku`), `ARCHIVR_CODEX_TITLE_MODEL` (`gpt-6-luna`, override if unavailable) — never the summary model; `thread_title.rs` reuses provider transports via `summarizer::complete_plain`. The exceptions to env-only config: admins may override the title model per provider (`instance_settings.title_model_{anthropic_http,openai_compatible,claude_cli,codex_cli}`) and the OpenAI-compatible endpoint, API key, and model (`instance_settings.openai_{base_url,api_key,model}`; PATCH `/api/admin/instance-settings` trims, blank clears, rejects overlong or whitespace/control chars; GET returns `title_models.<kind>` and `openai_api_key_set` without exposing keys; `POST /api/admin/openai-models` lists remote models). Precedence instance > `ARCHIVR_*` env > default; the server passes instance values to core as overrides — core never reads the auth DB. Users may persist their preferred summary provider across devices via `users.summary_provider` (`PATCH /api/auth/me`). Same convention as above — never TOML, which also keeps API keys out of anything the archive persists. Summaries are manual-only: nothing in `capture.rs` triggers them. The two CLI vars are optional overrides: unset, `resolve_cli()` auto-discovers well-known absolute installs first (`/opt/homebrew/bin/claude`, `/usr/local/bin/claude`; `/Applications/ChatGPT.app/Contents/Resources/codex`, `/opt/homebrew/bin/codex`, `/usr/local/bin/codex`), then `$HOME/.local/bin/<name>`, then the bare name on PATH — the absolute defaults matter because the ChatGPT desktop app ships `codex` off PATH. Frontend static output is generated; never hand-edit `crates/archivr-server/static/`.
- **Frontend**: JSX (no TypeScript), PascalCase components in `frontend/src/components/`, kebab-case CSS classes, plain CSS with custom properties in `styles.css` (no Tailwind/CSS-in-JS). No router — `App.jsx` parses `window.location.pathname` + `history.pushState`. State = `useState` + one `AuthContext`; `sessionStorage` for refresh-resilient dialog state (see `CaptureDialog.jsx` job polling, 500ms). All API calls through `frontend/src/api.js` with relative `/api/*` URLs — add new endpoints there, not inline `fetch`. Summary polling and generate callbacks must remain scoped to the currently selected entry; image-inclusion behavior is unchanged. In-progress captures render through `SkeletonEntryRow.jsx`, which is a compact spinner + locator + "Archiving…" line (with a playlist/channel hint), **not** a grey skeleton block — don't reintroduce placeholder shimmer. Layout comes from semantic classes (e.g. `.capture-text-row` in `styles.css`), never from fallthrough on a generic row class; give a new row shape its own class.
- **CLI providers parse a file, not stdout**: `codex` is invoked as `codex exec --output-last-message <tempfile> -` (prompt on stdin) and the reply is read back from that file — raw stdout carries a runtime header, an echo of the user prompt, and a `tokens used` footer that the JSON extractor will happily mistake for the answer. There is a positional-prompt fallback for older builds that reject `-`. Keep any new CLI provider on the same "give me only the final message" contract.
- **CLI providers parse a file, not stdout**: `codex` is invoked as `codex exec --skip-git-repo-check --sandbox read-only --output-last-message <tempfile> -` (prompt on stdin) and the reply is read back from that file — raw stdout carries a runtime header, an echo of the user prompt, and a `tokens used` footer that the JSON extractor will happily mistake for the answer. `--skip-git-repo-check` permits execution outside a trusted git repository and `--sandbox read-only` enforces safety. There is a positional-prompt fallback for older builds that reject `-`. Keep any new CLI provider on the same "give me only the final message" contract.
- **Transcription engines follow the same rule**: whisper.cpp writes `-ovtt`; script engines (Whisper `script`, Parakeet) are run as `<script> --input <wav> --output <vtt> --model <m> [--language xx]` and must write WebVTT to `--output` (optional `<output>.lang`); the only stdout parsed is Phonon-2's documented `--json`, converted to VTT by `phonon_json_to_vtt`. Phonon-2 is English-only, hard-coded. One job at a time (process-wide slot).
- **Log prefixes**: `info:`/`warn:` only. The one exception is the yt-dlp installer's `warning: python3 was not found on PATH …` (`ytdlp_tools.rs`), kept verbatim for byte-identical CLI stderr.
- **Naming (Rust)**: standard snake_case/PascalCase; visibility and roles are bitflag `u32`s, not enums.

View file

@ -249,7 +249,7 @@ CLI-only installs never backfill. Rearchive still does not change titles.
`tweet_thread` entries calls `POST .../entries/:entry_uid/thread-title` (user role, the same gate as rename). It reuses
the selected provider's transport (`summarizer::complete_plain`) with a cheap title model — admin instance setting
`instance_settings.title_model_<kind>`, else `ARCHIVR_*_TITLE_MODEL`, else a per-provider default, never the summary
model; the server passes the instance value to core as an `Option<&str>` override (core never reads the auth DB) — and
model; OpenAI-compatible endpoints can also be configured via instance settings (`instance_settings.openai_{base_url,api_key,model}`); the server passes instance values to core as overrides (core never reads the auth DB) — and
never touches `entry_summaries`. The model returns only the topic; the server sanitizes it and owns the
`Thread about <topic> — @author` format, saved via `update_entry_title`. The bulk panel's **Generate titles** (≥2
selected, ≥1 thread) loops the same endpoint client-side over the selected threads, 2 at a time, with the rail's

View file

@ -187,6 +187,13 @@ pub struct InstanceSettings {
pub title_model_openai_compatible: Option<String>,
pub title_model_claude_cli: Option<String>,
pub title_model_codex_cli: Option<String>,
/// Optional base URL for an OpenAI-compatible endpoint (e.g. `http://localhost:8318/v1`).
pub openai_base_url: Option<String>,
/// Optional API key for the OpenAI-compatible endpoint. Never serialized in API responses.
#[serde(skip_serializing)]
pub openai_api_key: Option<String>,
/// Optional default model for the OpenAI-compatible endpoint.
pub openai_model: Option<String>,
}
impl InstanceSettings {
@ -222,6 +229,29 @@ impl InstanceSettings {
_ => None,
}
}
/// Returns instance-level overrides for the OpenAI-compatible provider, if any are set.
pub fn openai_compatible_overrides(&self) -> crate::summarizer::OpenAiCompatibleOverrides {
crate::summarizer::OpenAiCompatibleOverrides {
base_url: self
.openai_base_url
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(String::from),
api_key: self
.openai_api_key
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(String::from),
model: self
.openai_model
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(String::from),
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@ -719,7 +749,10 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> {
title_model_anthropic_http TEXT,
title_model_openai_compatible TEXT,
title_model_claude_cli TEXT,
title_model_codex_cli TEXT
title_model_codex_cli TEXT,
openai_base_url TEXT,
openai_api_key TEXT,
openai_model TEXT
);
INSERT OR IGNORE INTO instance_settings
@ -737,7 +770,8 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> {
status TEXT NOT NULL CHECK (status IN ('active', 'disabled')),
role TEXT NOT NULL CHECK (role IN ('admin', 'user')),
created_at TEXT NOT NULL,
last_login_at TEXT
last_login_at TEXT,
summary_provider TEXT
);
CREATE TABLE IF NOT EXISTS cookie_rules (
@ -769,6 +803,9 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> {
"ALTER TABLE users ADD COLUMN humanize_slugs INTEGER NOT NULL DEFAULT 0",
[],
);
// Add summary_provider column to users if not present (idempotent migration)
let _ = conn.execute("ALTER TABLE users ADD COLUMN summary_provider TEXT", []);
// Add scope column to api_tokens if not present ('full' | 'read'; idempotent migration)
let _ = conn.execute(
@ -808,6 +845,18 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> {
[],
);
}
// Add OpenAI-compatible configuration to instance_settings if not present (idempotent migration)
for column in [
"openai_base_url",
"openai_api_key",
"openai_model",
] {
let _ = conn.execute(
&format!("ALTER TABLE instance_settings ADD COLUMN {column} TEXT"),
[],
);
}
// Backfill allocations for custom roles created before role_bit_allocations existed.
// Roles deleted before this migration left no record here, so their bits cannot be
@ -1068,7 +1117,8 @@ pub fn get_instance_settings(conn: &Connection) -> Result<InstanceSettings> {
COALESCE(modal_closer_enabled, 1),
COALESCE(reorder_children_role_bits, 12),
title_model_anthropic_http, title_model_openai_compatible,
title_model_claude_cli, title_model_codex_cli
title_model_claude_cli, title_model_codex_cli,
openai_base_url, openai_api_key, openai_model
FROM instance_settings WHERE id = 1",
[],
|row| {
@ -1085,6 +1135,9 @@ pub fn get_instance_settings(conn: &Connection) -> Result<InstanceSettings> {
title_model_openai_compatible: row.get(9)?,
title_model_claude_cli: row.get(10)?,
title_model_codex_cli: row.get(11)?,
openai_base_url: row.get(12)?,
openai_api_key: row.get(13)?,
openai_model: row.get(14)?,
})
},
)
@ -1105,7 +1158,10 @@ pub fn update_instance_settings(conn: &Connection, settings: &InstanceSettings)
title_model_anthropic_http = ?9,
title_model_openai_compatible = ?10,
title_model_claude_cli = ?11,
title_model_codex_cli = ?12
title_model_codex_cli = ?12,
openai_base_url = ?13,
openai_api_key = ?14,
openai_model = ?15
WHERE id = 1",
params![
settings.public_index_enabled as i64,
@ -1120,6 +1176,9 @@ pub fn update_instance_settings(conn: &Connection, settings: &InstanceSettings)
settings.title_model_openai_compatible,
settings.title_model_claude_cli,
settings.title_model_codex_cli,
settings.openai_base_url,
settings.openai_api_key,
settings.openai_model,
],
)?;
Ok(())
@ -1239,6 +1298,27 @@ pub fn update_user_humanize_slugs(conn: &Connection, user_id: i64, value: bool)
Ok(())
}
pub fn update_user_summary_provider(
conn: &Connection,
user_id: i64,
provider: Option<&str>,
) -> Result<()> {
conn.execute(
"UPDATE users SET summary_provider = ?1 WHERE id = ?2",
params![provider, user_id],
)?;
Ok(())
}
pub fn get_user_summary_provider(conn: &Connection, user_id: i64) -> Result<Option<String>> {
conn.query_row(
"SELECT summary_provider FROM users WHERE id = ?1",
[user_id],
|row| row.get(0),
)
.map_err(Into::into)
}
/// Updates the user-visible title of an archived entry.
/// Returns `Ok(true)` if a row was updated, `Ok(false)` if the entry_uid was not found.
pub fn update_entry_title(conn: &Connection, entry_uid: &str, title: Option<&str>) -> Result<bool> {
@ -4718,6 +4798,54 @@ mod tests {
assert_eq!(s.title_model_anthropic_http, None);
}
#[test]
fn instance_settings_openai_compatible_migrates_and_round_trips() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE instance_settings (id INTEGER PRIMARY KEY CHECK (id = 1), public_index_enabled INTEGER NOT NULL DEFAULT 0, public_entry_content_enabled INTEGER NOT NULL DEFAULT 0, public_archive_submission_enabled INTEGER NOT NULL DEFAULT 0, default_entry_visibility INTEGER NOT NULL DEFAULT 2);
INSERT INTO instance_settings (id) VALUES (1);",
)
.unwrap();
initialize_auth_schema(&conn).unwrap();
initialize_auth_schema(&conn).unwrap();
let mut s = get_instance_settings(&conn).unwrap();
assert_eq!(s.openai_base_url, None);
assert_eq!(s.openai_api_key, None);
assert_eq!(s.openai_model, None);
s.openai_base_url = Some("http://localhost:8318/v1".into());
s.openai_api_key = Some("test-key".into());
s.openai_model = Some("llama3.2".into());
update_instance_settings(&conn, &s).unwrap();
let s2 = get_instance_settings(&conn).unwrap();
assert_eq!(s2.openai_base_url.as_deref(), Some("http://localhost:8318/v1"));
assert_eq!(s2.openai_api_key.as_deref(), Some("test-key"));
assert_eq!(s2.openai_model.as_deref(), Some("llama3.2"));
let overrides = s2.openai_compatible_overrides();
assert_eq!(overrides.base_url.as_deref(), Some("http://localhost:8318/v1"));
assert_eq!(overrides.api_key.as_deref(), Some("test-key"));
assert_eq!(overrides.model.as_deref(), Some("llama3.2"));
}
#[test]
fn user_summary_provider_migrates_and_round_trips() {
let conn = make_auth_conn_for_mgmt();
let uid = create_user(&conn, "providertester", None, "hash", 1).unwrap();
let user_id = get_user_id_by_uid(&conn, &uid).unwrap().unwrap();
assert_eq!(get_user_summary_provider(&conn, user_id).unwrap(), None);
update_user_summary_provider(&conn, user_id, Some("openai_compatible")).unwrap();
assert_eq!(
get_user_summary_provider(&conn, user_id).unwrap().as_deref(),
Some("openai_compatible")
);
update_user_summary_provider(&conn, user_id, None).unwrap();
assert_eq!(get_user_summary_provider(&conn, user_id).unwrap(), None);
}
#[test]
fn can_reorder_children_intersects_mask() {
let conn = make_auth_conn_for_mgmt();

View file

@ -203,6 +203,31 @@ pub struct CliProviderConfig {
pub timeout_secs: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OpenAiCompatibleOverrides {
pub base_url: Option<String>,
pub api_key: Option<String>,
pub model: Option<String>,
}
pub fn normalize_openai_chat_url(base_or_chat: &str) -> String {
let trimmed = base_or_chat.trim().trim_end_matches('/');
if trimmed.ends_with("/chat/completions") {
trimmed.to_string()
} else {
format!("{trimmed}/chat/completions")
}
}
pub fn normalize_openai_models_url(base_or_chat: &str) -> String {
let trimmed = base_or_chat.trim().trim_end_matches('/');
if let Some(stripped) = trimmed.strip_suffix("/chat/completions") {
format!("{}/models", stripped.trim_end_matches('/'))
} else {
format!("{trimmed}/models")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderConfig {
AnthropicHttp(HttpProviderConfig),
@ -237,6 +262,14 @@ pub(crate) fn summary_cli_timeout() -> std::time::Duration {
/// Builds a provider configuration for `kind` purely from the environment.
pub fn provider_from_env(kind: &str) -> Result<ProviderConfig> {
provider_from_env_with_openai_overrides(kind, None)
}
/// Builds a provider configuration with optional instance-level overrides for OpenAI-compatible.
pub fn provider_from_env_with_openai_overrides(
kind: &str,
overrides: Option<&OpenAiCompatibleOverrides>,
) -> Result<ProviderConfig> {
match kind {
"anthropic_http" => Ok(ProviderConfig::AnthropicHttp(HttpProviderConfig {
endpoint: env_or(
@ -247,15 +280,50 @@ pub fn provider_from_env(kind: &str) -> Result<ProviderConfig> {
model: env_or("ARCHIVR_ANTHROPIC_MODEL", "claude-3-5-sonnet-latest"),
timeout_secs: env_timeout("ARCHIVR_SUMMARY_HTTP_TIMEOUT", DEFAULT_HTTP_TIMEOUT_SECS),
})),
"openai_compatible" => Ok(ProviderConfig::OpenAiCompatible(HttpProviderConfig {
endpoint: env_or(
"ARCHIVR_OPENAI_URL",
"https://api.openai.com/v1/chat/completions",
),
api_key: required_env("ARCHIVR_OPENAI_API_KEY")?,
model: env_or("ARCHIVR_OPENAI_MODEL", "gpt-4o-mini"),
timeout_secs: env_timeout("ARCHIVR_SUMMARY_HTTP_TIMEOUT", DEFAULT_HTTP_TIMEOUT_SECS),
})),
"openai_compatible" => {
let instance_base = overrides
.and_then(|o| o.base_url.as_deref())
.map(str::trim)
.filter(|s| !s.is_empty());
let instance_key = overrides
.and_then(|o| o.api_key.as_deref())
.map(str::trim)
.filter(|s| !s.is_empty());
let instance_model = overrides
.and_then(|o| o.model.as_deref())
.map(str::trim)
.filter(|s| !s.is_empty());
let endpoint = if let Some(base) = instance_base {
normalize_openai_chat_url(base)
} else {
env_or(
"ARCHIVR_OPENAI_URL",
"https://api.openai.com/v1/chat/completions",
)
};
let api_key = if let Some(key) = instance_key {
key.to_string()
} else if instance_base.is_some() {
optional_env("ARCHIVR_OPENAI_API_KEY").unwrap_or_default()
} else {
required_env("ARCHIVR_OPENAI_API_KEY")?
};
let model = if let Some(m) = instance_model {
m.to_string()
} else {
env_or("ARCHIVR_OPENAI_MODEL", "gpt-4o-mini")
};
Ok(ProviderConfig::OpenAiCompatible(HttpProviderConfig {
endpoint,
api_key,
model,
timeout_secs: env_timeout("ARCHIVR_SUMMARY_HTTP_TIMEOUT", DEFAULT_HTTP_TIMEOUT_SECS),
}))
}
"claude_cli" => Ok(ProviderConfig::ClaudeCli(CliProviderConfig {
executable: resolve_cli(
"ARCHIVR_CLAUDE_CLI",
@ -480,10 +548,13 @@ impl SummaryProvider for OpenAiCompatibleProvider {
}
fn send_openai(cfg: &HttpProviderConfig, body: &serde_json::Value) -> Result<SummaryOutput> {
let resp = http_client(cfg.timeout_secs)?
let mut req = http_client(cfg.timeout_secs)?
.post(&cfg.endpoint)
.header("authorization", format!("Bearer {}", cfg.api_key))
.header("content-type", "application/json")
.header("content-type", "application/json");
if !cfg.api_key.trim().is_empty() {
req = req.header("authorization", format!("Bearer {}", cfg.api_key));
}
let resp = req
.body(body.to_string())
.send()
.with_context(|| format!("request to {} failed", cfg.endpoint))?;
@ -510,6 +581,62 @@ pub fn parse_openai_response(body: &str) -> Result<SummaryOutput> {
})
}
pub fn parse_openai_models_response(body: &str) -> Result<Vec<String>> {
let json: serde_json::Value =
serde_json::from_str(body).context("openai-compatible models response was not JSON")?;
let mut models = Vec::new();
if let Some(arr) = json["data"].as_array() {
for item in arr {
if let Some(id) = item["id"].as_str() {
models.push(id.to_string());
}
}
} else if let Some(arr) = json["models"].as_array() {
for item in arr {
if let Some(id) = item["id"].as_str().or_else(|| item["name"].as_str()) {
models.push(id.to_string());
} else if let Some(s) = item.as_str() {
models.push(s.to_string());
}
}
} else if let Some(arr) = json.as_array() {
for item in arr {
if let Some(id) = item["id"].as_str() {
models.push(id.to_string());
} else if let Some(s) = item.as_str() {
models.push(s.to_string());
}
}
}
models.sort();
models.dedup();
Ok(models)
}
pub fn list_openai_compatible_models(
base_url: &str,
api_key: Option<&str>,
timeout_secs: u64,
) -> Result<Vec<String>> {
let url = normalize_openai_models_url(base_url);
let mut req = http_client(timeout_secs)?.get(&url);
if let Some(key) = api_key.map(str::trim).filter(|k| !k.is_empty()) {
req = req.header("authorization", format!("Bearer {key}"));
}
let resp = req
.send()
.with_context(|| format!("request to {url} failed"))?;
let status = resp.status();
let text = resp.text().unwrap_or_default();
if !status.is_success() {
bail!(
"openai-compatible models endpoint returned {status}: {}",
truncate_for_error(&text)
);
}
parse_openai_models_response(&text)
}
fn truncate_for_error(s: &str) -> String {
let trimmed = s.trim();
if trimmed.chars().count() <= 400 {
@ -580,13 +707,17 @@ impl SummaryProvider for ClaudeCliProvider {
/// Codex invocation lives in its own module because its one-shot interface is
/// the least stable of the four.
///
/// Primary form is `codex exec --output-last-message <file> -`, which reads the
/// prompt from stdin and writes ONLY the final assistant message to `<file>`.
/// Primary form is `codex exec --skip-git-repo-check --sandbox read-only
/// --output-last-message <file> -`, which reads the prompt from stdin and
/// writes ONLY the final assistant message to `<file>`.
/// Without `--output-last-message`, stdout is polluted with a header
/// (`OpenAI Codex vX`, session id, model, sandbox, …) and a footer
/// (`tokens used`, message replay), and the JSON extractor can pick up the
/// echoed user prompt instead of the real answer. Older builds that reject
/// `-` as stdin marker fall back to a positional prompt.
/// echoed user prompt instead of the real answer. `--skip-git-repo-check` is
/// required because the server's working directory is rarely a trusted git
/// repo (codex refuses to start otherwise); `--sandbox read-only` keeps a
/// prompt-injected archived page from writing anywhere. Older builds that
/// reject `-` as stdin marker fall back to a positional prompt.
mod codex {
use super::*;
@ -604,12 +735,18 @@ mod codex {
))
}
fn missing_binary_hint(cfg: &CliProviderConfig) -> &'static str {
// Only nudge users about the env var when we're running the default
// bare "codex" and it failed — an explicit ARCHIVR_CODEX_CLI path
// failure is their configuration, not a discovery gap.
if cfg.executable == Path::new("codex") {
" (hint: set ARCHIVR_CODEX_CLI to your codex binary; on macOS the ChatGPT desktop app installs it at /Applications/ChatGPT.app/Contents/Resources/codex)"
pub(crate) fn missing_binary_hint(cfg: &CliProviderConfig, err: &anyhow::Error) -> &'static str {
// Only nudge users about the env var when the default bare "codex"
// could not be spawned at all. A codex that ran and exited non-zero is
// not a discovery gap, and an explicit ARCHIVR_CODEX_CLI path failure
// is their configuration.
let not_found = err.chain().any(|cause| {
cause
.downcast_ref::<std::io::Error>()
.is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
});
if not_found && cfg.executable == Path::new("codex") {
" (hint: set ARCHIVR_CODEX_CLI to your codex binary; on macOS the ChatGPT desktop app installs it at /Applications/ChatGPT.app/Contents/Resources/codex)"
} else {
""
}
@ -631,7 +768,12 @@ mod codex {
out_path: &Path,
model: Option<&str>,
) -> Vec<String> {
let mut args = vec!["exec".into()];
let mut args: Vec<String> = vec![
"exec".into(),
"--skip-git-repo-check".into(),
"--sandbox".into(),
"read-only".into(),
];
for image in images {
args.push("--image".into());
args.push(image.archive_file.to_string_lossy().into_owned());
@ -684,13 +826,16 @@ mod codex {
// Fallback: positional prompt, no stdin, same --output-last-message.
let fb = positional_args(images, &out_path, cfg.model.as_deref(), prompt);
let fb_refs: Vec<&str> = fb.iter().map(String::as_str).collect();
let out = run_cli(&cfg.executable, &fb_refs, "", cfg.timeout_secs).with_context(|| {
let _ = std::fs::remove_file(&out_path);
format!(
"codex `exec -` failed ({primary_err:#}); positional fallback failed{}",
missing_binary_hint(cfg)
)
})?;
let out = match run_cli(&cfg.executable, &fb_refs, "", cfg.timeout_secs) {
Ok(out) => out,
Err(e) => {
let _ = std::fs::remove_file(&out_path);
let hint = missing_binary_hint(cfg, &e);
return Err(e.context(format!(
"codex `exec -` failed ({primary_err:#}); positional fallback failed{hint}"
)));
}
};
if let Some(text) = read_and_cleanup(&out_path) {
return Ok(text);
}
@ -1523,6 +1668,87 @@ mod tests {
clear_provider_env();
}
#[test]
fn normalize_openai_urls_works_for_various_formats() {
assert_eq!(
normalize_openai_chat_url("http://localhost:8318/v1"),
"http://localhost:8318/v1/chat/completions"
);
assert_eq!(
normalize_openai_chat_url("http://localhost:8318/v1/"),
"http://localhost:8318/v1/chat/completions"
);
assert_eq!(
normalize_openai_chat_url("http://localhost:8318/v1/chat/completions"),
"http://localhost:8318/v1/chat/completions"
);
assert_eq!(
normalize_openai_models_url("http://localhost:8318/v1"),
"http://localhost:8318/v1/models"
);
assert_eq!(
normalize_openai_models_url("http://localhost:8318/v1/chat/completions"),
"http://localhost:8318/v1/models"
);
assert_eq!(
normalize_openai_models_url("http://localhost:8318/v1/"),
"http://localhost:8318/v1/models"
);
}
#[test]
fn provider_with_openai_overrides_honours_instance_settings() {
let _g = ENV_LOCK.lock().unwrap();
clear_provider_env();
let overrides = OpenAiCompatibleOverrides {
base_url: Some("http://localhost:8318/v1".into()),
api_key: Some("custom-key".into()),
model: Some("qwen2.5:3b".into()),
};
let ProviderConfig::OpenAiCompatible(c) =
provider_from_env_with_openai_overrides("openai_compatible", Some(&overrides)).unwrap()
else {
panic!("wrong variant");
};
assert_eq!(c.endpoint, "http://localhost:8318/v1/chat/completions");
assert_eq!(c.api_key, "custom-key");
assert_eq!(c.model, "qwen2.5:3b");
}
#[test]
fn provider_with_openai_overrides_allows_no_key_for_custom_base() {
let _g = ENV_LOCK.lock().unwrap();
clear_provider_env();
let overrides = OpenAiCompatibleOverrides {
base_url: Some("http://localhost:8318/v1".into()),
api_key: None,
model: None,
};
let ProviderConfig::OpenAiCompatible(c) =
provider_from_env_with_openai_overrides("openai_compatible", Some(&overrides)).unwrap()
else {
panic!("wrong variant");
};
assert_eq!(c.endpoint, "http://localhost:8318/v1/chat/completions");
assert_eq!(c.api_key, "");
assert_eq!(c.model, "gpt-4o-mini");
}
#[test]
fn parse_openai_models_response_extracts_and_sorts_ids() {
let json = r#"{
"object": "list",
"data": [
{"id": "qwen2.5:3b", "object": "model"},
{"id": "llama3.2:1b", "object": "model"},
{"id": "deepseek-r1:8b", "object": "model"}
]
}"#;
let models = parse_openai_models_response(json).unwrap();
assert_eq!(models, vec!["deepseek-r1:8b", "llama3.2:1b", "qwen2.5:3b"]);
}
#[test]
fn provider_from_env_clis_default_to_bare_binary_names() {
let _g = ENV_LOCK.lock().unwrap();
@ -1672,6 +1898,11 @@ mod tests {
request.images[0].archive_file.to_string_lossy()
);
assert_eq!(args.last().unwrap(), "-");
// Without these codex refuses to run outside a trusted git repo, which
// is where the server usually lives.
assert!(args.iter().any(|a| a == "--skip-git-repo-check"));
let sandbox_at = args.iter().position(|a| a == "--sandbox").unwrap();
assert_eq!(args[sandbox_at + 1], "read-only");
}
#[test]
@ -1690,6 +1921,9 @@ mod tests {
request.images[0].archive_file.to_string_lossy()
);
assert_eq!(args.last().unwrap(), "prompt");
assert!(args.iter().any(|a| a == "--skip-git-repo-check"));
let sandbox_at = args.iter().position(|a| a == "--sandbox").unwrap();
assert_eq!(args[sandbox_at + 1], "read-only");
}
#[cfg(unix)]
@ -1718,6 +1952,30 @@ mod tests {
assert!(err.contains("timed out after 1s"), "got: {err}");
}
#[test]
fn codex_missing_binary_hint_only_fires_on_not_found_with_bare_command() {
let bare_cfg = CliProviderConfig {
executable: PathBuf::from("codex"),
model: None,
timeout_secs: 10,
};
let explicit_cfg = CliProviderConfig {
executable: PathBuf::from("/usr/bin/codex"),
model: None,
timeout_secs: 10,
};
let not_found_err = anyhow::Error::new(std::io::Error::new(
std::io::ErrorKind::NotFound,
"No such file",
));
let exit_err = anyhow::anyhow!("codex exited with 1: Not inside a trusted directory");
assert!(codex::missing_binary_hint(&bare_cfg, &not_found_err).contains("ARCHIVR_CODEX_CLI"));
assert_eq!(codex::missing_binary_hint(&bare_cfg, &exit_err), "");
assert_eq!(codex::missing_binary_hint(&explicit_cfg, &not_found_err), "");
}
#[test]
fn claude_rejects_images_before_spawning() {
let (_temp, request) = image_request();

View file

@ -106,11 +106,30 @@ impl TitleModelSource {
pub fn resolve_title_model(
kind: &str,
instance_override: Option<&str>,
) -> Option<(String, TitleModelSource)> {
resolve_title_model_with_openai_overrides(kind, instance_override, None)
}
/// Effective title model for `kind`: non-empty trimmed `instance_override` >
/// OpenAI endpoint model (for `openai_compatible`) > non-empty title env var > built-in default.
pub fn resolve_title_model_with_openai_overrides(
kind: &str,
instance_override: Option<&str>,
openai_overrides: Option<&summarizer::OpenAiCompatibleOverrides>,
) -> Option<(String, TitleModelSource)> {
let (var, default) = (title_model_env(kind)?, default_title_model(kind)?);
if let Some(m) = instance_override.map(str::trim).filter(|m| !m.is_empty()) {
return Some((m.to_string(), TitleModelSource::Instance));
}
if kind == "openai_compatible" {
if let Some(m) = openai_overrides
.and_then(|o| o.model.as_deref())
.map(str::trim)
.filter(|m| !m.is_empty())
{
return Some((m.to_string(), TitleModelSource::Instance));
}
}
if let Some(m) = optional_env(var).map(|m| m.trim().to_string()).filter(|m| !m.is_empty()) {
return Some((m, TitleModelSource::Env));
}
@ -122,10 +141,20 @@ pub fn resolve_title_model(
pub fn title_provider_from_env(
kind: &str,
instance_override: Option<&str>,
) -> Result<ProviderConfig> {
title_provider_from_env_with_openai_overrides(kind, instance_override, None)
}
/// Provider config for title generation with optional instance OpenAI overrides:
/// transport settings from env / overrides, model from [`resolve_title_model_with_openai_overrides`].
pub fn title_provider_from_env_with_openai_overrides(
kind: &str,
instance_override: Option<&str>,
openai_overrides: Option<&summarizer::OpenAiCompatibleOverrides>,
) -> Result<ProviderConfig> {
// Validates `kind` and keeps the summary path's missing-key messages.
let cfg = summarizer::provider_from_env(kind)?;
let Some((model, _)) = resolve_title_model(kind, instance_override) else {
let cfg = summarizer::provider_from_env_with_openai_overrides(kind, openai_overrides)?;
let Some((model, _)) = resolve_title_model_with_openai_overrides(kind, instance_override, openai_overrides) else {
bail!("unknown summary provider: {kind}");
};
Ok(with_title_model(cfg, model))
@ -443,6 +472,35 @@ mod tests {
}
}
#[test]
fn resolve_title_model_inherits_openai_endpoint_model() {
let overrides = summarizer::OpenAiCompatibleOverrides {
base_url: Some("http://localhost:8318/v1".into()),
api_key: None,
model: Some("qwen2.5:3b".into()),
};
// Without explicit title override, inherits endpoint model
let (model, source) = resolve_title_model_with_openai_overrides(
"openai_compatible",
None,
Some(&overrides),
)
.unwrap();
assert_eq!(model, "qwen2.5:3b");
assert_eq!(source, TitleModelSource::Instance);
// Explicit title override wins over endpoint model
let (model2, source2) = resolve_title_model_with_openai_overrides(
"openai_compatible",
Some("gpt-4o-mini"),
Some(&overrides),
)
.unwrap();
assert_eq!(model2, "gpt-4o-mini");
assert_eq!(source2, TitleModelSource::Instance);
}
/// Archive with one entry of `entity_kind` and the given raw tweet JSON files.
fn fixture(
entity_kind: &str,

View file

@ -169,10 +169,11 @@ fn env_var_json(spec: &EnvSpec) -> Value {
// ── Derived state ───────────────────────────────────────────────────────────
fn summary_providers_json() -> Vec<Value> {
fn summary_providers_json(settings: &database::InstanceSettings) -> Vec<Value> {
let openai_overrides = settings.openai_compatible_overrides();
summarizer::PROVIDER_KINDS
.iter()
.map(|kind| match summarizer::provider_from_env(kind) {
.map(|kind| match summarizer::provider_from_env_with_openai_overrides(kind, Some(&openai_overrides)) {
Ok(summarizer::ProviderConfig::AnthropicHttp(c))
| Ok(summarizer::ProviderConfig::OpenAiCompatible(c)) => json!({
"kind": kind, "configured": true, "model": c.model,
@ -196,7 +197,13 @@ fn summary_providers_json() -> Vec<Value> {
Err(error) => {
let key_var = match *kind {
"anthropic_http" => Some("ARCHIVR_ANTHROPIC_API_KEY"),
"openai_compatible" => Some("ARCHIVR_OPENAI_API_KEY"),
"openai_compatible" => {
if openai_overrides.base_url.is_some() {
None
} else {
Some("ARCHIVR_OPENAI_API_KEY")
}
}
_ => None,
};
let missing: Vec<&str> = key_var.filter(|v| env_value(v).is_none()).into_iter().collect();
@ -296,7 +303,7 @@ async fn effective_config_handler(
"archives": archives,
},
"env_vars": ENV_VARS.iter().map(env_var_json).collect::<Vec<_>>(),
"summary_providers": summary_providers_json(),
"summary_providers": summary_providers_json(&settings),
"title_models": title_models_json(&settings),
"transcription_engines": transcription_engines_json(),
"extensions": {

View file

@ -95,6 +95,9 @@ async fn setup_guard(State(state): State<AppState>, req: Request, next: Next) ->
let exempt = path.starts_with("/api/auth/")
|| path.starts_with("/assets")
|| path == "/"
|| path == "/theme-init.js"
|| path == "/favicon.ico"
|| path == "/favicon.svg"
|| path == "/health";
if !exempt {
if let Ok(conn) = database::open_auth_db(&state.auth_db_path) {
@ -396,6 +399,7 @@ pub fn app_with_state(state: AppState) -> Router {
)
.route("/api/admin/yt-dlp", get(get_yt_dlp_status_handler))
.route("/api/admin/yt-dlp/update", post(update_yt_dlp_handler))
.route("/api/admin/openai-models", post(fetch_openai_models_handler))
.route(
"/api/admin/cookie-rules",
get(list_cookie_rules_handler).post(create_cookie_rule_handler),
@ -601,7 +605,8 @@ async fn entry_detail(
#[derive(Debug, serde::Deserialize)]
struct SummaryRequestBody {
provider: String,
#[serde(default)]
provider: Option<String>,
#[serde(default)]
force: bool,
#[serde(default)]
@ -673,6 +678,7 @@ async fn request_entry_summary_handler(
Path((archive_id, entry_uid)): Path<(String, String)>,
Json(body): Json<SummaryRequestBody>,
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
let (caller_id, _) = auth_user.require_auth()?;
auth_user.require_role(ROLE_USER)?;
let mounted = mounted_archive(&state, &archive_id)?;
// A hidden entry is not found: it must not be summarized, nor probe provider config.
@ -684,9 +690,19 @@ async fn request_entry_summary_handler(
let archive_paths =
archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?;
// 1. Provider config from the environment. The error text carries the exact
let auth_conn = database::open_auth_db(&state.auth_db_path)?;
let settings = database::get_instance_settings(&auth_conn)?;
let openai_overrides = settings.openai_compatible_overrides();
let provider_kind = match body.provider.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
Some(p) => p.to_string(),
None => database::get_user_summary_provider(&auth_conn, caller_id)?
.unwrap_or_else(|| "anthropic_http".to_string()),
};
// 1. Provider config from the environment / instance overrides. The error text carries the exact
// variable name, which is the whole point of returning it as a 400.
let provider_cfg = summarizer::provider_from_env(&body.provider)
let provider_cfg = summarizer::provider_from_env_with_openai_overrides(&provider_kind, Some(&openai_overrides))
.map_err(|e| ApiError::bad_request(&format!("{e:#}")))?;
if body.include_images && matches!(provider_cfg, summarizer::ProviderConfig::ClaudeCli(_)) {
return Err(ApiError::bad_request(
@ -1452,7 +1468,8 @@ async fn capture_options_handler(
#[derive(Debug, serde::Deserialize)]
struct TextTitleBody {
body: String,
provider: String,
#[serde(default)]
provider: Option<String>,
}
async fn generate_text_title_handler(
@ -1461,6 +1478,7 @@ async fn generate_text_title_handler(
Path(archive_id): Path<String>,
Json(body): Json<TextTitleBody>,
) -> Result<Json<serde_json::Value>, ApiError> {
let (caller_id, _) = auth_user.require_auth()?;
auth_user.require_role(ROLE_USER)?;
if body.body.trim().is_empty() {
return Err(ApiError::bad_request("body must not be empty"));
@ -1469,10 +1487,18 @@ async fn generate_text_title_handler(
return Err(ApiError::bad_request("body must not exceed 2 MiB"));
}
mounted_archive(&state, &archive_id)?;
let settings = database::get_instance_settings(&database::open_auth_db(&state.auth_db_path)?)?;
let cfg = thread_title::title_provider_from_env(
&body.provider,
settings.title_model_override(&body.provider),
let auth_conn = database::open_auth_db(&state.auth_db_path)?;
let settings = database::get_instance_settings(&auth_conn)?;
let openai_overrides = settings.openai_compatible_overrides();
let provider_kind = match body.provider.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
Some(p) => p.to_string(),
None => database::get_user_summary_provider(&auth_conn, caller_id)?
.unwrap_or_else(|| "anthropic_http".to_string()),
};
let cfg = thread_title::title_provider_from_env_with_openai_overrides(
&provider_kind,
settings.title_model_override(&provider_kind),
Some(&openai_overrides),
)
.map_err(|error| ApiError::bad_request(&format!("{error:#}")))?;
let title = tokio::task::spawn_blocking(move || {
@ -1491,7 +1517,8 @@ async fn generate_text_title_handler(
#[derive(Debug, serde::Deserialize)]
struct ThreadTitleBody {
provider: String,
#[serde(default)]
provider: Option<String>,
}
/// `POST /api/archives/:id/entries/:uid/thread-title` — names an X thread with a
@ -1503,6 +1530,7 @@ async fn generate_thread_title_handler(
Path((archive_id, entry_uid)): Path<(String, String)>,
Json(body): Json<ThreadTitleBody>,
) -> Result<Json<serde_json::Value>, ApiError> {
let (caller_id, _) = auth_user.require_auth()?;
auth_user.require_role(ROLE_USER)?;
let mounted = mounted_archive(&state, &archive_id)?;
ensure_entry_visible(
@ -1511,10 +1539,18 @@ async fn generate_thread_title_handler(
&entry_uid,
)?;
let paths = archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?;
let settings = database::get_instance_settings(&database::open_auth_db(&state.auth_db_path)?)?;
let cfg = thread_title::title_provider_from_env(
&body.provider,
settings.title_model_override(&body.provider),
let auth_conn = database::open_auth_db(&state.auth_db_path)?;
let settings = database::get_instance_settings(&auth_conn)?;
let openai_overrides = settings.openai_compatible_overrides();
let provider_kind = match body.provider.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
Some(p) => p.to_string(),
None => database::get_user_summary_provider(&auth_conn, caller_id)?
.unwrap_or_else(|| "anthropic_http".to_string()),
};
let cfg = thread_title::title_provider_from_env_with_openai_overrides(
&provider_kind,
settings.title_model_override(&provider_kind),
Some(&openai_overrides),
)
.map_err(|e| ApiError::bad_request(&format!("{e:#}")))?;
let uid = entry_uid.clone();
@ -2522,11 +2558,16 @@ async fn auth_me(
) -> Result<Json<serde_json::Value>, ApiError> {
let (user_id, role_bits) = auth_user.require_auth()?;
let conn = database::open_auth_db(&state.auth_db_path)?;
let (username, display_name, humanize_slugs_int): (String, Option<String>, i64) = conn
let (username, display_name, humanize_slugs_int, summary_provider): (
String,
Option<String>,
i64,
Option<String>,
) = conn
.query_row(
"SELECT username, display_name, COALESCE(humanize_slugs, 0) FROM users WHERE id = ?1",
"SELECT username, display_name, COALESCE(humanize_slugs, 0), summary_provider FROM users WHERE id = ?1",
[user_id],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)
.map_err(|e| ApiError::from(anyhow::anyhow!("db error: {e}")))?;
let humanize_slugs = humanize_slugs_int != 0;
@ -2540,6 +2581,7 @@ async fn auth_me(
"username": username,
"display_name": display_name,
"humanize_slugs": humanize_slugs,
"summary_provider": summary_provider,
"can_reorder_children": settings.can_reorder_children(role_bits),
})))
}
@ -2591,6 +2633,21 @@ async fn patch_me(
database::update_user_humanize_slugs(&conn, user_id, hs)?;
}
if let Some(sp) = &body.summary_provider {
let trimmed = sp.trim();
if trimmed.is_empty() {
database::update_user_summary_provider(&conn, user_id, None)?;
} else {
if !summarizer::PROVIDER_KINDS.contains(&trimmed) {
return Err(ApiError::bad_request(&format!(
"unknown summary provider: {trimmed} (expected one of {})",
summarizer::PROVIDER_KINDS.join(", ")
)));
}
database::update_user_summary_provider(&conn, user_id, Some(trimmed))?;
}
}
Ok(StatusCode::NO_CONTENT)
}
@ -2621,13 +2678,24 @@ async fn get_instance_settings_handler(
"cookie_ext_available".into(),
serde_json::Value::Bool(cookie_ext_available),
);
obj.insert(
"openai_api_key_set".into(),
serde_json::Value::Bool(
settings
.openai_api_key
.as_deref()
.map(str::trim)
.is_some_and(|k| !k.is_empty()),
),
);
let title_models: serde_json::Map<String, serde_json::Value> = summarizer::PROVIDER_KINDS
.iter()
.filter_map(|kind| {
let instance = settings.title_model_override(kind);
let (model, source) = thread_title::resolve_title_model(kind, instance)?;
let openai_overrides = settings.openai_compatible_overrides();
let (model, source) = thread_title::resolve_title_model_with_openai_overrides(kind, instance, Some(&openai_overrides))?;
// Fallback = what applies if the instance value is cleared (placeholder).
let (fallback, fallback_source) = thread_title::resolve_title_model(kind, None)?;
let (fallback, fallback_source) = thread_title::resolve_title_model_with_openai_overrides(kind, None, Some(&openai_overrides))?;
Some((
kind.to_string(),
serde_json::json!({
@ -2711,11 +2779,103 @@ async fn update_instance_settings_handler(
}
}
}
if let Some(raw) = body.openai_base_url {
let trimmed = raw.trim();
if trimmed.is_empty() {
settings.openai_base_url = None;
} else {
if !trimmed.starts_with("http://") && !trimmed.starts_with("https://") {
return Err(ApiError::bad_request(
"openai_base_url must start with http:// or https://",
));
}
if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) {
return Err(ApiError::bad_request(
"openai_base_url must not contain whitespace or control characters",
));
}
settings.openai_base_url = Some(trimmed.to_string());
}
}
if let Some(raw) = body.openai_api_key {
let trimmed = raw.trim();
if trimmed.is_empty() {
settings.openai_api_key = None;
} else {
settings.openai_api_key = Some(trimmed.to_string());
}
}
if let Some(raw) = body.openai_model {
let trimmed = raw.trim();
settings.openai_model = if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
};
}
database::update_instance_settings(&tx, &settings)?;
tx.commit()?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Debug, serde::Deserialize)]
struct FetchOpenAiModelsBody {
#[serde(default)]
base_url: Option<String>,
#[serde(default)]
api_key: Option<String>,
}
async fn fetch_openai_models_handler(
State(state): State<AppState>,
auth_user: AuthUser,
Json(body): Json<FetchOpenAiModelsBody>,
) -> Result<Json<serde_json::Value>, ApiError> {
auth_user.require_role(ROLE_ADMIN)?;
let conn = database::open_auth_db(&state.auth_db_path)?;
let settings = database::get_instance_settings(&conn)?;
let base_url = body
.base_url
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.or(settings.openai_base_url.as_deref().map(str::trim).filter(|s| !s.is_empty()))
.map(String::from)
.or_else(|| std::env::var("ARCHIVR_OPENAI_URL").ok().filter(|s| !s.trim().is_empty()))
.unwrap_or_else(|| "https://api.openai.com/v1".to_string());
if !base_url.starts_with("http://") && !base_url.starts_with("https://") {
return Err(ApiError::bad_request("base_url must start with http:// or https://"));
}
if base_url.chars().any(|c| c.is_whitespace() || c.is_control()) {
return Err(ApiError::bad_request("base_url must not contain whitespace or control characters"));
}
let api_key = body
.api_key
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.or(settings.openai_api_key.as_deref().map(str::trim).filter(|s| !s.is_empty()))
.map(String::from)
.or_else(|| std::env::var("ARCHIVR_OPENAI_API_KEY").ok().filter(|s| !s.trim().is_empty()));
let timeout_secs = std::env::var("ARCHIVR_SUMMARY_HTTP_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120);
let models = tokio::task::spawn_blocking(move || {
summarizer::list_openai_compatible_models(&base_url, api_key.as_deref(), timeout_secs)
})
.await
.map_err(|e| ApiError::internal(&format!("task failed: {e}")))?
.map_err(|e| ApiError::bad_request(&format!("failed to fetch models: {e:#}")))?;
Ok(Json(serde_json::json!({ "models": models })))
}
const MAX_TITLE_MODEL_CHARS: usize = 100;
/// Trims an admin-supplied title model; empty clears it (`None`). Rejects
@ -3219,6 +3379,7 @@ struct UpdateProfileBody {
current_password: Option<String>,
new_password: Option<String>,
humanize_slugs: Option<bool>,
summary_provider: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
@ -3235,6 +3396,9 @@ struct UpdateInstanceSettingsBody {
title_model_openai_compatible: Option<String>,
title_model_claude_cli: Option<String>,
title_model_codex_cli: Option<String>,
openai_base_url: Option<String>,
openai_api_key: Option<String>,
openai_model: Option<String>,
}
async fn admin_list_users(
@ -4847,6 +5011,51 @@ mod tests {
assert!(database::latest_entry_summary(&conn, entry.id).unwrap().is_none());
}
#[tokio::test]
async fn summary_request_uses_saved_provider_when_omitted() {
let dir = tempfile::tempdir().unwrap();
let (registry, archive_path, auth_path) = make_test_registry(&dir);
let entry = make_test_entry(&archive_path);
let session_cookie = make_test_session(&auth_path);
// Save claude_cli as user's preferred summary provider
let patch_resp = app(registry.clone(), auth_path.clone())
.oneshot(
Request::builder()
.method("PATCH")
.uri("/api/auth/me")
.header("content-type", "application/json")
.header("cookie", &session_cookie)
.body(Body::from(r#"{"summary_provider":"claude_cli"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(patch_resp.status(), StatusCode::NO_CONTENT);
// Post summary with omitted provider but include_images: true
let response = app(registry, auth_path)
.oneshot(
Request::builder()
.method("POST")
.uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid))
.header("content-type", "application/json")
.header("cookie", &session_cookie)
.body(json_body(&serde_json::json!({
"include_images": true,
})))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(
body_json(response).await["error"],
"Claude CLI cannot attach local images; choose an HTTP provider or Codex CLI"
);
}
#[tokio::test]
async fn summary_preflight_returns_safe_message_for_unsupported_video_content() {
let dir = tempfile::tempdir().unwrap();
@ -6253,6 +6462,21 @@ mod tests {
assert_eq!(json["setup_required"], true);
}
#[tokio::test]
async fn theme_init_exempt_from_setup_guard() {
let (test_app, _dir) = make_setup_test_app();
let response = test_app
.oneshot(
Request::builder()
.uri("/theme-init.js")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_ne!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn setup_post_returns_409_on_repeat() {
let dir = tempfile::tempdir().unwrap();
@ -9242,6 +9466,180 @@ mod tests {
);
}
#[tokio::test]
async fn auth_me_returns_summary_provider_null_by_default() {
let dir = tempfile::tempdir().unwrap();
let (registry, _, auth_path) = make_test_registry(&dir);
let session = make_test_session(&auth_path);
let me = me_json(registry, auth_path, &session).await;
assert!(me["summary_provider"].is_null());
}
#[tokio::test]
async fn patch_me_summary_provider_persists_and_validates() {
let dir = tempfile::tempdir().unwrap();
let (registry, _, auth_path) = make_test_registry(&dir);
let session = make_test_session(&auth_path);
// Rejects unknown provider
let bad_resp = app(registry.clone(), auth_path.clone())
.oneshot(
Request::builder()
.method("PATCH")
.uri("/api/auth/me")
.header("content-type", "application/json")
.header("cookie", &session)
.body(Body::from(r#"{"summary_provider":"invalid_provider"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(bad_resp.status(), StatusCode::BAD_REQUEST);
// Accepts valid provider
let patch_resp = app(registry.clone(), auth_path.clone())
.oneshot(
Request::builder()
.method("PATCH")
.uri("/api/auth/me")
.header("content-type", "application/json")
.header("cookie", &session)
.body(Body::from(r#"{"summary_provider":"openai_compatible"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(patch_resp.status(), StatusCode::NO_CONTENT);
let me = me_json(registry.clone(), auth_path.clone(), &session).await;
assert_eq!(me["summary_provider"], "openai_compatible");
// Clears provider on blank
let clear_resp = app(registry.clone(), auth_path.clone())
.oneshot(
Request::builder()
.method("PATCH")
.uri("/api/auth/me")
.header("content-type", "application/json")
.header("cookie", &session)
.body(Body::from(r#"{"summary_provider":""}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(clear_resp.status(), StatusCode::NO_CONTENT);
let me2 = me_json(registry, auth_path, &session).await;
assert!(me2["summary_provider"].is_null());
}
#[tokio::test]
async fn instance_settings_openai_compatible_round_trips_and_validates() {
let dir = tempfile::tempdir().unwrap();
let (registry, _, auth_path) = make_test_registry(&dir);
let owner = make_test_session(&auth_path);
// Initial state: api_key_set false, never returns key
let json = get_settings_json(registry.clone(), auth_path.clone(), &owner).await;
assert_eq!(json["openai_api_key_set"], false);
assert!(json.get("openai_api_key").is_none());
assert!(json["openai_base_url"].is_null());
assert!(json["openai_model"].is_null());
// Rejects bad URL (not http/https)
let bad_resp = app(registry.clone(), auth_path.clone())
.oneshot(patch_settings_request(
serde_json::json!({ "openai_base_url": "ftp://example.com" }),
&owner,
))
.await
.unwrap();
assert_eq!(bad_resp.status(), StatusCode::BAD_REQUEST);
// Rejects whitespace in URL
let bad_resp2 = app(registry.clone(), auth_path.clone())
.oneshot(patch_settings_request(
serde_json::json!({ "openai_base_url": "http://localhost:8318 /v1" }),
&owner,
))
.await
.unwrap();
assert_eq!(bad_resp2.status(), StatusCode::BAD_REQUEST);
// Sets valid base_url, key, and model
let patch_resp = app(registry.clone(), auth_path.clone())
.oneshot(patch_settings_request(
serde_json::json!({
"openai_base_url": "http://localhost:8318/v1",
"openai_api_key": "secret-token-123",
"openai_model": "qwen2.5:3b"
}),
&owner,
))
.await
.unwrap();
assert_eq!(patch_resp.status(), StatusCode::NO_CONTENT);
// GET verifies: base_url set, model set, key set is true, key itself is NOT returned
let json2 = get_settings_json(registry.clone(), auth_path.clone(), &owner).await;
assert_eq!(json2["openai_base_url"], "http://localhost:8318/v1");
assert_eq!(json2["openai_model"], "qwen2.5:3b");
assert_eq!(json2["openai_api_key_set"], true);
assert!(json2.get("openai_api_key").is_none());
// Blank key clears the stored key
let clear_key_resp = app(registry.clone(), auth_path.clone())
.oneshot(patch_settings_request(
serde_json::json!({ "openai_api_key": "" }),
&owner,
))
.await
.unwrap();
assert_eq!(clear_key_resp.status(), StatusCode::NO_CONTENT);
let json3 = get_settings_json(registry, auth_path, &owner).await;
assert_eq!(json3["openai_api_key_set"], false);
assert_eq!(json3["openai_base_url"], "http://localhost:8318/v1");
}
#[tokio::test]
async fn fetch_openai_models_enforces_admin_and_validates_url() {
let dir = tempfile::tempdir().unwrap();
let (registry, _, auth_path) = make_test_registry(&dir);
let owner = make_test_session(&auth_path);
let user = make_role_session(&auth_path, "regularuser", &["user"]);
// Non-admin is forbidden
let forbidden_resp = app(registry.clone(), auth_path.clone())
.oneshot(
Request::builder()
.method("POST")
.uri("/api/admin/openai-models")
.header("content-type", "application/json")
.header("cookie", &user)
.body(Body::from(r#"{"base_url":"http://localhost:8318/v1"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(forbidden_resp.status(), StatusCode::FORBIDDEN);
// Admin with invalid scheme gets 400
let bad_resp = app(registry.clone(), auth_path.clone())
.oneshot(
Request::builder()
.method("POST")
.uri("/api/admin/openai-models")
.header("content-type", "application/json")
.header("cookie", &owner)
.body(Body::from(r#"{"base_url":"ftp://localhost:8318"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(bad_resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn delete_entry_returns_204_and_entry_is_gone() {
let dir = tempfile::tempdir().unwrap();

View file

@ -6,8 +6,9 @@
<title>Archivr</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="icon" type="image/x-icon" href="/favicon.ico">
<script type="module" crossorigin src="/assets/index-CSEU9J6M.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-D-bTRI4I.css">
<script src="/theme-init.js"></script>
<script type="module" crossorigin src="/assets/index-C6nWFmj8.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-wmXsSAqS.css">
</head>
<body>
<div id="root"></div>

View file

@ -56,6 +56,8 @@ Contributing? See the [contributor guide](../CONTRIBUTING.md) and its ecosystem
- **LLM summaries** — regenerable per-entry summary via the Anthropic HTTP API, an OpenAI-compatible HTTP API, a local `claude` CLI, or a local `codex` CLI; triggered manually from the entry rail, never automatically on capture; text-only by default, with an explicit `Include attached images` option; YouTube videos are summarized from their subtitles
- **Text notes** — capture a plain-text or Markdown note with a title and no URL; the byte-preserving note is stored as a normal deduplicated blob and opens in the usual entry-rail preview
- **In-progress capture indicator** — running captures appear as a compact spinner row in the entries list until they finish, replacing the earlier grey skeleton block
- **Dark mode** — toggle light/dark from the topbar or auth screen, or configure System/Light/Dark under **Settings › Profile**
- **Cookie rules** — global, wildcard, or regex rules under **Settings › Cookies** inject custom cookies into capture network requests (yt-dlp, HTTP downloads, web snapshots). The input accepts native JSON, browser extension exports (Cookie-Editor, EditThisCookie), Netscape `cookies.txt`, or `Cookie:` header strings with automatic formatting and collision-safe merge on paste
## Quick Start
@ -393,11 +395,13 @@ replacement succeeds, and public readers receive completed content only—never
| `ARCHIVR_CODEX_MODEL` | *(the CLI's own default)* | Optional model override for the local Codex CLI |
| `ARCHIVR_SUMMARY_HTTP_TIMEOUT` | `120` | Seconds before an HTTP-provider summary is killed |
| `ARCHIVR_SUMMARY_CLI_TIMEOUT` | `300` | Seconds before a CLI-provider summary is killed; also bounds each summary-time yt-dlp subtitle fetch call |
OpenAI-compatible endpoints can also be configured directly in the web UI under **Settings › Instance › OpenAI-compatible endpoint** (Base URL, optional API key, and model, with a **Fetch models** helper). Instance settings take precedence over the `ARCHIVR_OPENAI_*` environment variables.
Users can also choose and save their preferred summary provider across sessions and devices in **Settings › Profile › Preferred summary provider** or directly via the Summary section in the sidebar.
Thread-title generation uses the same provider but never its summary model (`ARCHIVR_*_MODEL`); it uses a cheap title
model instead. Admins can set a per-provider title model in **Settings › Instance › Thread title models**. Precedence:
that instance setting (blank = unset) > the env var below > the built-in default.
| Variable | Default | Description |
|---|---|---|
| `ARCHIVR_ANTHROPIC_TITLE_MODEL` | `claude-haiku-4-5` | Model used only for thread-title generation |

View file

@ -6,6 +6,7 @@
<title>Archivr</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="icon" type="image/x-icon" href="/favicon.ico">
<script src="/theme-init.js"></script>
</head>
<body>
<div id="root"></div>

View file

@ -0,0 +1,9 @@
(function () {
try {
var stored = localStorage.getItem('archivr-theme');
var isDark = stored === 'dark' || (stored !== 'light' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.dataset.theme = isDark ? 'dark' : 'light';
} catch (e) {
/* ignore storage access error */
}
})();

View file

@ -207,7 +207,7 @@ export default function App() {
poll()
const timer = setInterval(poll, 3000)
return () => { clearInterval(timer); setForeignCaptures([]) }
}, [archiveId, currentUser])
}, [archiveId, !currentUser])
const [ublockWarningIgnored, setUblockWarningIgnored] = useState(
() => sessionStorage.getItem('ublockWarningIgnored') === 'true'
@ -317,7 +317,7 @@ export default function App() {
tasks.push(fetchTags(archiveId).then(setTagNodes))
}
Promise.all(tasks)
}, [archiveId, currentUser]) // currentUser distinguishes guest vs authenticated
}, [archiveId, !currentUser]) // distinguishes guest vs authenticated without firing on preference changes
// Debounced search — scoped to active collection
useEffect(() => {

View file

@ -484,6 +484,22 @@ export async function updateInstanceSettings(patch) {
if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b.error || `HTTP ${res.status}`); }
}
export async function fetchOpenAiModels(options = {}) {
const res = await fetch('/api/admin/openai-models', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
base_url: options.baseUrl || undefined,
api_key: options.apiKey || undefined,
}),
});
if (!res.ok) {
const b = await res.json().catch(() => ({}));
throw new Error(b.error || `HTTP ${res.status}`);
}
return res.json();
}
export async function getYtDlpStatus({ signal } = {}) {
return getJson('/api/admin/yt-dlp', { signal });
}

View file

@ -1,5 +1,6 @@
import { useState, useEffect, useLayoutEffect, useRef } from 'react'
import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, saveEntrySummary, fetchTranscriptionEngines } from '../api'
import { useState, useEffect, useLayoutEffect, useRef, useContext } from 'react'
import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, saveEntrySummary, fetchTranscriptionEngines, patchMe } from '../api'
import { AuthContext } from '../App.jsx'
import ExportDialog from './ExportDialog'
import { formatTimestamp, formatBytes, valueText, sourceIconSvg, displayPath } from '../utils'
@ -66,6 +67,7 @@ function orderedSelection(rows, selectedUids) {
}
export default function ContextRail({ archiveId, selectedEntry, selectedUids, selectedEntries, detail, onTagFilterSet, tagNodes, onTagsRefresh, onEntryTitleChange, onEntryDeleted, onBulkDeleted, humanizeTags, onDetailRefresh, onOpenPreview, onPlay, isPublicSession }) {
const { currentUser, setCurrentUser } = useContext(AuthContext) ?? {}
const [tags, setTags] = useState([])
const [exportOpen, setExportOpen] = useState(false)
const [assignInput, setAssignInput] = useState('')
@ -91,10 +93,18 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
const [summaryError, setSummaryError] = useState('')
const [summaryBusy, setSummaryBusy] = useState(false)
const [summaryProvider, setSummaryProvider] = useState(() => {
if (currentUser?.summary_provider) return currentUser.summary_provider
try {
return sessionStorage.getItem(SUMMARY_PROVIDER_KEY) || SUMMARY_PROVIDERS[0].value
} catch { return SUMMARY_PROVIDERS[0].value }
})
useEffect(() => {
if (currentUser?.summary_provider) {
setSummaryProvider(currentUser.summary_provider)
try { sessionStorage.setItem(SUMMARY_PROVIDER_KEY, currentUser.summary_provider) } catch {}
}
}, [currentUser?.summary_provider])
const [includeSummaryImages, setIncludeSummaryImages] = useState(false)
// Local transcription engines offered by the server ([] = feature off) and
// the one picked for YouTube videos without subtitles ('' = none).
@ -361,6 +371,13 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
setSummaryProvider(value)
if (value === 'claude_cli') setIncludeSummaryImages(false)
try { sessionStorage.setItem(SUMMARY_PROVIDER_KEY, value) } catch { /* private mode */ }
if (currentUser && currentUser.summary_provider !== value) {
patchMe({ summary_provider: value })
.then(() => {
setCurrentUser?.(prev => prev ? { ...prev, summary_provider: value } : prev)
})
.catch(() => {})
}
}
function handleTranscribeEngineChange(value) {

View file

@ -1,5 +1,6 @@
import { useState } from 'react';
import { login } from '../api.js';
import ThemeToggle from './ThemeToggle.jsx';
export default function LoginPage({ onLogin }) {
const [username, setUsername] = useState('');
@ -23,6 +24,7 @@ export default function LoginPage({ onLogin }) {
return (
<div className="login-page">
<ThemeToggle className="auth-page-theme-toggle" />
<div className="login-card">
<h1 className="login-brand">Archivr</h1>
<p className="login-tagline">Sign in to your archive</p>

View file

@ -8,9 +8,11 @@ import {
scanOrphanBlobs, deleteOrphanBlobs,
listCookieRules, createCookieRule, updateCookieRule, deleteCookieRule,
listRoles, fetchMe,
getYtDlpStatus, updateYtDlp,
getYtDlpStatus, updateYtDlp, fetchOpenAiModels,
} from '../api.js'
import { describeExpiry, formatTimestamp } from '../utils.js'
import { useTheme } from '../useTheme.js'
import { normalizeCookiesInput, pasteCookies } from '../cookieImport.js'
const ROLE_ADMIN = 4
const ROLE_OWNER = 8
@ -54,6 +56,7 @@ export default function SettingsView({ tab, onTabChange, archiveId }) {
function ProfileTab({ currentUser, setCurrentUser }) {
const [displayName, setDisplayName] = useState(currentUser?.display_name ?? '')
const { preference, resolved, setPreference } = useTheme()
const [saving, setSaving] = useState(false)
const [saveMsg, setSaveMsg] = useState(null)
@ -133,6 +136,48 @@ function ProfileTab({ currentUser, setCurrentUser }) {
<p className="muted" style={{ fontSize: 13, margin: '4px 0 0' }}>
When on, tag paths show as "X / Articles" instead of "x/articles".
</p>
<div className="form-field" style={{ marginTop: 16 }}>
<label className="form-label" htmlFor="summary-provider-select">Preferred summary provider</label>
<select
id="summary-provider-select"
className="field-input"
value={currentUser?.summary_provider ?? ''}
onChange={async e => {
const val = e.target.value;
try {
await patchMe({ summary_provider: val });
setCurrentUser(prev => ({ ...prev, summary_provider: val || null }));
} catch {
// silently revert
}
}}
>
<option value="">Default (Anthropic API)</option>
<option value="anthropic_http">Anthropic API</option>
<option value="openai_compatible">OpenAI-compatible API</option>
<option value="claude_cli">Claude CLI</option>
<option value="codex_cli">Codex CLI</option>
</select>
<p className="muted" style={{ fontSize: 13, margin: '4px 0 0' }}>
Default provider used for summaries and thread title generation across all your devices.
</p>
</div>
<div className="form-field" style={{ marginTop: 16 }}>
<label className="form-label" htmlFor="theme-select">Theme</label>
<select
id="theme-select"
className="field-input"
value={preference}
onChange={e => setPreference(e.target.value)}
>
<option value="system">System ({resolved})</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<p className="muted" style={{ fontSize: 13, margin: '4px 0 0' }}>
Choose light, dark, or follow your operating system settings.
</p>
</div>
</div>
<div className="form-section">
@ -379,6 +424,36 @@ function InstanceTab({ isOwner, setCurrentUser }) {
const [permSaving, setPermSaving] = useState(false)
const [permMsg, setPermMsg] = useState(null)
const [fetchingModels, setFetchingModels] = useState(false)
const [modelFetchMsg, setModelFetchMsg] = useState(null)
const [fetchedModels, setFetchedModels] = useState([])
const [apiKeyInput, setApiKeyInput] = useState('')
const [clearingKey, setClearingKey] = useState(false)
async function handleFetchModels() {
setFetchingModels(true)
setModelFetchMsg(null)
try {
const res = await fetchOpenAiModels({
baseUrl: settings.openai_base_url,
apiKey: apiKeyInput || undefined,
})
const list = res.models || []
setFetchedModels(list)
if (list.length > 0) {
setModelFetchMsg({ ok: true, text: `Fetched ${list.length} model${list.length === 1 ? '' : 's'}.` })
if (!settings.openai_model) {
setSettings(s => ({ ...s, openai_model: list[0] }))
}
} else {
setModelFetchMsg({ ok: true, text: 'No models returned from endpoint.' })
}
} catch (e) {
setModelFetchMsg({ ok: false, text: e.message || 'Failed to fetch models' })
} finally {
setFetchingModels(false)
}
}
useEffect(() => {
(async () => {
try {
@ -416,8 +491,23 @@ function InstanceTab({ isOwner, setCurrentUser }) {
e.preventDefault()
setSaving(true); setSaveMsg(null)
try {
const { reorder_children_role_bits: _mask, title_models: _models, ...rest } = settings
await updateInstanceSettings(rest)
const {
reorder_children_role_bits: _mask,
title_models: _models,
openai_api_key_set: _ks,
ublock_ext_available: _ub,
cookie_ext_available: _ck,
...rest
} = settings
const payload = { ...rest }
if (apiKeyInput.trim()) {
payload.openai_api_key = apiKeyInput.trim()
} else if (clearingKey) {
payload.openai_api_key = ''
}
await updateInstanceSettings(payload)
setApiKeyInput('')
setClearingKey(false)
setSettings(await getInstanceSettings()) // server-trimmed models + effective sources
setSaveMsg({ ok: true, text: 'Saved.' })
} catch (err) {
@ -461,11 +551,16 @@ function InstanceTab({ isOwner, setCurrentUser }) {
{TITLE_MODEL_PROVIDERS.map(([kind, label]) => {
const key = `title_model_${kind}`
const info = settings.title_models?.[kind]
const placeholder = info ? `${info.fallback_model} (${info.fallback_source})` : ''
const isOai = kind === 'openai_compatible'
const sourceLabel = info?.fallback_source === 'instance' && isOai
? 'endpoint model'
: info?.fallback_source
const placeholder = info ? `${info.fallback_model} (${sourceLabel})` : ''
return (
<div key={kind} className="form-field">
<label className="form-label" htmlFor={key}>{label}</label>
<input id={key} className="field-input" type="text" maxLength={100}
list={isOai ? 'openai-models-datalist' : undefined}
value={settings[key] ?? ''} placeholder={placeholder}
onChange={e => setSettings(s => ({ ...s, [key]: e.target.value }))} />
</div>
@ -473,6 +568,99 @@ function InstanceTab({ isOwner, setCurrentUser }) {
})}
<p className="form-hint">Cheap model used for Generate title. Leave blank to use the default.</p>
</div>
<div className="form-field" style={{ marginTop: 16 }}>
<label className="form-label">OpenAI-compatible endpoint</label>
<div className="form-field">
<label className="form-label" htmlFor="openai-base-url" style={{ fontSize: 12 }}>Base URL</label>
<input
id="openai-base-url"
className="field-input"
type="text"
placeholder="http://localhost:8318/v1 or https://api.openai.com/v1"
value={settings.openai_base_url ?? ''}
onChange={e => setSettings(s => ({ ...s, openai_base_url: e.target.value }))}
/>
<p className="form-hint">Endpoint for OpenAI-compatible LLMs (e.g. Handy STT post-processing, Ollama, LocalAI).</p>
</div>
<div className="form-field">
<label className="form-label" htmlFor="openai-api-key" style={{ fontSize: 12 }}>API Key</label>
<input
id="openai-api-key"
className="field-input"
type="password"
autoComplete="off"
placeholder={
clearingKey
? 'Will be cleared on save'
: settings.openai_api_key_set
? '•••••••• (saved — enter new key to replace)'
: 'Optional (leave blank if server requires no auth)'
}
value={apiKeyInput}
onChange={e => {
setApiKeyInput(e.target.value)
if (clearingKey) setClearingKey(false)
}}
/>
{settings.openai_api_key_set && !clearingKey && !apiKeyInput && (
<button
type="button"
style={{ background: 'none', border: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 12, marginTop: 4, padding: 0, textDecoration: 'underline' }}
onClick={() => setClearingKey(true)}
>
Clear saved API key
</button>
)}
{clearingKey && (
<span className="muted" style={{ fontSize: 12, marginTop: 4, display: 'inline-block' }}>
Key will be removed on save.{' '}
<button
type="button"
style={{ background: 'none', border: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 12, padding: 0, textDecoration: 'underline' }}
onClick={() => setClearingKey(false)}
>
Cancel
</button>
</span>
)}
</div>
<div className="form-field">
<label className="form-label" htmlFor="openai-model" style={{ fontSize: 12 }}>Model</label>
<div style={{ display: 'flex', gap: 8 }}>
<input
id="openai-model"
className="field-input"
type="text"
list="openai-models-datalist"
placeholder="e.g. gpt-4o-mini, llama3, or local model"
value={settings.openai_model ?? ''}
onChange={e => setSettings(s => ({ ...s, openai_model: e.target.value }))}
style={{ flex: 1 }}
/>
<button
type="button"
className="btn-ghost"
onClick={handleFetchModels}
disabled={fetchingModels}
style={{ whiteSpace: 'nowrap' }}
>
{fetchingModels ? 'Fetching\u2026' : 'Fetch models'}
</button>
</div>
<datalist id="openai-models-datalist">
{fetchedModels.map(m => (
<option key={m} value={m} />
))}
</datalist>
{modelFetchMsg && (
<div className={`form-msg form-msg--${modelFetchMsg.ok ? 'ok' : 'err'}`} style={{ marginTop: 6 }}>
{modelFetchMsg.text}
</div>
)}
</div>
</div>
{saveMsg && <div className={`form-msg form-msg--${saveMsg.ok ? 'ok' : 'err'}`}>{saveMsg.text}</div>}
<button className="btn-primary" type="submit" disabled={saving}>
{saving ? 'Saving\u2026' : 'Save Settings'}
@ -665,9 +853,9 @@ function CookiesTab() {
async function handleAdd(e) {
e.preventDefault()
// Validate JSON
try { JSON.parse(cookiesInput) } catch {
setAddMsg({ ok: false, text: 'cookies must be valid JSON, e.g. {"session": "abc"}' })
const normalized = normalizeCookiesInput(cookiesInput)
if (!normalized.ok) {
setAddMsg({ ok: false, text: normalized.error })
return
}
setAdding(true); setAddMsg(null)
@ -675,7 +863,7 @@ function CookiesTab() {
await createCookieRule(
patternKind === 'global' ? null : urlPattern.trim(),
patternKind,
cookiesInput,
normalized.json,
)
setUrlPattern('')
setCookiesInput('{}')
@ -689,6 +877,44 @@ function CookiesTab() {
}
}
function handlePasteAdd(e) {
const clip = e.clipboardData?.getData('text')
if (!clip) return
const start = e.target.selectionStart ?? 0
const end = e.target.selectionEnd ?? 0
const action = pasteCookies(cookiesInput, start, end, clip)
if (!action) return
e.preventDefault()
if (action.error) {
setAddMsg({ ok: false, text: action.error })
} else {
setCookiesInput(action.text)
setAddMsg({ ok: true, text: action.message })
}
}
function handlePasteEdit(ruleUid, e) {
const clip = e.clipboardData?.getData('text')
if (!clip) return
const current = edits[ruleUid]?.cookiesInput ?? ''
const start = e.target.selectionStart ?? 0
const end = e.target.selectionEnd ?? 0
const action = pasteCookies(current, start, end, clip)
if (!action) return
e.preventDefault()
if (action.error) {
setEdits(prev => ({
...prev,
[ruleUid]: { ...prev[ruleUid], msg: { ok: false, text: action.error } },
}))
} else {
setEdits(prev => ({
...prev,
[ruleUid]: { ...prev[ruleUid], cookiesInput: action.text, msg: { ok: true, text: action.message } },
}))
}
}
async function handleDelete(ruleUid) {
try {
await deleteCookieRule(ruleUid)
@ -715,13 +941,14 @@ function CookiesTab() {
async function saveEdit(rule) {
const edit = edits[rule.rule_uid]
try { JSON.parse(edit.cookiesInput) } catch {
setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], msg: { ok: false, text: 'Invalid JSON' } } }))
const normalized = normalizeCookiesInput(edit.cookiesInput)
if (!normalized.ok) {
setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], msg: { ok: false, text: normalized.error } } }))
return
}
setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], saving: true, msg: null } }))
try {
await updateCookieRule(rule.rule_uid, { cookies_json: edit.cookiesInput })
await updateCookieRule(rule.rule_uid, { cookies_json: normalized.json })
cancelEdit(rule.rule_uid)
await load()
} catch (err) {
@ -767,6 +994,7 @@ function CookiesTab() {
style={{ fontFamily: 'monospace', fontSize: 12, width: '100%', minHeight: 60 }}
value={edit.cookiesInput}
onChange={ev => setEdits(prev => ({ ...prev, [rule.rule_uid]: { ...prev[rule.rule_uid], cookiesInput: ev.target.value } }))}
onPaste={ev => handlePasteEdit(rule.rule_uid, ev)}
/>
{edit.msg && <div className={`form-msg form-msg--${edit.msg.ok ? 'ok' : 'err'}`}>{edit.msg.text}</div>}
<div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
@ -829,9 +1057,13 @@ function CookiesTab() {
style={{ fontFamily: 'monospace', fontSize: 13, minHeight: 70 }}
value={cookiesInput}
onChange={e => setCookiesInput(e.target.value)}
onPaste={handlePasteAdd}
placeholder='{"SESSION": "abc123", "token": "xyz"}'
required
/>
<span className="muted" style={{ fontSize: 12, display: 'block', marginTop: 4 }}>
Paste JSON object, extension export, Netscape cookies.txt, or header string.
</span>
</div>
{addMsg && <div className={`form-msg form-msg--${addMsg.ok ? 'ok' : 'err'}`}>{addMsg.text}</div>}
<button className="btn-primary" type="submit" disabled={adding}>

View file

@ -1,5 +1,6 @@
import { useState } from 'react';
import { doSetup } from '../api.js';
import ThemeToggle from './ThemeToggle.jsx';
export default function SetupPage({ onComplete }) {
const [username, setUsername] = useState('');
@ -32,6 +33,7 @@ export default function SetupPage({ onComplete }) {
return (
<div className="setup-page">
<ThemeToggle className="auth-page-theme-toggle" />
<div className="setup-card">
<h1 className="setup-brand">Archivr</h1>
<p className="setup-tagline">Create your owner account to get started.</p>

View file

@ -0,0 +1,40 @@
import { useTheme } from '../useTheme.js'
export function SunIcon() {
return (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="8" cy="8" r="3" />
<line x1="8" y1="1" x2="8" y2="2.5" />
<line x1="8" y1="13.5" x2="8" y2="15" />
<line x1="3.05" y1="3.05" x2="4.11" y2="4.11" />
<line x1="11.89" y1="11.89" x2="12.95" y2="12.95" />
<line x1="1" y1="8" x2="2.5" y2="8" />
<line x1="13.5" y1="8" x2="15" y2="8" />
<line x1="3.05" y1="12.95" x2="4.11" y2="11.89" />
<line x1="11.89" y1="4.11" x2="12.95" y2="3.05" />
</svg>
)
}
export function MoonIcon() {
return (
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M13.5 9.8A6 6 0 1 1 6.2 2.5a4.7 4.7 0 0 0 7.3 7.3z" />
</svg>
)
}
export default function ThemeToggle({ className = 'theme-toggle-btn' }) {
const { preference, resolved, toggleTheme } = useTheme()
return (
<button
type="button"
className={className}
aria-label={`Switch to ${resolved === 'dark' ? 'light' : 'dark'} mode`}
title={`Theme: ${preference} (${resolved}). Click to toggle.`}
onClick={toggleTheme}
>
{resolved === 'dark' ? <SunIcon /> : <MoonIcon />}
</button>
)
}

View file

@ -1,6 +1,7 @@
import { useContext, useState } from 'react';
import { AuthContext } from '../App.jsx';
import { logout as apiLogout } from '../api.js';
import ThemeToggle from './ThemeToggle.jsx';
export default function Topbar({ archives, archiveId, onArchiveChange, view, onViewChange, onCaptureClick, collections, selectedCollectionUid, onCollectionChange, isPublicSession, onSignInClick }) {
const { currentUser, setCurrentUser } = useContext(AuthContext) ?? {};
@ -51,6 +52,9 @@ export default function Topbar({ archives, archiveId, onArchiveChange, view, onV
<>
<span style={{ flex: 1 }} />
<button className="logout-btn" onClick={onSignInClick}>Sign in</button>
<div className="user-menu">
<ThemeToggle />
</div>
</>
) : (
<>
@ -63,14 +67,17 @@ export default function Topbar({ archives, archiveId, onArchiveChange, view, onV
))}
</nav>
<button className="capture-button" onClick={onCaptureClick}>Capture</button>
{currentUser && (
<div className="user-menu">
<span className="user-name">{currentUser.display_name || currentUser.username}</span>
<button className="logout-btn" onClick={handleLogout} disabled={loggingOut}>
{loggingOut ? 'Logging out\u2026' : 'Log out'}
</button>
</div>
)}
<div className="user-menu">
<ThemeToggle />
{currentUser && (
<>
<span className="user-name">{currentUser.display_name || currentUser.username}</span>
<button className="logout-btn" onClick={handleLogout} disabled={loggingOut}>
{loggingOut ? 'Logging out\u2026' : 'Log out'}
</button>
</>
)}
</div>
</>
)}
</header>

View file

@ -0,0 +1,233 @@
/**
* Converts cookies pasted into Settings › Cookies into the cookie-rule format
* the server accepts: a JSON object whose values are all strings
* ({"name": "value"}).
*
* Recognised inputs:
* - archivr JSON: {"session": "abc"}
* - extension JSON: [{"name": "session", "value": "abc", "domain": …}, …]
* (Cookie-Editor / EditThisCookie export; a single such object also works)
* - Netscape: cookies.txt lines, including `#HttpOnly_` prefixed ones
* - header string: session=abc; theme=dark (optional `Cookie:` prefix)
*
* Rules are scoped by URL pattern, so domain/path/expiry/flags are dropped.
*/
const FORMAT_LABELS = {
archivr: 'archivr JSON',
extension: 'extension JSON',
netscape: 'Netscape',
header: 'header string',
}
// Same character rules as the extension session cookies (browserData.js).
const INVALID_NAME = /[\x00-\x1f\x7f ;=]/
const INVALID_VALUE = /[\x00-\x1f\x7f;]/
const NETSCAPE_HEADER = /^#\s*Netscape HTTP Cookie File/i
const HTTP_ONLY_PREFIX = '#HttpOnly_'
const BOOL_FIELD = /^(TRUE|FALSE)$/i
function fail(error) {
return { ok: false, error }
}
function checkPair(name, value) {
if (!name || INVALID_NAME.test(name)) {
return `Invalid cookie name ${JSON.stringify(name)}: names cannot be empty or contain spaces, ';' or '='.`
}
if (INVALID_VALUE.test(value)) {
return `Invalid value for cookie ${JSON.stringify(name)}: values cannot contain ';' or control characters.`
}
return null
}
function converted(format, entries) {
for (const [name, value] of entries) {
const err = checkPair(name, value)
if (err) return fail(err)
}
if (entries.length === 0) return fail(`No cookies found in ${FORMAT_LABELS[format]}.`)
return { ok: true, format, cookies: entries }
}
function isPlainObject(v) {
return v !== null && typeof v === 'object' && !Array.isArray(v)
}
function extensionCookie(item, index) {
if (!isPlainObject(item) || typeof item.name !== 'string' || typeof item.value !== 'string') {
return { error: `Cookie #${index + 1} needs string "name" and "value" fields.` }
}
return { entry: [item.name, item.value] }
}
function parseJson(text) {
let data
try { data = JSON.parse(text) } catch {
return fail('Invalid JSON.')
}
if (Array.isArray(data)) {
const entries = []
for (let i = 0; i < data.length; i++) {
const { entry, error } = extensionCookie(data[i], i)
if (error) return fail(error)
entries.push(entry)
}
return converted('extension', entries)
}
if (!isPlainObject(data)) {
return fail('Cookies JSON must be an object like {"session": "abc"} or an extension export array.')
}
const values = Object.values(data)
if (values.every(v => typeof v === 'string')) {
// Native format: passed through as-is (the server is the authority on it).
return { ok: true, format: 'archivr', cookies: Object.entries(data) }
}
// One cookie copied out of an extension export ({"name", "value", "domain", …}).
if (typeof data.name === 'string' && typeof data.value === 'string') {
return converted('extension', [[data.name, data.value]])
}
return fail('Cookie values must all be strings, e.g. {"session": "abc"}.')
}
function netscapeFields(line) {
const tabbed = line.split('\t')
if (tabbed.length >= 7) return tabbed
// Copies out of a terminal or chat often turn tabs into spaces.
return line.trim().split(/\s+/)
}
function looksLikeNetscapeLine(line) {
const fields = netscapeFields(line)
return fields.length >= 6 && BOOL_FIELD.test(fields[1]) && BOOL_FIELD.test(fields[3])
}
function cookieLines(text) {
return text.split(/\r?\n/)
.map(line => line.trimEnd())
.filter(line => line.trim() !== '')
.map(line => line.startsWith(HTTP_ONLY_PREFIX) ? line.slice(HTTP_ONLY_PREFIX.length) : line)
.filter(line => !line.startsWith('#'))
}
function parseNetscape(text) {
const entries = []
for (const line of cookieLines(text)) {
if (!looksLikeNetscapeLine(line)) {
return fail(`Not a Netscape cookie line: ${line.slice(0, 80)}`)
}
const fields = netscapeFields(line)
const sep = fields.length === line.split('\t').length ? '\t' : ' '
entries.push([fields[5], fields.slice(6).join(sep)])
}
return converted('netscape', entries)
}
function parseHeader(text) {
const body = text.trim().replace(/^cookie:\s*/i, '')
const entries = []
for (const part of body.split(/;|\r?\n/)) {
const pair = part.trim()
if (pair === '') continue
const eq = pair.indexOf('=')
if (eq <= 0) return fail(`Expected name=value, got ${JSON.stringify(pair.slice(0, 80))}.`)
entries.push([pair.slice(0, eq).trim(), pair.slice(eq + 1).trim()])
}
return converted('header', entries)
}
/**
* Parses cookies in any supported format.
* @param {string} text
* @returns {{ok: true, format: string, cookies: Array<[string, string]>} | {ok: false, error: string}}
*/
export function parseCookies(text) {
const trimmed = (text ?? '').trim()
if (trimmed === '') return fail('No cookies found.')
if (trimmed.startsWith('{') || trimmed.startsWith('[')) return parseJson(trimmed)
const firstLine = cookieLines(trimmed)[0]
if (NETSCAPE_HEADER.test(trimmed) || (firstLine !== undefined && looksLikeNetscapeLine(firstLine))) {
return parseNetscape(trimmed)
}
return parseHeader(trimmed)
}
/**
* Merges cookie lists; `incoming` wins on a name collision.
* @returns {{cookies: Object<string, string>, added: number, replaced: number}}
*/
export function mergeCookies(base, incoming) {
const merged = new Map(base)
let added = 0
let replaced = 0
for (const [name, value] of incoming) {
if (!merged.has(name)) added++
else if (merged.get(name) !== value) replaced++
merged.set(name, value)
}
// Object.fromEntries keeps names such as "__proto__" as own properties.
return { cookies: Object.fromEntries(merged), added, replaced }
}
export function formatCookies(cookies) {
return JSON.stringify(cookies, null, 2)
}
function plural(n, word) {
return `${n} ${word}${n === 1 ? '' : 's'}`
}
/**
* Normalises a cookie-rule textarea before it is sent to the server.
* Native JSON is sent unchanged; other formats are converted.
* @returns {{ok: true, json: string} | {ok: false, error: string}}
*/
export function normalizeCookiesInput(text) {
const parsed = parseCookies(text)
if (!parsed.ok) return parsed
if (parsed.format === 'archivr') return { ok: true, json: text }
return { ok: true, json: formatCookies(Object.fromEntries(parsed.cookies)) }
}
/**
* Decides what pasting `clip` over the selection [start, end) of `current` does.
*
* Returns null when the browser's normal paste should run: the result is
* already a valid cookie object (ordinary JSON editing), or the clipboard is
* not cookies at all. Otherwise the caller prevents the paste and either
* replaces the textarea with `text` or shows `error`.
*
* @returns {null | {text: string, message: string} | {error: string}}
*/
export function pasteCookies(current, start, end, clip) {
const before = current.slice(0, start)
const after = current.slice(end)
const combined = parseCookies(before + clip + after)
if (combined.ok && combined.format === 'archivr') return null
const incoming = parseCookies(clip)
if (!incoming.ok) return null
const label = FORMAT_LABELS[incoming.format]
const count = plural(incoming.cookies.length, 'cookie')
const rest = before + after
if (rest.trim() === '') {
return {
text: formatCookies(Object.fromEntries(incoming.cookies)),
message: `Converted ${count} from ${label}.`,
}
}
const existing = parseCookies(rest)
if (!existing.ok) {
return {
error: `Clipboard has ${count} (${label}), but the existing content isn't valid cookies (${existing.error}) — fix or clear it, then paste again.`,
}
}
const { cookies, added, replaced } = mergeCookies(existing.cookies, incoming.cookies)
const message = existing.cookies.length === 0
? `Converted ${count} from ${label}.`
: `Merged ${count} from ${label}: ${added} added, ${replaced} replaced.`
return { text: formatCookies(cookies), message }
}

View file

@ -0,0 +1,289 @@
import { describe, expect, test } from 'bun:test'
import {
parseCookies,
mergeCookies,
formatCookies,
normalizeCookiesInput,
pasteCookies,
} from './cookieImport.js'
// User's exact prompt sample: extension JSON
const EXTENSION_JSON_SAMPLE = `[
{
"domain": "127.0.0.1",
"expirationDate": 1794836374,
"hostOnly": true,
"httpOnly": true,
"name": "session",
"path": "/",
"sameSite": "strict",
"secure": false,
"session": false,
"storeId": null,
"value": "sess_2242ce38c8c54a49b80fab32e8556b82"
}
]`
// User's exact prompt sample: Netscape format
const NETSCAPE_SAMPLE = `# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by Cookie-Editor
#HttpOnly_127.0.0.1 FALSE / FALSE 1794836374 session sess_2242ce38c8c54a49b80fab32e8556b82`
// User's exact prompt sample: header string
const HEADER_SAMPLE = 'session=sess_2242ce38c8c54a49b80fab32e8556b82'
describe('parseCookies', () => {
test('parses extension JSON array', () => {
const res = parseCookies(EXTENSION_JSON_SAMPLE)
expect(res.ok).toBe(true)
expect(res.format).toBe('extension')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses single extension cookie object', () => {
const single = JSON.parse(EXTENSION_JSON_SAMPLE)[0]
const res = parseCookies(JSON.stringify(single))
expect(res.ok).toBe(true)
expect(res.format).toBe('extension')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses Netscape cookie file with #HttpOnly_ and whitespace-separated fields', () => {
const res = parseCookies(NETSCAPE_SAMPLE)
expect(res.ok).toBe(true)
expect(res.format).toBe('netscape')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses standard tab-separated Netscape file', () => {
const tabbed = [
'# Netscape HTTP Cookie File',
'.example.com\tTRUE\t/\tFALSE\t1794836374\tsession\tsess_123',
'#HttpOnly_.example.com\tTRUE\t/\tTRUE\t1794836374\tcsrf\ttoken_456',
].join('\n')
const res = parseCookies(tabbed)
expect(res.ok).toBe(true)
expect(res.format).toBe('netscape')
expect(res.cookies).toEqual([
['session', 'sess_123'],
['csrf', 'token_456'],
])
})
test('handles CRLF line endings in Netscape file', () => {
const crlf = NETSCAPE_SAMPLE.replace(/\n/g, '\r\n')
const res = parseCookies(crlf)
expect(res.ok).toBe(true)
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses header string', () => {
const res = parseCookies(HEADER_SAMPLE)
expect(res.ok).toBe(true)
expect(res.format).toBe('header')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses header string with Cookie: prefix and multiple pairs', () => {
const res = parseCookies('Cookie: a=1; b=2=3; c="quoted"')
expect(res.ok).toBe(true)
expect(res.format).toBe('header')
expect(res.cookies).toEqual([
['a', '1'],
['b', '2=3'], // value preserves subsequent '='
['c', '"quoted"'],
])
})
test('parses multiline header strings (newline separated)', () => {
const res = parseCookies('a=1\nb=2\r\nc=3')
expect(res.ok).toBe(true)
expect(res.cookies).toEqual([['a', '1'], ['b', '2'], ['c', '3']])
})
test('identifies native archivr JSON', () => {
const res = parseCookies('{"session": "sess_2242ce38c8c54a49b80fab32e8556b82"}')
expect(res.ok).toBe(true)
expect(res.format).toBe('archivr')
expect(res.cookies).toEqual([
['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'],
])
})
test('parses empty object as native archivr JSON', () => {
const res = parseCookies('{}')
expect(res.ok).toBe(true)
expect(res.format).toBe('archivr')
expect(res.cookies).toEqual([])
})
test('rejects empty string', () => {
expect(parseCookies('').ok).toBe(false)
expect(parseCookies(' ').ok).toBe(false)
})
test('rejects cookie name with space or semicolon', () => {
expect(parseCookies('bad name=val').ok).toBe(false)
expect(parseCookies('bad;name=val').ok).toBe(false)
})
test('rejects cookie value with control chars', () => {
expect(parseCookies('name=val\x00x').ok).toBe(false)
})
test('rejects malformed extension entry missing value', () => {
const res = parseCookies('[{"name": "foo"}]')
expect(res.ok).toBe(false)
expect(res.error).toMatch(/needs string "name" and "value"/)
})
})
describe('mergeCookies', () => {
test('merges base and incoming; incoming overwrites collision', () => {
const base = [['a', '1'], ['b', '2']]
const incoming = [['b', 'overwritten'], ['c', '3']]
const res = mergeCookies(base, incoming)
expect(res.cookies).toEqual({
a: '1',
b: 'overwritten',
c: '3',
})
expect(res.added).toBe(1)
expect(res.replaced).toBe(1)
})
test('detects unchanged values as not replaced', () => {
const base = [['a', '1']]
const incoming = [['a', '1']]
const res = mergeCookies(base, incoming)
expect(res.added).toBe(0)
expect(res.replaced).toBe(0)
})
test('preserves reserved property names like __proto__', () => {
const res = mergeCookies([], [['__proto__', 'safe']])
expect(Object.hasOwn(res.cookies, '__proto__')).toBe(true)
expect(res.cookies['__proto__']).toBe('safe')
})
})
describe('normalizeCookiesInput', () => {
test('passes native JSON string through verbatim', () => {
const native = '{\n "session": "abc"\n}'
expect(normalizeCookiesInput(native)).toEqual({ ok: true, json: native })
})
test('converts extension JSON to pretty JSON', () => {
const res = normalizeCookiesInput(EXTENSION_JSON_SAMPLE)
expect(res.ok).toBe(true)
expect(JSON.parse(res.json)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
})
test('converts Netscape to pretty JSON', () => {
const res = normalizeCookiesInput(NETSCAPE_SAMPLE)
expect(res.ok).toBe(true)
expect(JSON.parse(res.json)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
})
test('converts header string to pretty JSON', () => {
const res = normalizeCookiesInput(HEADER_SAMPLE)
expect(res.ok).toBe(true)
expect(JSON.parse(res.json)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
})
test('returns error for invalid input', () => {
const res = normalizeCookiesInput('not a valid cookie string')
expect(res.ok).toBe(false)
})
})
describe('pasteCookies', () => {
test('returns null if entire pasted result is already valid native JSON', () => {
// Normal JSON typing/editing: pasting `"abc"` into `{"a": }`
const current = '{"a": }'
// Cursor right after the space: start = 6, end = 6
const res = pasteCookies(current, 6, 6, '"abc"')
expect(res).toBeNull()
})
test('returns null if clipboard is not cookies at all', () => {
const res = pasteCookies('{}', 0, 2, 'hello world')
expect(res).toBeNull()
})
test('converts clipboard when textarea is default empty object and selected entirely', () => {
const res = pasteCookies('{}', 0, 2, EXTENSION_JSON_SAMPLE)
expect(res).not.toBeNull()
expect(res.error).toBeUndefined()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Converted 1 cookie from extension JSON/)
})
test('converts clipboard when textarea is completely empty', () => {
const res = pasteCookies('', 0, 0, HEADER_SAMPLE)
expect(res).not.toBeNull()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Converted 1 cookie from header string/)
})
test('merges into existing native JSON', () => {
const current = '{\n "existing": "val"\n}'
const res = pasteCookies(current, current.length, current.length, NETSCAPE_SAMPLE)
expect(res).not.toBeNull()
expect(res.error).toBeUndefined()
expect(JSON.parse(res.text)).toEqual({
existing: 'val',
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Merged 1 cookie from Netscape: 1 added, 0 replaced/)
})
test('overwrites existing keys when pasting newer values', () => {
const current = '{\n "session": "old_value"\n}'
const res = pasteCookies(current, current.length, current.length, HEADER_SAMPLE)
expect(res).not.toBeNull()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
})
expect(res.message).toMatch(/Merged 1 cookie from header string: 0 added, 1 replaced/)
})
test('merges into existing Netscape content (if user already had that in textarea)', () => {
const current = NETSCAPE_SAMPLE
const clip = 'extra=value_123'
const res = pasteCookies(current, current.length, current.length, clip)
expect(res).not.toBeNull()
expect(JSON.parse(res.text)).toEqual({
session: 'sess_2242ce38c8c54a49b80fab32e8556b82',
extra: 'value_123',
})
})
test('returns error when clipboard has cookies but remaining textarea is invalid', () => {
const current = '{"broken json: '
const res = pasteCookies(current, current.length, current.length, HEADER_SAMPLE)
expect(res).not.toBeNull()
expect(res.error).toMatch(/existing content isn't valid cookies/)
})
})

View file

@ -15,6 +15,36 @@
--link: #245f72;
--top: #141d18;
--field: #fffdf7;
--lift: #fff;
--row-alt: #f2ede5;
--row-selected: #eee2d2;
--child-row-a: #fafaf8;
--child-row-b: #f2f0ec;
--url-ink: #555b55;
--pill-bg: #d8e3df;
--pill-ink: #275a5f;
--pill-line: #bfd0ca;
--ok-bg: #d8eddf;
--ok-ink: #235c35;
--ok-line: #b4d9be;
--err-bg: #f5ddd8;
--err-ink: #8d3f30;
--err-line: #e0b8b0;
--err-row: #fdf0ed;
--warn-bg: #fdefd8;
--warn-ink: #8a4f10;
--warn-line: #f0cfa0;
--conflict-ink: #c07000;
--conflict-bg: #fff3cd;
--conflict-line: #e0a000;
--alert: #c05000;
--disabled-bg: #ede8e0;
--ink-hover: #2c332b;
/* Primary buttons: dark-on-light page, light-on-dark page. */
--strong: var(--top);
--on-strong: #f5f0e7;
/* Text on --accent fills; stays light in both themes. */
--on-accent: #f5f0e7;
--r: 3px;
--r2: 6px;
--r3: 10px;
@ -23,6 +53,52 @@
--display: "Cormorant Garamond", Georgia, serif;
}
/* data-theme is always resolved to light|dark by /theme-init.js before first
paint and kept in sync by src/theme.js. */
:root[data-theme="dark"] {
color-scheme: dark;
--ink: #e6dfd1;
--muted: #a29d91;
--muted-2: #858074;
--paper: #171916;
--paper-2: #23261f;
--paper-3: #1d201b;
--line: #3a3e35;
--line-soft: #2b2e27;
--accent: #b85d46;
--accent-2: #c9944f;
--link: #79b4c6;
--top: #0e110f;
--field: #1a1d18;
--lift: #33372f;
--row-alt: #191c17;
--row-selected: #352d25;
--child-row-a: #1b1e19;
--child-row-b: #181b16;
--url-ink: #9b9e94;
--pill-bg: #1d3236;
--pill-ink: #9ccdd6;
--pill-line: #2f4c51;
--ok-bg: #1b3223;
--ok-ink: #8fd0a2;
--ok-line: #2d5038;
--err-bg: #3b211b;
--err-ink: #f0a08e;
--err-line: #5c3329;
--err-row: #2a1b17;
--warn-bg: #382a15;
--warn-ink: #e6b169;
--warn-line: #5a4321;
--conflict-ink: #e9a646;
--conflict-bg: #352a11;
--conflict-line: #7d5c12;
--alert: #f08b4f;
--disabled-bg: #262922;
--ink-hover: #d3ccbe;
--strong: var(--ink);
--on-strong: var(--paper);
}
* {
box-sizing: border-box;
}
@ -216,7 +292,7 @@ select {
align-items: center;
gap: 16px;
padding: 12px 22px;
background: color-mix(in srgb, var(--paper) 88%, white);
background: color-mix(in srgb, var(--paper) 88%, var(--lift));
border-bottom: 1px solid var(--line-soft);
}
.search-field {
@ -286,7 +362,7 @@ select {
position: sticky;
top: 67px;
z-index: 2;
background: color-mix(in srgb, var(--paper) 92%, white);
background: color-mix(in srgb, var(--paper) 92%, var(--lift));
border-bottom: 1px solid var(--line-soft);
color: var(--muted);
font-size: 10.5px;
@ -303,17 +379,17 @@ select {
}
#entries-body > div > div { padding: 7px 10px; flex-shrink: 0; overflow: hidden; }
/* Pending capture rows (no index class) fall back to nth-child; real rows use explicit classes. */
#entries-body > div:not(.entry-row-outer):nth-child(even) { background: #f2ede5; }
#entries-body > div:not(.entry-row-outer):nth-child(even) { background: var(--row-alt); }
#entries-body > div:not(.entry-row-outer):nth-child(odd) { background: var(--paper-3); }
/* Index-based stripes for real entry rows — immune to pending-capture sibling count. */
#entries-body > .entry-row-outer--light { background: var(--paper-3); }
#entries-body > .entry-row-outer--dark { background: #f2ede5; }
#entries-body > .entry-row-outer--dark { background: var(--row-alt); }
#entries-body > div.is-selected {
background: #eee2d2;
background: var(--row-selected);
box-shadow: inset 0 0 0 2px var(--accent);
}
#entries-body > div.is-multi-selected {
background: #eee2d2;
background: var(--row-selected);
box-shadow: inset 0 0 0 2px var(--accent);
}
@ -340,12 +416,33 @@ select {
.entry-title { color: var(--link); font-weight: 700; min-width: 0; }
.entry-header-row > div { padding: 9px 10px; flex-shrink: 0; font-weight: 600; }
.source-icon { display: flex; align-items: center; justify-content: center; width: 1.05em; height: 1.05em; flex-shrink: 0; }
.source-icon {
display: flex;
align-items: center;
justify-content: center;
width: 1.05em;
height: 1.05em;
flex-shrink: 0;
color: var(--ink);
opacity: 0.88;
}
.source-icon:hover,
#entries-body > div:hover .source-icon,
#entries-body > div.is-selected .source-icon,
.child-entry-row:hover .source-icon,
.child-entry-row.is-selected .source-icon {
opacity: 1;
}
.source-icon > * { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
.source-icon svg { width: 100%; height: 100%; }
.url-cell { color: #555b55; white-space: nowrap; text-overflow: ellipsis; word-break: break-all; }
.source-icon svg path:not([fill]) { fill: currentColor; }
:root[data-theme="dark"] .favicon-img {
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
}
.url-cell { color: var(--url-ink); white-space: nowrap; text-overflow: ellipsis; word-break: break-all; }
#entries-body .url-cell:hover { overflow: visible; white-space: normal; }
.type-pill { display: inline-block; padding: 2px 6px; background: #d8e3df; color: #275a5f; border: 1px solid #bfd0ca; border-radius: var(--r); }
.type-pill { display: inline-block; padding: 2px 6px; background: var(--pill-bg); color: var(--pill-ink); border: 1px solid var(--pill-line); border-radius: var(--r); }
/* ── Multi-select checkbox column ───────────────────────────────────────── */
/* Hidden on desktop (pointer:fine); always visible on touch/mobile */
@ -408,7 +505,7 @@ select {
z-index: 1;
text-align: left;
padding: 10px;
background: color-mix(in srgb, var(--paper) 92%, white);
background: color-mix(in srgb, var(--paper) 92%, var(--lift));
color: var(--muted);
border-bottom: 1px solid var(--line-soft);
font-size: 10.5px;
@ -420,7 +517,7 @@ select {
border-bottom: 1px solid var(--line-soft);
vertical-align: top;
}
#runs-view .entry-table tr:nth-child(even) td { background: #f2ede5; }
#runs-view .entry-table tr:nth-child(even) td { background: var(--row-alt); }
#runs-view .entry-table tr:nth-child(odd) td { background: var(--paper-3); }
/* ── Context rail ────────────────────────────────────────────────────────── */
@ -578,7 +675,7 @@ select {
text-transform: uppercase; border-radius: var(--r);
cursor: pointer; white-space: nowrap;
}
.tag-add-btn:hover { background: #2c332b; }
.tag-add-btn:hover { background: var(--ink-hover); }
/* collections in rail */
.coll-row {
@ -1046,7 +1143,7 @@ select {
color: var(--muted);
font-style: italic;
}
.capture-quality-hint--error { color: #c05000; font-style: normal; }
.capture-quality-hint--error { color: var(--alert); font-style: normal; }
/* Status dot */
.cap-dot {
@ -1061,9 +1158,9 @@ select {
line-height: 1;
}
.cap-dot--idle { background: var(--paper-2); }
.cap-dot--running { background: #fdefd8; color: #8a4f10; }
.cap-dot--ok { background: #d8eddf; color: #235c35; }
.cap-dot--err { background: #f5ddd8; color: #8d3f30; }
.cap-dot--running { background: var(--warn-bg); color: var(--warn-ink); }
.cap-dot--ok { background: var(--ok-bg); color: var(--ok-ink); }
.cap-dot--err { background: var(--err-bg); color: var(--err-ink); }
/* Spinner inside the running dot */
.cap-spinner {
@ -1317,12 +1414,12 @@ select {
line-height: 1;
}
.capture-file-badge--done {
background: #d8eddf;
color: #235c35;
background: var(--ok-bg);
color: var(--ok-ink);
}
.capture-file-badge--error {
background: #f5ddd8;
color: #8d3f30;
background: var(--err-bg);
color: var(--err-ink);
}
/* ── Toast stack ─────────────────────────────────────────────────────────── */
@ -1877,7 +1974,7 @@ select {
cursor: pointer;
border-radius: var(--r);
}
.coll-delete-btn:hover { background: var(--accent); color: var(--paper); }
.coll-delete-btn:hover { background: var(--accent); color: var(--on-accent); }
.coll-detail-vis {
display: flex;
align-items: center;
@ -2042,8 +2139,32 @@ select {
white-space: nowrap;
transition: background 0.15s, color 0.15s;
}
.logout-btn:hover { background: rgba(255,255,255,0.1); color: var(--paper); }
.logout-btn:hover { background: rgba(255,255,255,0.1); color: #f5f0e7; }
.logout-btn:disabled { opacity: 0.5; cursor: default; }
.theme-toggle-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
padding: 0;
border: 1px solid rgba(255,255,255,0.18);
background: transparent;
color: #c8bfb0;
border-radius: var(--r);
cursor: pointer;
transition: background 0.15s, color 0.15s, border-color 0.15s;
}
.theme-toggle-btn:hover {
background: rgba(255,255,255,0.1);
color: #f5f0e7;
border-color: rgba(255,255,255,0.32);
}
.theme-toggle-btn svg {
width: 14px;
height: 14px;
display: block;
}
/* ── Login / Setup pages ─────────────────────────────────────────────────── */
.login-page,
@ -2054,6 +2175,7 @@ select {
align-items: center;
justify-content: center;
background: var(--paper);
position: relative;
}
.login-card,
.setup-card {
@ -2065,6 +2187,32 @@ select {
border-radius: var(--r3);
box-shadow: 0 2px 20px rgba(20,29,24,0.07);
}
.auth-page-theme-toggle {
position: absolute;
top: 18px;
right: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
border: 1px solid var(--line);
background: var(--paper-2);
color: var(--ink);
border-radius: var(--r2);
cursor: pointer;
transition: background 0.15s, border-color 0.15s;
}
.auth-page-theme-toggle:hover {
background: var(--field);
border-color: var(--accent);
}
.auth-page-theme-toggle svg {
width: 16px;
height: 16px;
display: block;
}
.login-brand,
.setup-brand {
font-family: var(--display);
@ -2120,8 +2268,8 @@ select {
width: 100%;
margin-top: 8px;
border: none;
background: var(--top);
color: var(--paper);
background: var(--strong);
color: var(--on-strong);
font-size: 14px;
font-weight: 600;
padding: 11px 16px;
@ -2204,8 +2352,8 @@ select {
.form-msg--err { color: var(--accent); }
.btn-primary {
border: none;
background: var(--top);
color: var(--paper);
background: var(--strong);
color: var(--on-strong);
font-size: 13px;
font-weight: 600;
padding: 8px 16px;
@ -2234,7 +2382,7 @@ select {
border-radius: var(--r);
cursor: pointer;
}
.btn-danger:hover { background: var(--accent); color: var(--paper); }
.btn-danger:hover { background: var(--accent); color: var(--on-accent); }
/* ── Admin view overrides ────────────────────────────────────────────────── */
.admin-view h1 { font-family: var(--display); font-weight: 600; font-size: 26px; margin: 0 0 20px; }
@ -2324,8 +2472,8 @@ select {
text-transform: uppercase;
letter-spacing: 0.04em;
}
.status-active { background: #d8eddf; color: #235c35; border: 1px solid #b4d9be; }
.status-disabled { background: #ede8e0; color: var(--muted); border: 1px solid var(--line); }
.status-active { background: var(--ok-bg); color: var(--ok-ink); border: 1px solid var(--ok-line); }
.status-disabled { background: var(--disabled-bg); color: var(--muted); border: 1px solid var(--line); }
/* ── Runs view improvements ──────────────────────────────────────────────── */
.run-status {
@ -2337,13 +2485,13 @@ select {
text-transform: uppercase;
letter-spacing: 0.04em;
}
.run-status--completed { background: #d8eddf; color: #235c35; border: 1px solid #b4d9be; }
.run-status--failed { background: #f5ddd8; color: #8d3f30; border: 1px solid #e0b8b0; }
.run-status--in-progress { background: #fdefd8; color: #8a4f10; border: 1px solid #f0cfa0; }
.run-status--completed { background: var(--ok-bg); color: var(--ok-ink); border: 1px solid var(--ok-line); }
.run-status--failed { background: var(--err-bg); color: var(--err-ink); border: 1px solid var(--err-line); }
.run-status--in-progress { background: var(--warn-bg); color: var(--warn-ink); border: 1px solid var(--warn-line); }
/* Clickable failed run rows and expandable error detail */
.run-row--failed { cursor: pointer; }
.run-row--failed:hover td { background: #fdf0ed !important; }
.run-row--failed:hover td { background: var(--err-row) !important; }
.run-expand-hint {
margin-left: 6px;
font-size: 10px;
@ -2369,8 +2517,8 @@ select {
/* ── Token created banner ────────────────────────────────────────────────── */
.token-banner {
background: #d8eddf;
border: 1px solid #b4d9be;
background: var(--ok-bg);
border: 1px solid var(--ok-line);
padding: 12px 14px;
margin-bottom: 16px;
font-size: 13px;
@ -2425,7 +2573,7 @@ select {
color: var(--muted);
background: var(--paper-2);
}
.session-badge { background: #d8eddf; color: #235c35; border-color: #b4d9be; }
.session-badge { background: var(--ok-bg); color: var(--ok-ink); border-color: var(--ok-line); }
.token-expiry { font-size: 12px; color: var(--muted); margin-top: 2px; }
.token-expiry--expired { color: var(--accent); }
.session-row {
@ -2440,7 +2588,7 @@ select {
}
.session-row .muted { font-size: 12px; margin-top: 2px; }
.admin-action-btn--danger { color: var(--accent); border-color: var(--accent); }
.admin-action-btn--danger:hover { background: #f5ddd8; }
.admin-action-btn--danger:hover { background: var(--err-bg); }
/* ── Instance settings checkboxes ───────────────────────────────────────── */
.checkbox-row {
@ -3079,7 +3227,7 @@ google-cast-launcher.video-tv-btn {
height: 38px;
border-radius: 50%;
background: var(--accent);
color: var(--paper);
color: var(--on-accent);
border: none;
cursor: pointer;
display: flex;
@ -3235,7 +3383,7 @@ google-cast-launcher.video-tv-btn {
padding: 8px 12px;
margin-bottom: 16px;
background: var(--accent);
color: var(--paper);
color: var(--on-accent);
border: none;
border-radius: var(--r3);
font-size: 13px;
@ -3340,11 +3488,11 @@ body.has-audio-bar { padding-bottom: 56px; }
#entries-body > .entry-row-outer.is-selected { background: unset; outline: none; box-shadow: none; }
#entries-body > .entry-row-outer.is-multi-selected { background: unset; outline: none; box-shadow: none; }
#entries-body > .entry-row-outer.is-selected > .entry-row-main {
background: #eee2d2;
background: var(--row-selected);
box-shadow: inset 0 0 0 2px var(--accent);
}
#entries-body > .entry-row-outer.is-multi-selected > .entry-row-main {
background: #eee2d2;
background: var(--row-selected);
box-shadow: inset 0 0 0 2px var(--accent);
}
@ -3371,15 +3519,15 @@ body.has-audio-bar { padding-bottom: 56px; }
}
.child-entry-row:hover { opacity: 1; }
.child-entry-row:last-child { border-bottom: none; }
.child-entry-row--light { background: #fafaf8; }
.child-entry-row--dark { background: #f2f0ec; }
.child-entry-row--light { background: var(--child-row-a); }
.child-entry-row--dark { background: var(--child-row-b); }
.child-entry-row.is-selected {
background: #eee2d2;
background: var(--row-selected);
box-shadow: inset 0 0 0 2px var(--accent);
opacity: 1;
}
.child-entry-row.is-multi-selected {
background: #eee2d2;
background: var(--row-selected);
box-shadow: inset 0 0 0 2px var(--accent);
opacity: 1;
}
@ -3515,9 +3663,9 @@ body.has-audio-bar { padding-bottom: 56px; }
.capture-conflict-badge {
font-size: 0.7rem;
color: #c07000;
background: #fff3cd;
border: 1px solid #e0a000;
color: var(--conflict-ink);
background: var(--conflict-bg);
border: 1px solid var(--conflict-line);
border-radius: 4px;
padding: 1px 6px;
margin-left: 6px;
@ -3542,8 +3690,8 @@ body.has-audio-bar { padding-bottom: 56px; }
}
.capture-playlist-item:last-of-type { border-bottom: none; }
.capture-playlist-item--conflict {
border-left-color: #c07000;
background: color-mix(in srgb, #c07000 6%, transparent);
border-left-color: var(--conflict-ink);
background: color-mix(in srgb, var(--conflict-ink) 6%, transparent);
}
.capture-playlist-item-title {
flex: 1;
@ -3566,7 +3714,7 @@ body.has-audio-bar { padding-bottom: 56px; }
.capture-playlist-conflict-badge {
font-size: 0.68rem;
font-weight: 600;
color: #c07000;
color: var(--conflict-ink);
white-space: nowrap;
flex-shrink: 0;
}
@ -3588,7 +3736,7 @@ body.has-audio-bar { padding-bottom: 56px; }
}
.capture-playlist-item:hover .capture-playlist-item-remove,
.capture-playlist-item-remove:focus-visible { opacity: 1; }
.capture-playlist-item-remove:hover { color: #c04000; opacity: 1; }
.capture-playlist-item-remove:hover { color: var(--alert); opacity: 1; }
@media (pointer: coarse) { .capture-playlist-item-remove { opacity: 1; } }
.capture-playlist-item-remove { font-size: 0.75rem; line-height: 1; }

113
frontend/src/theme.js Normal file
View file

@ -0,0 +1,113 @@
export const THEME_KEY = 'archivr-theme'
export const THEMES = ['system', 'light', 'dark']
export function parseThemePreference(val) {
return val === 'light' || val === 'dark' ? val : 'system'
}
export function getStoredThemePreference() {
if (typeof window === 'undefined' || !window.localStorage) return 'system'
try {
return parseThemePreference(window.localStorage.getItem(THEME_KEY))
} catch {
return 'system'
}
}
export function systemPrefersDark() {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
try {
return window.matchMedia('(prefers-color-scheme: dark)').matches
} catch {
return false
}
}
export function resolveTheme(preference, isDark) {
const pref = parseThemePreference(preference)
if (pref === 'system') return isDark ? 'dark' : 'light'
return pref
}
export function applyTheme(preference) {
if (typeof document === 'undefined') return 'light'
const isDark = systemPrefersDark()
const resolved = resolveTheme(preference, isDark)
document.documentElement.dataset.theme = resolved
return resolved
}
const listeners = new Set()
function notify() {
for (const cb of listeners) {
try { cb() } catch { /* ignore subscriber error */ }
}
}
export function setThemePreference(preference) {
const valid = parseThemePreference(preference)
if (typeof window !== 'undefined' && window.localStorage) {
try {
if (valid === 'system') {
window.localStorage.removeItem(THEME_KEY)
} else {
window.localStorage.setItem(THEME_KEY, valid)
}
} catch {
// storage unavailable / quota exceeded
}
}
applyTheme(valid)
notify()
return valid
}
// Attach listeners once in browser environments
let mediaQueryList = null
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
try {
mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)')
const onMediaChange = () => {
const currentPref = getStoredThemePreference()
if (currentPref === 'system') {
applyTheme('system')
notify()
}
}
if (typeof mediaQueryList.addEventListener === 'function') {
mediaQueryList.addEventListener('change', onMediaChange)
} else if (typeof mediaQueryList.addListener === 'function') {
mediaQueryList.addListener(onMediaChange)
}
} catch {
// ignore matchMedia setup failures
}
window.addEventListener('storage', (e) => {
if (e.key === THEME_KEY) {
applyTheme(getStoredThemePreference())
notify()
}
})
}
export function subscribeTheme(callback) {
listeners.add(callback)
return () => {
listeners.delete(callback)
}
}
export function getThemeSnapshot() {
const preference = getStoredThemePreference()
const resolved = resolveTheme(preference, systemPrefersDark())
return `${preference}:${resolved}`
}
if (typeof document !== 'undefined') {
try {
applyTheme(getStoredThemePreference())
} catch {
/* ignore in environments with partial DOM mocks */
}
}

116
frontend/src/theme.test.js Normal file
View file

@ -0,0 +1,116 @@
import { describe, it, expect, beforeEach, afterAll } from 'bun:test'
function makeStorage() {
const store = new Map()
return {
getItem: (k) => (store.has(k) ? store.get(k) : null),
setItem: (k, v) => store.set(k, String(v)),
removeItem: (k) => store.delete(k),
clear: () => store.clear(),
}
}
const originalWindow = globalThis.window
const mockStorage = makeStorage()
globalThis.window = {
localStorage: mockStorage,
matchMedia: (query) => ({
matches: false,
media: query,
addEventListener: () => {},
removeEventListener: () => {},
}),
addEventListener: () => {},
removeEventListener: () => {},
}
const {
THEME_KEY,
parseThemePreference,
resolveTheme,
getStoredThemePreference,
setThemePreference,
subscribeTheme,
applyTheme,
} = await import('./theme.js')
describe('theme preference and resolution', () => {
beforeEach(() => {
mockStorage.clear()
})
afterAll(() => {
globalThis.window = originalWindow
})
it('parses valid and invalid preference strings', () => {
expect(parseThemePreference('light')).toBe('light')
expect(parseThemePreference('dark')).toBe('dark')
expect(parseThemePreference('system')).toBe('system')
expect(parseThemePreference('auto')).toBe('system')
expect(parseThemePreference('')).toBe('system')
expect(parseThemePreference(null)).toBe('system')
expect(parseThemePreference(undefined)).toBe('system')
expect(parseThemePreference('DARK')).toBe('system')
})
it('resolves explicit preference over system state', () => {
expect(resolveTheme('light', true)).toBe('light')
expect(resolveTheme('light', false)).toBe('light')
expect(resolveTheme('dark', true)).toBe('dark')
expect(resolveTheme('dark', false)).toBe('dark')
})
it('resolves system preference according to system state', () => {
expect(resolveTheme('system', true)).toBe('dark')
expect(resolveTheme('system', false)).toBe('light')
expect(resolveTheme('unknown', true)).toBe('dark')
expect(resolveTheme('unknown', false)).toBe('light')
})
it('stores explicit preference and removes item for system', () => {
setThemePreference('dark')
expect(mockStorage.getItem(THEME_KEY)).toBe('dark')
expect(getStoredThemePreference()).toBe('dark')
setThemePreference('light')
expect(mockStorage.getItem(THEME_KEY)).toBe('light')
expect(getStoredThemePreference()).toBe('light')
setThemePreference('system')
expect(mockStorage.getItem(THEME_KEY)).toBeNull()
expect(getStoredThemePreference()).toBe('system')
})
it('notifies subscribers when preference changes', () => {
let callCount = 0
const unsubscribe = subscribeTheme(() => {
callCount += 1
})
setThemePreference('dark')
expect(callCount).toBe(1)
setThemePreference('light')
expect(callCount).toBe(2)
unsubscribe()
setThemePreference('system')
expect(callCount).toBe(2)
})
it('applies theme to document element dataset when document exists', () => {
const originalDoc = globalThis.document
const htmlEl = { dataset: {} }
globalThis.document = { documentElement: htmlEl }
try {
applyTheme('dark')
expect(htmlEl.dataset.theme).toBe('dark')
applyTheme('light')
expect(htmlEl.dataset.theme).toBe('light')
} finally {
globalThis.document = originalDoc
}
})
})

32
frontend/src/useTheme.js Normal file
View file

@ -0,0 +1,32 @@
import { useSyncExternalStore, useCallback } from 'react'
import {
getStoredThemePreference,
systemPrefersDark,
resolveTheme,
setThemePreference,
subscribeTheme,
getThemeSnapshot,
} from './theme.js'
export function useTheme() {
const snapshot = useSyncExternalStore(subscribeTheme, getThemeSnapshot, () => 'system:light')
const [preference, resolved] = snapshot.split(':')
const setPreference = useCallback((next) => {
setThemePreference(next)
}, [])
const toggleTheme = useCallback(() => {
// If currently resolving to dark -> switch to light. Otherwise -> switch to dark.
const currentResolved = resolveTheme(getStoredThemePreference(), systemPrefersDark())
const next = currentResolved === 'dark' ? 'light' : 'dark'
setThemePreference(next)
}, [])
return {
preference,
resolved,
setPreference,
toggleTheme,
}
}

View file

@ -49,15 +49,15 @@ export const SOURCE_ICONS = {
youtube: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#FF0000" d="M23.5 6.2a3 3 0 0 0-2.1-2.1C19.5 3.6 12 3.6 12 3.6s-7.5 0-9.4.5A3 3 0 0 0 .5 6.2C0 8.1 0 12 0 12s0 3.9.5 5.8a3 3 0 0 0 2.1 2.1c1.9.5 9.4.5 9.4.5s7.5 0 9.4-.5a3 3 0 0 0 2.1-2.1C24 15.9 24 12 24 12s0-3.9-.5-5.8z"/><polygon fill="#fff" points="9.6,15.6 15.8,12 9.6,8.4"/></svg>`,
youtube_music: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="#FF0000"/><polygon fill="#fff" points="9.6,15.6 15.8,12 9.6,8.4"/></svg>`,
spotify: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="#1DB954"/><path fill="#fff" d="M17.9 10.9c-3.2-1.9-8.5-2.1-11.6-1.1-.5.1-1-.2-1.1-.6-.1-.5.2-1 .6-1.1 3.5-1.1 9.4-.9 13 1.3.4.2.6.8.3 1.2-.2.5-.8.6-1.2.3zm-.1 2.9c-.2.4-.7.5-1.1.3-2.7-1.6-6.7-2.1-9.9-1.1-.4.1-.9-.1-1-.5-.1-.4.1-.9.5-1 3.6-1.1 8-.5 11.1 1.3.4.2.5.7.4 1zm-1.3 2.8c-.2.3-.6.4-.9.2-2.3-1.4-5.2-1.7-8.6-.9-.3.1-.7-.1-.8-.5-.1-.3.1-.7.4-.8 3.7-.9 7-.5 9.6 1 .4.2.5.6.3.9z"/></svg>`,
x: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M18.2 2h3.3l-7.2 8.2L23 22h-6.6l-5.2-6.8L5 22H1.7l7.7-8.8L1 2h6.8l4.7 6.2zm-1.1 18h1.8L6.9 3.9H5z"/></svg>`,
x: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M18.2 2h3.3l-7.2 8.2L23 22h-6.6l-5.2-6.8L5 22H1.7l7.7-8.8L1 2h6.8l4.7 6.2zm-1.1 18h1.8L6.9 3.9H5z"/></svg>`,
instagram: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="ig" x1="0%" y1="100%" x2="100%" y2="0%"><stop offset="0%" stop-color="#f09433"/><stop offset="25%" stop-color="#e6683c"/><stop offset="50%" stop-color="#dc2743"/><stop offset="75%" stop-color="#cc2366"/><stop offset="100%" stop-color="#bc1888"/></linearGradient></defs><rect width="24" height="24" rx="5" fill="url(#ig)"/><rect x="2.5" y="2.5" width="19" height="19" rx="4" fill="none" stroke="#fff" stroke-width="1.5"/><circle cx="12" cy="12" r="4" fill="none" stroke="#fff" stroke-width="1.5"/><circle cx="17.5" cy="6.5" r="1" fill="#fff"/></svg>`,
facebook: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><rect width="24" height="24" rx="4" fill="#1877F2"/><path fill="#fff" d="M16 8h-2c-.6 0-1 .4-1 1v2h3l-.4 3H13v8h-3v-8H8v-3h2V9a4 4 0 0 1 4-4h2v3z"/></svg>`,
tiktok: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19.6 5.4a4.8 4.8 0 0 1-4.8-4.8h-3v14.7a2 2 0 1 1-2-2l.1-3a5 5 0 1 0 4.9 5V8.4a8 8 0 0 0 4.8 1.6V6.7a4.8 4.8 0 0 1-0-.2l0 0 .1.9z" fill="#000"/><path d="M18.6 4.4a4.8 4.8 0 0 1-4.8-4.8h-3v14.7a2 2 0 1 1-2-2l.1-3a5 5 0 1 0 4.9 5V7.4a8 8 0 0 0 4.8 1.6V5.7" fill="none" stroke="#69C9D0" stroke-width="1.5"/></svg>`,
tiktok: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19.6 5.4a4.8 4.8 0 0 1-4.8-4.8h-3v14.7a2 2 0 1 1-2-2l.1-3a5 5 0 1 0 4.9 5V8.4a8 8 0 0 0 4.8 1.6V6.7a4.8 4.8 0 0 1-0-.2l0 0 .1.9z" fill="currentColor"/><path d="M18.6 4.4a4.8 4.8 0 0 1-4.8-4.8h-3v14.7a2 2 0 1 1-2-2l.1-3a5 5 0 1 0 4.9 5V7.4a8 8 0 0 0 4.8 1.6V5.7" fill="none" stroke="#69C9D0" stroke-width="1.5"/></svg>`,
reddit: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="#FF4500"/><path fill="#fff" d="M20 12a2 2 0 0 0-2-2 2 2 0 0 0-1.3.5c-1.3-.9-3-.9-4.6-.9l.8-3.7 2.6.5a1.4 1.4 0 1 0 1.4-1.3 1.4 1.4 0 0 0-1.3.8l-2.9-.5a.3.3 0 0 0-.4.3l-.9 4.1c-1.6 0-3.1.1-4.3.9A2 2 0 0 0 4 12a2 2 0 0 0 1 1.7 3.3 3.3 0 0 0 0 .5c0 2.6 3 4.8 6.8 4.8s6.8-2.1 6.8-4.8a3.3 3.3 0 0 0 0-.5A2 2 0 0 0 20 12zm-13.6 1a1.1 1.1 0 1 1 1.1 1.1A1.1 1.1 0 0 1 6.4 13zm6.2 3.1a3.5 3.5 0 0 1-2.3.7 3.5 3.5 0 0 1-2.3-.7.3.3 0 0 1 .4-.4 3 3 0 0 0 1.9.5 3 3 0 0 0 1.9-.5.3.3 0 0 1 .4.4zm-.3-2a1.1 1.1 0 1 1 1.1-1.1A1.1 1.1 0 0 1 12.3 14.1z"/></svg>`,
snapchat: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><rect width="24" height="24" rx="4" fill="#FFFC00"/><path d="M12 3.5c-2.4 0-4.4 2-4.4 4.4v1.3l-.8.1c-.3 0-.5.2-.5.5s.3.5.6.6c.3.1.5.3.5.8 0 .3-.1.5-.3.7-.6.8-1.5 1.3-2.2 1.4-.1.7.7 1 1.7 1.2.1.6.3.8.8.8.6 0 1.1.4 2.7.4 1.5 0 2.1-.4 2.7-.4.5 0 .7-.2.8-.8 1-.2 1.8-.5 1.7-1.2-.7-.1-1.6-.6-2.2-1.4-.2-.2-.3-.4-.3-.7 0-.5.2-.7.5-.8.3-.1.6-.3.6-.6s-.2-.5-.5-.5l-.8-.1V7.9C16.4 5.5 14.4 3.5 12 3.5z"/></svg>`,
local: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="#666" stroke-width="1.5" stroke-linejoin="round" d="M4 4h7l2 2h7v14H4z"/></svg>`,
web: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="none" stroke="#555" stroke-width="1.5"/><ellipse cx="12" cy="12" rx="4" ry="10" fill="none" stroke="#555" stroke-width="1.5"/><line x1="2" y1="9" x2="22" y2="9" stroke="#555" stroke-width="1.5"/><line x1="2" y1="15" x2="22" y2="15" stroke="#555" stroke-width="1.5"/></svg>`,
other: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="none" stroke="#999" stroke-width="1.5"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#999">?</text></svg>`,
local: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" d="M4 4h7l2 2h7v14H4z"/></svg>`,
web: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="1.5"/><ellipse cx="12" cy="12" rx="4" ry="10" fill="none" stroke="currentColor" stroke-width="1.5"/><line x1="2" y1="9" x2="22" y2="9" stroke="currentColor" stroke-width="1.5"/><line x1="2" y1="15" x2="22" y2="15" stroke="currentColor" stroke-width="1.5"/></svg>`,
other: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="1.5"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="currentColor">?</text></svg>`,
};
export function sourceIconSvg(kind) {