Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Camera-to-Completed: save the case before marking a letter read; lists confirm only what changed
Lin (kwant bot)0355cf48b8d5
diff --git a/docs/camera-to-completed.md b/docs/camera-to-completed.mdindex de27af1e..91b32028 100644--- a/docs/camera-to-completed.md+++ b/docs/camera-to-completed.md@@ -82,8 +82,9 @@ Nothing is `confirmed` until the person confirms it. `PATCH /api/zombie/cases/:i- for a single field: `null` to clear it, `{}` to confirm it as it is (the value must still parse), or `{"value": "..."}` to set it(which also confirms it);-- for a list: the whole list, as `[{"value": "...", "done"?: bool}]`. An item whose value is unchanged keeps its quote, and `done`- applies to checklist items only.+- for a list: the whole list, as `[{"value": "...", "done"?: bool, "confirmed"?: true}]`. `done` applies to checklist items only.+ A new or changed item is confirmed. An item whose value is unchanged keeps its quote and its confirmed/uncertain state, so+ ticking one checklist item confirms nothing; send `"confirmed": true` on an item to confirm it as it is.Values are at most 500 characters and lists at most 20 items.diff --git a/src/db/documents.rs b/src/db/documents.rsindex 47c44f35..87722265 100644--- a/src/db/documents.rs+++ b/src/db/documents.rs@@ -186,3 +186,45 @@ impl Database {.rows_affected())}}++#[cfg(test)]+mod tests {+ use crate::db::Database;+ use crate::documents::extract;+ use chrono::Utc;++ #[tokio::test]+ async fn a_letter_is_marked_read_only_after_its_case_is_saved() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let now = Utc::now();+ db.zombie_put_case(&extract::new_case("c1", now)).await.unwrap();+ db.document_put_extraction(&extract::running_row("c1", &["a1".into()], now)).await.unwrap();+ let out = extract::Outcome {+ status: "read",+ method: Some("model_vision"),+ note: None,+ text: String::new(),+ fields: crate::documents::Fields {+ sender: Some(crate::documents::Field { value: "Northfield Water".into(), ..Default::default() }),+ ..Default::default()+ },+ read_by: Some("stub:test".into()),+ };++ // The case write fails: the letter must not look read with the old case+ sqlx::query("CREATE TRIGGER no_case_writes BEFORE UPDATE ON zombie_cases BEGIN SELECT RAISE(ABORT, 'test'); END")+ .execute(&db.pool)+ .await+ .unwrap();+ assert!(extract::save(&db, "c1", out.clone(), now).await.is_err());+ assert_eq!(db.document_extraction("c1").await.unwrap().unwrap().status, "running");++ sqlx::query("DROP TRIGGER no_case_writes").execute(&db.pool).await.unwrap();+ extract::save(&db, "c1", out, now).await.unwrap();+ assert_eq!(db.document_extraction("c1").await.unwrap().unwrap().status, "read");+ let c = db.zombie_case("c1").await.unwrap().unwrap();+ assert_eq!(c.title, "Letter from Northfield Water");+ assert!(c.draft.is_some());+ }+}diff --git a/src/documents/extract.rs b/src/documents/extract.rsindex aaf6a8fe..f39ed049 100644--- a/src/documents/extract.rs+++ b/src/documents/extract.rs@@ -252,10 +252,12 @@ pub async fn after_status_change(db: &Database, c: &CaseRow) -> Result<(), crate/// The person's corrections. Each key is optional:/// - `sender`, `request`, `reply_to`, `deadline`: `null` clears it, `{}` confirms it as it is,/// `{"value": "..."}` sets it (confirmed).-/// - `references`, `amounts`, `checklist`: the whole list, each `{"value": "...", "done"?: bool}`-/// (`done` for checklist items). An entry whose value was already there keeps its quote.+/// - `references`, `amounts`, `checklist`: the whole list, each+/// `{"value": "...", "done"?: bool, "confirmed"?: true}` (`done` for checklist items). An entry+/// whose value was already there keeps its quote, and keeps its confirmed/uncertain state unless+/// it is sent with `"confirmed": true`; a new or changed entry is confirmed.///-/// Every field the person touches is confirmed and no longer uncertain. A deadline must be+/// Every single field the person touches is confirmed and no longer uncertain. A deadline must be/// `YYYY-MM-DD`; an amount must parse (`GBP 142.60`, `£142.60`, `142,60 EUR`).pub fn patch(old: &Fields, body: &Value) -> Result<Fields, String> {let obj = body.as_object().ok_or("send a JSON object of fields")?;@@ -333,6 +335,11 @@ fn list(old: &[Field], v: &Value, key: &str, kind: Kind) -> Result<Vec<Field>, Slet value = item.get("value").and_then(Value::as_str).ok_or_else(|| format!("{key}: each entry needs a value"))?;let value = valid(value, key, kind)?;let before = old.iter().find(|o| o.value == value);+ let confirm = match item.get("confirmed") {+ None | Some(Value::Bool(false)) => false,+ Some(Value::Bool(true)) => true,+ Some(_) => return Err(format!("{key}: confirmed is true or false")),+ };let done = match (kind, item.get("done")) {(Kind::Checklist, Some(Value::Bool(b))) => Some(*b),(Kind::Checklist, None) => Some(before.and_then(|b| b.done).unwrap_or(false)),@@ -340,7 +347,13 @@ fn list(old: &[Field], v: &Value, key: &str, kind: Kind) -> Result<Vec<Field>, S(_, Some(_)) => return Err(format!("{key}: only checklist entries can be done")),(_, None) => None,};- Ok(Field { quote: before.map(|b| b.quote.clone()).unwrap_or_default(), value, uncertain: false, confirmed: true, done })+ // A new or changed entry, or one the person confirms, is confirmed; an unchanged one+ // (say, ticking another checklist item) keeps what it was+ let (uncertain, confirmed) = match before {+ Some(b) if !confirm => (b.uncertain, b.confirmed),+ _ => (false, true),+ };+ Ok(Field { quote: before.map(|b| b.quote.clone()).unwrap_or_default(), value, uncertain, confirmed, done })}).collect()}@@ -380,9 +393,16 @@ pub async fn run(state: crate::server::AppState, case_id: String, attachments: V}/// Stores `out` for `case_id` and brings the case up to date. A case deleted meanwhile stays gone.+///+/// The case and its reminders are written first and the extraction's status last: a poller that+/// sees the letter read always gets the updated case and its draft with it. If the case write+/// fails, the extraction stays `running` and the next start marks it interrupted.pub async fn save(db: &Database, case_id: &str, out: Outcome, now: DateTime<Utc>) -> Result<(), crate::db::DbError> {let Some(mut e) = db.document_extraction(case_id).await? else { return Ok(()) };let Some(mut c) = db.zombie_case(case_id).await? else { return Ok(()) };+ apply(&mut c, &out.fields, now);+ db.zombie_put_case(&c).await?;+ reschedule(db, &c, &out.fields, now).await?;e.status = out.status.into();e.method = out.method.map(str::to_string);e.note = out.note;@@ -391,9 +411,6 @@ pub async fn save(db: &Database, case_id: &str, out: Outcome, now: DateTime<Utc>e.read_by = out.read_by;e.updated_at = now;db.document_put_extraction(&e).await?;- apply(&mut c, &out.fields, now);- db.zombie_put_case(&c).await?;- reschedule(db, &c, &out.fields, now).await?;Ok(())}@@ -509,6 +526,32 @@ mod tests {assert_eq!(f.checklist[0].done, Some(true));}+ #[test]+ fn a_list_confirms_only_new_changed_or_confirmed_entries() {+ let mut old = fields();+ old.checklist = vec![+ Field { value: "Pay".into(), quote: "pay by".into(), uncertain: true, done: Some(false), ..Default::default() },+ Field { value: "Call".into(), done: Some(false), ..Default::default() },+ ];+ // Ticking one item: neither changes its confirmed/uncertain state+ let f = patch(&old, &json!({"checklist": [{"value": "Pay", "done": true}, {"value": "Call", "done": false}]})).unwrap();+ assert_eq!(f.checklist[0].done, Some(true));+ assert!(f.checklist[0].uncertain && !f.checklist[0].confirmed, "ticked, still uncertain");+ assert!(!f.checklist[1].uncertain && !f.checklist[1].confirmed, "untouched, still unconfirmed");+ assert_eq!(f.checklist[0].quote, "pay by");+ // A changed value and a new one are confirmed; the unchanged one isn't+ let f = patch(&old, &json!({"checklist": [{"value": "Pay"}, {"value": "Call back"}, {"value": "File it"}]})).unwrap();+ assert!(f.checklist[0].uncertain && !f.checklist[0].confirmed);+ assert!(f.checklist[1..].iter().all(|x| x.confirmed && !x.uncertain && x.quote.is_empty()));+ // Confirming as they are+ let f = patch(&old, &json!({"checklist": [{"value": "Pay", "confirmed": true}, {"value": "Call", "confirmed": true}]})).unwrap();+ assert!(f.checklist.iter().all(|x| x.confirmed && !x.uncertain && x.done == Some(false)));+ assert_eq!(f.checklist[0].quote, "pay by");+ let f = patch(&old, &json!({"amounts": [{"value": "GBP 142.60"}]})).unwrap();+ assert!(!f.amounts[0].confirmed, "an unchanged amount isn't confirmed by resending it");+ assert!(patch(&old, &json!({"amounts": [{"value": "GBP 142.60", "confirmed": "yes"}]})).is_err());+ }+#[test]fn the_case_takes_only_a_confirmed_deadline() {let now = Utc::now();diff --git a/tests/documents_test.rs b/tests/documents_test.rsindex 4767a78b..f8bdcfbc 100644--- a/tests/documents_test.rs+++ b/tests/documents_test.rs@@ -396,6 +396,7 @@ async fn a_text_pdf_and_a_photo_are_read_in_one_model_call() {assert_eq!(v["extraction"]["fields"]["deadline"]["confirmed"], true);assert_eq!(v["extraction"]["fields"]["checklist"].as_array().unwrap().len(), 1);assert_eq!(v["extraction"]["fields"]["checklist"][0]["done"], true);+ assert_eq!(v["extraction"]["fields"]["checklist"][0]["confirmed"], false, "ticking an item doesn't confirm it");assert_eq!(v["extraction"]["fields"]["checklist"][0]["quote"], "Tick the box and return this slip by post.", "an unchanged item keeps its quote");assert_eq!(v["case"]["deadline"].as_str().unwrap().get(..10), Some("2099-03-01"));let rem = v["reminders"].as_array().unwrap();