mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
fix(llm): saved provider per account, codex trust check, UI-configured OpenAI-compatible endpoint (#49)
This commit is contained in:
parent
ece485539b
commit
3a6dca66d2
12 changed files with 1105 additions and 70 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
"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",
|
||||
),
|
||||
api_key: required_env("ARCHIVR_OPENAI_API_KEY")?,
|
||||
model: env_or("ARCHIVR_OPENAI_MODEL", "gpt-4o-mini"),
|
||||
)
|
||||
};
|
||||
|
||||
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,11 +735,17 @@ 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") {
|
||||
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 out = match run_cli(&cfg.executable, &fb_refs, "", cfg.timeout_secs) {
|
||||
Ok(out) => out,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&out_path);
|
||||
format!(
|
||||
"codex `exec -` failed ({primary_err:#}); positional fallback failed{}",
|
||||
missing_binary_hint(cfg)
|
||||
)
|
||||
})?;
|
||||
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, ¬_found_err).contains("ARCHIVR_CODEX_CLI"));
|
||||
assert_eq!(codex::missing_binary_hint(&bare_cfg, &exit_err), "");
|
||||
assert_eq!(codex::missing_binary_hint(&explicit_cfg, ¬_found_err), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_rejects_images_before_spawning() {
|
||||
let (_temp, request) = image_request();
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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": {
|
||||
|
|
|
|||
|
|
@ -399,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),
|
||||
|
|
@ -604,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)]
|
||||
|
|
@ -676,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.
|
||||
|
|
@ -687,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(
|
||||
|
|
@ -1455,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(
|
||||
|
|
@ -1464,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"));
|
||||
|
|
@ -1472,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 || {
|
||||
|
|
@ -1494,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
|
||||
|
|
@ -1506,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(
|
||||
|
|
@ -1514,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();
|
||||
|
|
@ -2525,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;
|
||||
|
|
@ -2543,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),
|
||||
})))
|
||||
}
|
||||
|
|
@ -2594,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)
|
||||
}
|
||||
|
||||
|
|
@ -2624,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!({
|
||||
|
|
@ -2714,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
|
||||
|
|
@ -3222,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)]
|
||||
|
|
@ -3238,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(
|
||||
|
|
@ -4850,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();
|
||||
|
|
@ -9260,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();
|
||||
|
|
|
|||
|
|
@ -395,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 |
|
||||
|
|
|
|||
|
|
@ -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(() => {
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ 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'
|
||||
|
|
@ -136,6 +136,32 @@ 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
|
||||
|
|
@ -398,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 {
|
||||
|
|
@ -435,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) {
|
||||
|
|
@ -480,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>
|
||||
|
|
@ -492,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'}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue