mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
feat: PUT /summary endpoint for agent-written and hand-edited summaries
Adds PUT /api/archives/:id/entries/:uid/summary so agents (via the MCP) and humans (via the web UI) can write or edit entry summaries without going through a server-side LLM provider. Core (archivr-core) - summarizer.rs: EXTERNAL_SUMMARY_KINDS, external_summary_text, normalize_external_model — full validation (trim, dedupe+lowercase tags, control-char checks, per-field length limits) + 13 unit tests. - database.rs: extract new_summary_uid(); add insert_completed_entry_summary — single-row INSERT with status='completed', prompt_version='external', input_sha256='external', all timestamps set to now. Server (archivr-server) - routes.rs: ExternalSummaryBody, put_entry_summary_handler. Checks: role (USER), entry visibility (hidden→404), kind in [agent|manual], model validation, text validation, manual-requires-existing-summary (409). Returns 201 + the new EntrySummaryRecord. Route registered alongside existing GET+POST. - entry_access.rs: PUT /summary added to the hidden-entry gate test. - Three new tokio tests: agent creates and becomes latest, manual requires existing summary, body and role validation. Frontend - api.js: saveEntrySummary (PUT, kind:'manual'). - ContextRail.jsx: SUMMARY_SOURCE_LABEL (agent/manual labels), three new state vars, handleSaveSummary (scoped to selected entry), edit form (TL;DR/summary/tags + Save/Cancel), provider controls hidden while editing. - styles.css: rail-summary-edit-btn, rail-summary-editor and sub-classes. Companion MCP PR: thegeneralist01/archivr-mcp#<TBD>
This commit is contained in:
parent
1c8abddf93
commit
0aeb1a9580
8 changed files with 720 additions and 8 deletions
|
|
@ -1960,6 +1960,10 @@ pub fn entry_source_info(conn: &Connection, entry_uid: &str) -> Result<Option<En
|
|||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
fn new_summary_uid() -> String {
|
||||
format!("sum_{}", &Uuid::new_v4().simple().to_string()[..10])
|
||||
}
|
||||
|
||||
/// Creates a fresh pending summary attempt for one cache key.
|
||||
///
|
||||
/// Attempts are intentionally not unique by cache key: a forced regeneration
|
||||
|
|
@ -1972,7 +1976,7 @@ pub fn upsert_pending_entry_summary(
|
|||
prompt_version: &str,
|
||||
input_sha256: &str,
|
||||
) -> Result<String> {
|
||||
let summary_uid = format!("sum_{}", &Uuid::new_v4().simple().to_string()[..10]);
|
||||
let summary_uid = new_summary_uid();
|
||||
let now = now_timestamp();
|
||||
let model = provider_model.unwrap_or("");
|
||||
conn.execute(
|
||||
|
|
@ -2012,6 +2016,41 @@ pub fn update_entry_summary_completed(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Inserts an already-completed summary written outside the provider pipeline
|
||||
/// (an agent via the API, or a hand edit). Returns the new `summary_uid`.
|
||||
pub fn insert_completed_entry_summary(
|
||||
conn: &Connection,
|
||||
entry_id: i64,
|
||||
provider_kind: &str,
|
||||
model: Option<&str>,
|
||||
prompt_version: &str,
|
||||
input_sha256: &str,
|
||||
summary_text: &str,
|
||||
) -> Result<String> {
|
||||
let summary_uid = new_summary_uid();
|
||||
let now = now_timestamp();
|
||||
conn.execute(
|
||||
"INSERT INTO entry_summaries
|
||||
(summary_uid, entry_id, provider_kind, provider_model, prompt_version,
|
||||
input_sha256, status, summary_text, resolved_model, error_text,
|
||||
created_at, updated_at, completed_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'completed', ?7, ?8, NULL, ?9, ?9, ?9)",
|
||||
rusqlite::params![
|
||||
summary_uid,
|
||||
entry_id,
|
||||
provider_kind,
|
||||
model.unwrap_or(""),
|
||||
prompt_version,
|
||||
input_sha256,
|
||||
summary_text,
|
||||
model,
|
||||
now
|
||||
],
|
||||
)?;
|
||||
Ok(summary_uid)
|
||||
}
|
||||
|
||||
|
||||
/// Moves a summary row through `running` → `completed` / `failed`.
|
||||
/// `completed_at` is stamped only on the terminal `completed` transition.
|
||||
pub fn update_entry_summary_status(
|
||||
|
|
|
|||
|
|
@ -1270,6 +1270,81 @@ pub fn normalize_summary_json(raw: &str) -> String {
|
|||
.to_string()
|
||||
}
|
||||
|
||||
// ── External (agent / hand-edited) summary constants ────────────────────────
|
||||
|
||||
pub const EXTERNAL_SUMMARY_KINDS: [&str; 2] = ["agent", "manual"];
|
||||
pub const EXTERNAL_SUMMARY_PROMPT_VERSION: &str = "external";
|
||||
pub const EXTERNAL_SUMMARY_INPUT_SHA256: &str = "external";
|
||||
pub const MAX_EXTERNAL_TLDR_CHARS: usize = 300;
|
||||
pub const MAX_EXTERNAL_SUMMARY_CHARS: usize = 20_000;
|
||||
pub const MAX_EXTERNAL_SUMMARY_TAGS: usize = 10;
|
||||
pub const MAX_EXTERNAL_TAG_CHARS: usize = 50;
|
||||
pub const MAX_EXTERNAL_MODEL_CHARS: usize = 100;
|
||||
|
||||
/// Validates and normalizes a caller-written summary into the persisted
|
||||
/// `{"tldr","summary","tags"}` JSON (same shape as provider output).
|
||||
///
|
||||
/// Counts Unicode scalar values (`.chars().count()`), runs every check on the
|
||||
/// trimmed value, normalises tags to lowercase, and dedupes in first-seen
|
||||
/// order.
|
||||
pub fn external_summary_text(tldr: &str, summary: &str, tags: &[String]) -> Result<String> {
|
||||
// tldr
|
||||
let t = tldr.trim();
|
||||
if t.chars().any(|c| c.is_control()) {
|
||||
bail!("tldr must be a single line without control characters");
|
||||
}
|
||||
if t.chars().count() > MAX_EXTERNAL_TLDR_CHARS {
|
||||
bail!("tldr is longer than 300 characters");
|
||||
}
|
||||
|
||||
// summary
|
||||
let s = summary.trim();
|
||||
if s.is_empty() {
|
||||
bail!("summary must not be empty");
|
||||
}
|
||||
if s.chars().any(|c| c.is_control() && c != '\n' && c != '\r' && c != '\t') {
|
||||
bail!("summary contains control characters");
|
||||
}
|
||||
if s.chars().count() > MAX_EXTERNAL_SUMMARY_CHARS {
|
||||
bail!("summary is longer than 20000 characters");
|
||||
}
|
||||
|
||||
// tags: trim, lowercase, dedupe, validate
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for raw in tags {
|
||||
let tag = raw.trim().to_lowercase();
|
||||
if tag.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if tag.chars().any(|c| c.is_control()) || tag.chars().count() > MAX_EXTERNAL_TAG_CHARS {
|
||||
bail!("tags must be 1-50 characters without control characters");
|
||||
}
|
||||
if seen.insert(tag.clone()) {
|
||||
out.push(tag);
|
||||
}
|
||||
}
|
||||
if out.len() > MAX_EXTERNAL_SUMMARY_TAGS {
|
||||
bail!("at most 10 tags are allowed");
|
||||
}
|
||||
|
||||
Ok(serde_json::json!({"tldr": t, "summary": s, "tags": out}).to_string())
|
||||
}
|
||||
|
||||
/// Trims a self-reported model label. Returns `None` when absent or empty.
|
||||
pub fn normalize_external_model(model: Option<&str>) -> Result<Option<String>> {
|
||||
let Some(raw) = model else { return Ok(None) };
|
||||
let m = raw.trim();
|
||||
if m.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if m.chars().any(|c| c.is_control()) || m.chars().count() > MAX_EXTERNAL_MODEL_CHARS {
|
||||
bail!("model is longer than 100 characters or contains control characters");
|
||||
}
|
||||
Ok(Some(m.to_string()))
|
||||
}
|
||||
|
||||
|
||||
/// Full manual summarization pass for one entry, persisting the result.
|
||||
///
|
||||
/// Owns the whole row lifecycle (`pending` → `running` → `completed`/`failed`)
|
||||
|
|
@ -2766,4 +2841,115 @@ mod tests {
|
|||
);
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
// ── external_summary_text / normalize_external_model tests ──────────────
|
||||
|
||||
#[test]
|
||||
fn external_summary_tag_normalization() {
|
||||
let tags: Vec<String> = vec![
|
||||
" Rust ".to_string(),
|
||||
"rust".to_string(),
|
||||
"".to_string(),
|
||||
"CLI".to_string(),
|
||||
];
|
||||
let json_str = external_summary_text("T", "Some summary.", &tags).unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
|
||||
assert_eq!(v["tags"], serde_json::json!(["rust", "cli"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_empty_tldr_is_accepted() {
|
||||
let result = external_summary_text("", "Some summary.", &[]);
|
||||
assert!(result.is_ok(), "empty tldr should be accepted: {result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_tldr_control_char_rejected() {
|
||||
let err = external_summary_text("line1\nline2", "S.", &[]).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "tldr must be a single line without control characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_tldr_too_long_rejected() {
|
||||
let long = "x".repeat(301);
|
||||
let err = external_summary_text(&long, "S.", &[]).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "tldr is longer than 300 characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_empty_summary_rejected() {
|
||||
let err = external_summary_text("T", " ", &[]).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "summary must not be empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_control_char_in_summary_rejected() {
|
||||
let s = "hello\x01world";
|
||||
let err = external_summary_text("T", s, &[]).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "summary contains control characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_summary_too_long_rejected() {
|
||||
let long = "x".repeat(20_001);
|
||||
let err = external_summary_text("T", &long, &[]).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "summary is longer than 20000 characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_tag_control_char_rejected() {
|
||||
let tags = vec!["bad\x01tag".to_string()];
|
||||
let err = external_summary_text("T", "S.", &tags).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "tags must be 1-50 characters without control characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_tag_too_long_rejected() {
|
||||
let tags = vec!["x".repeat(51)];
|
||||
let err = external_summary_text("T", "S.", &tags).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "tags must be 1-50 characters without control characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_too_many_tags_rejected() {
|
||||
let tags: Vec<String> = (0..11).map(|i| format!("tag{i}")).collect();
|
||||
let err = external_summary_text("T", "S.", &tags).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "at most 10 tags are allowed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_summary_output_has_exactly_three_keys() {
|
||||
let json_str = external_summary_text("TL;DR", "A full summary.", &["rust".to_string()])
|
||||
.unwrap();
|
||||
let v: serde_json::Map<String, serde_json::Value> =
|
||||
serde_json::from_str(&json_str).unwrap();
|
||||
assert_eq!(v.len(), 3);
|
||||
assert!(v.contains_key("tldr"));
|
||||
assert!(v.contains_key("summary"));
|
||||
assert!(v.contains_key("tags"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_external_model_trims_and_returns_none_for_empty() {
|
||||
assert_eq!(normalize_external_model(None).unwrap(), None);
|
||||
assert_eq!(normalize_external_model(Some("")).unwrap(), None);
|
||||
assert_eq!(normalize_external_model(Some(" ")).unwrap(), None);
|
||||
assert_eq!(
|
||||
normalize_external_model(Some(" claude-opus-4-5 ")).unwrap(),
|
||||
Some("claude-opus-4-5".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_external_model_control_char_rejected() {
|
||||
let err = normalize_external_model(Some("bad\x01model")).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "model is longer than 100 characters or contains control characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_external_model_too_long_rejected() {
|
||||
let long = "x".repeat(101);
|
||||
let err = normalize_external_model(Some(&long)).unwrap_err();
|
||||
assert_eq!(format!("{err}"), "model is longer than 100 characters or contains control characters");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -125,6 +125,12 @@ async fn hidden_entry_is_not_found_on_every_by_uid_endpoint() {
|
|||
("DELETE", "", None, StatusCode::NO_CONTENT),
|
||||
("POST", "/tags", Some(json!({"tag_path": "/secret"})), StatusCode::CREATED),
|
||||
("POST", "/rearchive", None, StatusCode::ACCEPTED),
|
||||
(
|
||||
"PUT",
|
||||
"/summary",
|
||||
Some(json!({"kind": "agent", "summary": "x"})),
|
||||
StatusCode::CREATED,
|
||||
),
|
||||
]);
|
||||
for (method, suffix, body, _) in &cases {
|
||||
let uri = entry_path(hidden, suffix);
|
||||
|
|
@ -149,6 +155,10 @@ async fn hidden_entry_is_not_found_on_every_by_uid_endpoint() {
|
|||
.query_row("SELECT COUNT(*) FROM capture_jobs", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(jobs, 2, "rearchive of a hidden entry must not create a job");
|
||||
let summaries: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(summaries, 0, "PUT summary on hidden entry must not create a row");
|
||||
|
||||
// The tag-removal route is gated too (the tag need not exist for the gate to answer).
|
||||
let (status, json) = send_json(
|
||||
|
|
|
|||
|
|
@ -291,7 +291,7 @@ pub fn app_with_state(state: AppState) -> Router {
|
|||
)
|
||||
.route(
|
||||
"/api/archives/:archive_id/entries/:entry_uid/summary",
|
||||
get(entry_summary_handler).post(request_entry_summary_handler),
|
||||
get(entry_summary_handler).post(request_entry_summary_handler).put(put_entry_summary_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/summary/transcription-engines",
|
||||
|
|
@ -845,6 +845,68 @@ fn summary_failure_error_text(error: &anyhow::Error) -> String {
|
|||
}
|
||||
}
|
||||
|
||||
/// `PUT /api/archives/:id/entries/:uid/summary`
|
||||
///
|
||||
/// Inserts a new completed summary row written by an agent (`kind:"agent"`)
|
||||
/// or by a human editing an existing summary (`kind:"manual"`).
|
||||
///
|
||||
/// The newest completed row is displayed; earlier rows are retained. A
|
||||
/// provider attempt running concurrently will supersede this row when it
|
||||
/// completes — that is the existing regeneration semantics.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct ExternalSummaryBody {
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
tldr: String,
|
||||
summary: String,
|
||||
#[serde(default)]
|
||||
tags: Vec<String>,
|
||||
#[serde(default)]
|
||||
model: Option<String>,
|
||||
}
|
||||
|
||||
async fn put_entry_summary_handler(
|
||||
State(state): State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
Path((archive_id, entry_uid)): Path<(String, String)>,
|
||||
Json(body): Json<ExternalSummaryBody>,
|
||||
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
|
||||
auth_user.require_role(ROLE_USER)?;
|
||||
let mounted = mounted_archive(&state, &archive_id)?;
|
||||
let conn = database::open_or_initialize(&mounted.archive_path)?;
|
||||
ensure_entry_visible(&conn, &auth_user, &entry_uid)?;
|
||||
let entry_id = database::entry_id_for_uid(&conn, &entry_uid)?
|
||||
.ok_or(ApiError::not_found("entry not found"))?;
|
||||
if !summarizer::EXTERNAL_SUMMARY_KINDS.contains(&body.kind.as_str()) {
|
||||
return Err(ApiError::bad_request("kind must be 'agent' or 'manual'"));
|
||||
}
|
||||
let model = summarizer::normalize_external_model(body.model.as_deref())
|
||||
.map_err(|e| ApiError::bad_request(&format!("{e:#}")))?;
|
||||
if body.kind == "manual" && model.is_some() {
|
||||
return Err(ApiError::bad_request("model is only accepted for kind 'agent'"));
|
||||
}
|
||||
let text = summarizer::external_summary_text(&body.tldr, &body.summary, &body.tags)
|
||||
.map_err(|e| ApiError::bad_request(&format!("{e:#}")))?;
|
||||
if body.kind == "manual"
|
||||
&& database::latest_completed_entry_summary(&conn, entry_id)?.is_none()
|
||||
{
|
||||
return Err(ApiError::conflict("no summary to edit"));
|
||||
}
|
||||
let summary_uid = database::insert_completed_entry_summary(
|
||||
&conn,
|
||||
entry_id,
|
||||
&body.kind,
|
||||
model.as_deref(),
|
||||
summarizer::EXTERNAL_SUMMARY_PROMPT_VERSION,
|
||||
summarizer::EXTERNAL_SUMMARY_INPUT_SHA256,
|
||||
&text,
|
||||
)?;
|
||||
let record = database::get_entry_summary_by_uid(&conn, &summary_uid)?
|
||||
.ok_or_else(|| anyhow::anyhow!("inserted summary not found"))?;
|
||||
Ok((StatusCode::CREATED, Json(serde_json::to_value(record)?)))
|
||||
}
|
||||
|
||||
|
||||
/// `GET /api/summary/transcription-engines`
|
||||
///
|
||||
/// Local transcription engines that are enabled (`ARCHIVR_TRANSCRIBE_ENGINES`)
|
||||
|
|
@ -5172,6 +5234,261 @@ mod tests {
|
|||
assert_ne!(input_hashes[0], input_hashes[1]);
|
||||
}
|
||||
|
||||
async fn put_summary(
|
||||
registry: ServerRegistry,
|
||||
auth_path: std::path::PathBuf,
|
||||
entry_uid: &str,
|
||||
cookie: Option<&str>,
|
||||
token: Option<&str>,
|
||||
payload: serde_json::Value,
|
||||
) -> axum::response::Response {
|
||||
let mut builder = Request::builder()
|
||||
.method("PUT")
|
||||
.uri(format!("/api/archives/test/entries/{entry_uid}/summary"))
|
||||
.header("content-type", "application/json");
|
||||
if let Some(c) = cookie {
|
||||
builder = builder.header("cookie", c);
|
||||
}
|
||||
if let Some(t) = token {
|
||||
builder = builder.header("authorization", format!("Bearer {t}"));
|
||||
}
|
||||
app(registry, auth_path)
|
||||
.oneshot(builder.body(json_body(&payload)).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_agent_summary_creates_completed_row_that_becomes_latest() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (registry, archive_path, auth_path) = make_test_registry(&dir);
|
||||
let entry = make_test_entry(&archive_path);
|
||||
let session = make_test_session(&auth_path);
|
||||
|
||||
// Seed a pre-existing codex_cli completed row.
|
||||
let conn = database::open_or_initialize(&archive_path).unwrap();
|
||||
let old_uid = database::upsert_pending_entry_summary(
|
||||
&conn,
|
||||
entry.id,
|
||||
"codex_cli",
|
||||
None,
|
||||
summarizer::PROMPT_VERSION,
|
||||
"prior-sha",
|
||||
)
|
||||
.unwrap();
|
||||
database::update_entry_summary_status(&conn, &old_uid, "completed", Some("old summary"), None)
|
||||
.unwrap();
|
||||
drop(conn);
|
||||
|
||||
let resp = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({
|
||||
"kind": "agent",
|
||||
"tldr": "T",
|
||||
"summary": " S ",
|
||||
"tags": ["Rust", "rust", " cli "],
|
||||
"model": " claude-x "
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
let body = body_json(resp).await;
|
||||
assert_eq!(body["provider_kind"], "agent");
|
||||
assert_eq!(body["provider_model"], "claude-x");
|
||||
assert_eq!(body["resolved_model"], "claude-x");
|
||||
assert_eq!(body["prompt_version"], "external");
|
||||
assert_eq!(body["status"], "completed");
|
||||
let text: serde_json::Value = serde_json::from_str(body["summary_text"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(text, serde_json::json!({"tldr": "T", "summary": "S", "tags": ["rust", "cli"]}));
|
||||
|
||||
// GET /summary now returns this uid as summary and attempt null.
|
||||
let new_uid = body["summary_uid"].as_str().unwrap().to_string();
|
||||
let get_resp = app(registry.clone(), auth_path.clone())
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid))
|
||||
.header("cookie", &session)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let get_body = body_json(get_resp).await;
|
||||
assert_eq!(get_body["summary"]["summary_uid"], new_uid);
|
||||
assert!(get_body["attempt"].is_null());
|
||||
|
||||
// Both rows retained.
|
||||
let conn = database::open_or_initialize(&archive_path).unwrap();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_manual_summary_requires_existing_summary() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (registry, archive_path, auth_path) = make_test_registry(&dir);
|
||||
let entry = make_test_entry(&archive_path);
|
||||
let session = make_test_session(&auth_path);
|
||||
|
||||
// 409 on a fresh entry.
|
||||
let resp = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({"kind": "manual", "summary": "S"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), StatusCode::CONFLICT);
|
||||
assert_eq!(body_json(resp).await["error"], "no summary to edit");
|
||||
|
||||
// No row was created.
|
||||
let conn = database::open_or_initialize(&archive_path).unwrap();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
drop(conn);
|
||||
|
||||
// After an agent PUT the manual PUT succeeds.
|
||||
put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({"kind": "agent", "summary": "Agent S", "tldr": ""}),
|
||||
)
|
||||
.await;
|
||||
let resp2 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({"kind": "manual", "summary": "S"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp2.status(), StatusCode::CREATED);
|
||||
let b2 = body_json(resp2).await;
|
||||
assert_eq!(b2["provider_kind"], "manual");
|
||||
assert!(b2["resolved_model"].is_null());
|
||||
|
||||
// model with kind=manual → 400.
|
||||
let resp3 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({"kind": "manual", "summary": "S", "model": "m"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp3.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(body_json(resp3).await["error"], "model is only accepted for kind 'agent'");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_summary_validates_body_and_role() {
|
||||
use crate::test_support::{guest_session, make_api_token};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (registry, archive_path, auth_path) = make_test_registry(&dir);
|
||||
let entry = make_test_entry(&archive_path);
|
||||
let session = make_test_session(&auth_path);
|
||||
|
||||
// Bad kind.
|
||||
let r1 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({"kind": "anthropic_http", "summary": "S"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r1.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(body_json(r1).await["error"], "kind must be 'agent' or 'manual'");
|
||||
|
||||
// Empty summary.
|
||||
let r2 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({"kind": "agent", "summary": ""}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r2.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(body_json(r2).await["error"], "summary must not be empty");
|
||||
|
||||
// Too many tags.
|
||||
let tags: Vec<String> = (0..11_u8).map(|i| format!("tag{i}")).collect();
|
||||
let r3 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&session),
|
||||
None,
|
||||
serde_json::json!({"kind": "agent", "summary": "S", "tags": tags}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r3.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(body_json(r3).await["error"], "at most 10 tags are allowed");
|
||||
|
||||
// Guest → 403.
|
||||
let guest = guest_session(&auth_path);
|
||||
let r4 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
Some(&guest),
|
||||
None,
|
||||
serde_json::json!({"kind": "agent", "summary": "S"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r4.status(), StatusCode::FORBIDDEN);
|
||||
|
||||
// No cookie → 401.
|
||||
let r5 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
None,
|
||||
None,
|
||||
serde_json::json!({"kind": "agent", "summary": "S"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r5.status(), StatusCode::UNAUTHORIZED);
|
||||
|
||||
// Read-scope token → 403.
|
||||
let read_token = make_api_token(&auth_path, "testowner", None, "read");
|
||||
let r6 = put_summary(
|
||||
registry.clone(),
|
||||
auth_path.clone(),
|
||||
&entry.entry_uid,
|
||||
None,
|
||||
Some(&read_token),
|
||||
serde_json::json!({"kind": "agent", "summary": "S"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r6.status(), StatusCode::FORBIDDEN);
|
||||
|
||||
// No rows created by any of the above.
|
||||
let conn = database::open_or_initialize(&archive_path).unwrap();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn archives_endpoint_lists_mounted_archives() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@
|
|||
<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-B0u5xO9w.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-nzHmFByy.css">
|
||||
<script type="module" crossorigin src="/assets/index-CSEU9J6M.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-D-bTRI4I.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
|
|
|||
|
|
@ -77,6 +77,28 @@ export async function requestEntrySummary(archiveId, entryUid, { provider, force
|
|||
return resp.json();
|
||||
}
|
||||
|
||||
// Saves a hand-edited summary as a new completed row (kind "manual"). The
|
||||
// server refuses (409) when the entry has no summary yet: edit-only by design.
|
||||
export async function saveEntrySummary(archiveId, entryUid, { tldr, summary, tags, signal } = {}) {
|
||||
const resp = await fetch(
|
||||
`/api/archives/${archiveId}/entries/${entryUid}/summary`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ kind: 'manual', tldr, summary, tags }),
|
||||
signal,
|
||||
}
|
||||
);
|
||||
if (!resp.ok) {
|
||||
const detail = await resp.text();
|
||||
let message = detail.trim();
|
||||
try { message = JSON.parse(detail).error || message } catch { /* non-JSON body */ }
|
||||
throw new Error(message || `Summary save failed (${resp.status})`);
|
||||
}
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
|
||||
// Text artifacts are served by the same entry-artifact endpoint as previews.
|
||||
// Keep credentials explicit because this helper is also used by public/private
|
||||
// archive views, and preserve the previous concise HTTP error contract.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useState, useEffect, useLayoutEffect, useRef } from 'react'
|
||||
import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, fetchTranscriptionEngines } from '../api'
|
||||
import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, saveEntrySummary, fetchTranscriptionEngines } from '../api'
|
||||
import ExportDialog from './ExportDialog'
|
||||
import { formatTimestamp, formatBytes, valueText, sourceIconSvg, displayPath } from '../utils'
|
||||
|
||||
|
|
@ -14,6 +14,7 @@ const SUMMARY_PROVIDERS = [
|
|||
{ value: 'codex_cli', label: 'Codex CLI' },
|
||||
]
|
||||
const PROVIDER_LABEL = Object.fromEntries(SUMMARY_PROVIDERS.map(p => [p.value, p.label]))
|
||||
const SUMMARY_SOURCE_LABEL = { ...PROVIDER_LABEL, agent: 'Agent', manual: 'Edited by hand' }
|
||||
const SUMMARY_PROVIDER_KEY = 'archivr:summary:provider'
|
||||
const SUMMARY_TRANSCRIBE_ENGINE_KEY = 'archivr:summary:transcribe-engine'
|
||||
const SUMMARY_POLL_MS = 1500
|
||||
|
|
@ -103,6 +104,9 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
return sessionStorage.getItem(SUMMARY_TRANSCRIBE_ENGINE_KEY) || ''
|
||||
} catch { return '' }
|
||||
})
|
||||
const [editingSummary, setEditingSummary] = useState(false)
|
||||
const [summaryDraft, setSummaryDraft] = useState({ tldr: '', summary: '', tags: '' })
|
||||
const [summarySaving, setSummarySaving] = useState(false)
|
||||
const summaryPollRef = useRef(null)
|
||||
const summaryPollAbortRef = useRef(null)
|
||||
const summaryGenerateAbortRef = useRef(null)
|
||||
|
|
@ -206,6 +210,8 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
setSummaryError('')
|
||||
setSummaryBusy(false)
|
||||
setIncludeSummaryImages(false)
|
||||
setEditingSummary(false)
|
||||
setSummarySaving(false)
|
||||
}, [archiveId, selectedEntry?.entry_uid, detail?.summary?.entry_uid])
|
||||
|
||||
// Poll only while a replacement attempt is non-terminal. Anchoring the effect
|
||||
|
|
@ -323,6 +329,34 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
}
|
||||
}
|
||||
|
||||
async function handleSaveSummary() {
|
||||
if (!archiveId || !detail?.summary?.entry_uid || summarySaving) return
|
||||
const entryUid = detail.summary.entry_uid
|
||||
const selectionKey = `${archiveId}:${entryUid}`
|
||||
if (summarySelectionRef.current !== selectionKey) return
|
||||
setSummarySaving(true)
|
||||
setSummaryError('')
|
||||
try {
|
||||
const tags = summaryDraft.tags.split(',').map(t => t.trim()).filter(Boolean)
|
||||
const res = await saveEntrySummary(archiveId, entryUid, {
|
||||
tldr: summaryDraft.tldr,
|
||||
summary: summaryDraft.summary,
|
||||
tags,
|
||||
})
|
||||
if (summarySelectionRef.current !== selectionKey) return
|
||||
setSummary(res)
|
||||
setSummaryAttempt(null)
|
||||
setEditingSummary(false)
|
||||
onDetailRefresh?.()
|
||||
} catch (e) {
|
||||
if (summarySelectionRef.current !== selectionKey) return
|
||||
setSummaryError(e.message || 'Summary save failed')
|
||||
} finally {
|
||||
setSummarySaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function handleProviderChange(value) {
|
||||
setSummaryProvider(value)
|
||||
if (value === 'claude_cli') setIncludeSummaryImages(false)
|
||||
|
|
@ -810,15 +844,77 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
</div>
|
||||
)}
|
||||
<p className="rail-summary-provider">
|
||||
{PROVIDER_LABEL[summary.provider_kind] || summary.provider_kind}
|
||||
{SUMMARY_SOURCE_LABEL[summary.provider_kind] || summary.provider_kind}
|
||||
{summary.resolved_model || summary.provider_model
|
||||
? ` \u00b7 ${summary.resolved_model || summary.provider_model}`
|
||||
: ''}
|
||||
</p>
|
||||
{!isPublicSession && !running && !editingSummary && (
|
||||
<button
|
||||
className="rail-summary-edit-btn"
|
||||
onClick={() => {
|
||||
setSummaryDraft({
|
||||
tldr: parsed.tldr || '',
|
||||
summary: parsed.summary || '',
|
||||
tags: parsed.tags.join(', '),
|
||||
})
|
||||
setEditingSummary(true)
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{running && (
|
||||
{editingSummary && (
|
||||
<div className="rail-summary-editor">
|
||||
<label className="rail-summary-editor__label">
|
||||
TL;DR
|
||||
<input
|
||||
className="rail-summary-editor__input"
|
||||
value={summaryDraft.tldr}
|
||||
maxLength={300}
|
||||
onChange={e => setSummaryDraft(d => ({ ...d, tldr: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="rail-summary-editor__label">
|
||||
Summary
|
||||
<textarea
|
||||
className="rail-summary-editor__textarea"
|
||||
rows={8}
|
||||
value={summaryDraft.summary}
|
||||
onChange={e => setSummaryDraft(d => ({ ...d, summary: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="rail-summary-editor__label">
|
||||
Tags (comma-separated)
|
||||
<input
|
||||
className="rail-summary-editor__input"
|
||||
value={summaryDraft.tags}
|
||||
onChange={e => setSummaryDraft(d => ({ ...d, tags: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<div className="rail-summary-editor__actions">
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
onClick={handleSaveSummary}
|
||||
disabled={summarySaving || !summaryDraft.summary.trim()}
|
||||
>
|
||||
{summarySaving ? '\u2026' : 'Save'}
|
||||
</button>
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
onClick={() => { setEditingSummary(false); setSummaryError('') }}
|
||||
disabled={summarySaving}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!editingSummary && running && (
|
||||
<p className="rail-summary-status">
|
||||
<span className="rail-summary-spinner" aria-hidden="true" />
|
||||
{'Generating\u2026'}
|
||||
|
|
@ -842,7 +938,7 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
</p>
|
||||
)}
|
||||
|
||||
{!isPublicSession && !running && (
|
||||
{!isPublicSession && !running && !editingSummary && (
|
||||
<div className="rail-summary-controls">
|
||||
<select
|
||||
className="rail-summary-select"
|
||||
|
|
|
|||
|
|
@ -3526,6 +3526,48 @@ body.has-audio-bar { padding-bottom: 56px; }
|
|||
.rail-summary-spinner { animation: none; }
|
||||
}
|
||||
.rail-summary-controls { display: flex; flex-direction: column; gap: 6px; }
|
||||
.rail-summary-edit-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
align-self: flex-start;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.rail-summary-edit-btn:hover { color: var(--ink); }
|
||||
.rail-summary-editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.rail-summary-editor__label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.rail-summary-editor__input,
|
||||
.rail-summary-editor__textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
padding: 5px 8px;
|
||||
color: var(--ink);
|
||||
background: var(--paper);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.rail-summary-editor__textarea { resize: vertical; }
|
||||
.rail-summary-editor__actions {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 6px;
|
||||
}
|
||||
.rail-summary-select {
|
||||
width: 100%;
|
||||
padding: 5px 8px;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue