Cotton code
601 lines · 30.6 KB · RustRaw
//! Recordings in Comms (owner, 23 Nov 2026; DECISIONS "Recordings", CONTRACT//! "Recordings"): a meeting in a room, a memo, an imported file or the notes//! taken on a call, listed in Calls with the calls and opened on one page.//! The engine is Meetings' (`phone::meetings_app`, one set of tables); this//! module answers what Comms draws, every word from the `chat` set's//! `app.recording.*`.//!//! ```text//! chat.recording      { id, charging? }                       → the page//! chat.recording.act  { id, act, … }                          → { page, said? }//! chat.recording.live { meeting, duration_ms, free_bytes?, paused? } → the recording screen's words//! ```use std::collections::HashSet;use serde_json::{json, Map, Value};use cotton_core::messages::app::lay;use cotton_core::records::page::{stamp_parts, DateWords};use cotton_tools::mcp::dispatch::Ctx;use super::meetings_app::{self as engine, chat_line, chat_say, int_of, str_of, MEETING};use crate::handle::CottonHandle;use crate::methods::MethodError;pub const METHODS: [&str; 3] = ["chat.recording", "chat.recording.act", "chat.recording.live"];/// Under this much free space the recording screen says how long is left.pub const SPACE_WARN_BYTES: i64 = 500 * 1024 * 1024;/// Under this, the recording stops and keeps what it has.pub const SPACE_STOP_BYTES: i64 = 50 * 1024 * 1024;/// What a minute of a recording takes on the disk at most (16 kHz WAV, the iPhone's; Android's AAC is a sixth of it).pub const BYTES_PER_MINUTE: i64 = 16_000 * 2 * 60;pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "chat.recording" => page(handle, request),        "chat.recording.act" => act(handle, request),        "chat.recording.live" => Ok(live(request)),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a recording method"))),    }}// ── the list: recordings with the calls ─────────────────────────────────────/// A recording as Calls lists it.#[derive(Debug, Clone)]pub(crate) struct Listed {    pub id: String,    pub started_at: String,    pub title: String,    pub line: String,    pub mark: String,    /// The call row whose notes these are.    pub on_call: Option<String>,}/// Every recording older than `after` (Calls' cursor), newest first. A copy/// that holds no recordings (an older kit) lists none.pub(crate) fn listed(ctx: &mut Ctx<'_>, after: Option<&(String, String)>) -> Result<Vec<Listed>, String> {    let Ok(rows) = engine::rows(ctx, MEETING, json!({})) else { return Ok(Vec::new()) };    let mut out: Vec<Listed> = rows        .into_iter()        .filter(|m| str_of(m, "status") != "recording" || str_of(m, "source") == "call")        .filter(|m| match after {            Some((at, id)) => (str_of(m, "started_at"), str_of(m, "id")) < (at.as_str(), id.as_str()),            None => true,        })        .map(|m| Listed {            id: str_of(&m, "id").to_string(),            started_at: str_of(&m, "started_at").to_string(),            title: title(&m),            line: chat_say("app.recording.line", &[("length", &length(int_of(&m, "duration_ms"))), ("state", &state_words(&m))]),            mark: mark_of(&m).to_string(),            on_call: Some(str_of(&m, "call").to_string()).filter(|c| !c.is_empty() && str_of(&m, "source") == "call"),        })        .collect();    out.sort_by(|a, b| b.started_at.cmp(&a.started_at).then(b.id.cmp(&a.id)));    Ok(out)}fn mark_of(meeting: &Map<String, Value>) -> &'static str {    match (str_of(meeting, "source"), str_of(meeting, "kind")) {        ("call", _) => "notes",        ("import", _) => "import",        (_, "memo") => "memo",        _ => "recording",    }}/// "12 min", "40 sec".pub(crate) fn length(ms: i64) -> String {    let seconds = (ms.max(0) + 500) / 1000;    if seconds < 60 {        chat_say("app.recording.length.seconds", &[("seconds", &seconds.to_string())])    } else {        chat_say("app.recording.length.minutes", &[("minutes", &((seconds + 30) / 60).to_string())])    }}fn state_words(meeting: &Map<String, Value>) -> String {    let state = match str_of(meeting, "status") {        "" => "waiting",        other => other,    };    chat_line(&format!("app.recording.state.{state}"))}/// A recording's title: his own, else a group call's notes by the group ("Notes on a call in Invented Family"), else/// the core's words for its kind, a call's with the people it was with.fn title(meeting: &Map<String, Value>) -> String {    let tracks: Vec<Value> = serde_json::from_str(str_of(meeting, "tracks")).unwrap_or_default();    let group = tracks.iter().find_map(|t| t["group"].as_str()).filter(|g| !g.trim().is_empty());    match group {        Some(group) if str_of(meeting, "title").trim().is_empty() && str_of(meeting, "source") == "call" => chat_say("app.recording.untitled.call_group", &[("group", group)]),        _ => engine::title_of(meeting, call_with(meeting).as_deref()),    }}/// Who a call's notes were taken with: the other tracks' names.fn call_with(meeting: &Map<String, Value>) -> Option<String> {    let tracks: Vec<Value> = serde_json::from_str(str_of(meeting, "tracks")).unwrap_or_default();    // Named as the call named them, else by their number (someone not among his people).    let names: Vec<String> = tracks.iter().filter(|t| t["member"] != "me").filter_map(|t| t["name"].as_str().or_else(|| t["number"].as_str()).map(str::to_string)).collect();    (!names.is_empty()).then(|| names.join(", "))}// ── where the words are made ────────────────────────────────────────────────/// The page's one line on where the words (and the summary) are being made.fn where_of(meeting: &Map<String, Value>, charging: bool) -> Value {    let languages = engine::chosen_languages(meeting);    let mac_only = str_of(meeting, "transcribe_on") == "mac" || languages.len() >= 2;    let (on, line) = match str_of(meeting, "status") {        "transcribing" => match str_of(meeting, "transcribing_on") {            "phone" => ("phone", "app.recording.where.phone"),            _ => ("mac", "app.recording.where.mac"),        },        "waiting" if mac_only => ("waiting", "app.recording.where.waiting_mac"),        "waiting" if str_of(meeting, "status_why") == "model" => ("waiting", "app.recording.where.waiting_model"),        "waiting" if !charging && int_of(meeting, "duration_ms") > engine::SHORT_MS => ("waiting", "app.recording.where.waiting_charge"),        "waiting" => ("waiting", "app.recording.where.phone"),        "ready" => match str_of(meeting, "transcribed_by").split(':').next().unwrap_or_default() {            "phone" => ("phone", "app.recording.where.phone"),            "mac" => ("mac", "app.recording.where.mac"),            _ => ("none", ""),        },        _ => ("none", ""),    };    if line.is_empty() {        return json!({ "on": on, "line": Value::Null });    }    json!({ "on": on, "line": chat_line(line) })}// ── the page ────────────────────────────────────────────────────────────────fn language_name(code: &str) -> String {    let said = chat_line(&format!("app.recording.language.names.{code}"));    if said.starts_with("app.") { code.to_string() } else { said }}fn joined(names: &[String]) -> String {    match names {        [] => String::new(),        [one] => one.clone(),        [rest @ .., last] => chat_say("app.recording.language.and", &[("first", &rest.join(", ")), ("last", last)]),    }}/// The language codes Comms offers for a correction, in the set's order.fn offered() -> Vec<String> {    ["en", "te", "hi", "ta", "kn", "ml", "bn", "mr", "gu", "ur", "pa", "es", "fr", "de", "ja"].iter().map(|c| c.to_string()).collect()}fn person_of(ctx: &mut Ctx<'_>, id: &str) -> Option<(String, Option<String>)> {    let row = engine::get(ctx, "person", id)?;    let name = ["full_name", "name", "display_name"].iter().map(|k| str_of(&row, k).trim().to_string()).find(|n| !n.is_empty())?;    let photo = ["avatar_key", "photo"].iter().map(|k| str_of(&row, k).to_string()).find(|p| !p.is_empty());    Some((name, photo))}fn page(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let id = engine::text(request, "id").or_else(|| engine::text(request, "meeting")).ok_or_else(|| engine::bad("this names the recording: `id`"))?.to_string();    let charging = request.get("charging").and_then(Value::as_bool).unwrap_or(false);    let read = engine::call(handle, "meetings.read", &json!({ "id": id, "charging": charging }))?;    let query = engine::text(request, "query").map(str::trim).filter(|q| !q.is_empty()).map(str::to_string);    let zone = handle.client().time_zone().unwrap_or("Etc/UTC").to_string();    let now = handle.client().clock().now();    let meeting = engine::object(read["meeting"].clone());    let speakers: Vec<Map<String, Value>> = read["speakers"].as_array().into_iter().flatten().map(|s| engine::object(s.clone())).collect();    let people = engine::with_read(handle, "chat.recording.people", |ctx| {        let mut found = Map::new();        for s in &speakers {            let person = str_of(s, "person");            if !person.is_empty() {                if let Some((name, photo)) = person_of(ctx, person) {                    found.insert(person.to_string(), json!({ "name": name, "photo": photo }));                }            }        }        Ok(Value::Object(found))    })?;    let name_of = |s: &Map<String, Value>| -> String {        let given = str_of(s, "name").trim();        if !given.is_empty() {            return given.to_string();        }        people.get(str_of(s, "person")).and_then(|p| p["name"].as_str()).map(str::to_string).unwrap_or_else(|| engine::speaker_name(s))    };    let who: Vec<Value> = speakers        .iter()        .map(|s| {            let name = name_of(s);            let photo = people.get(str_of(s, "person")).and_then(|p| p["photo"].as_str()).map(str::to_string);            json!({                "speaker": str_of(s, "id"),                "label": str_of(s, "label"),                "name": name,                "person": Some(str_of(s, "person")).filter(|p| !p.is_empty()),                "picture": { "photo": photo, "initials": lay::initials(&name), "tint": lay::tint(str_of(s, "label")) },                "choose": chat_line("app.recording.choose"),            })        })        .collect();    // The lines a mark fell in while it recorded (MEETINGS-RETIRE "Marks on the lines"): each mark is the line it    // fell in, the last that began at or before it.    let starts: Vec<i64> = read["lines"].as_array().into_iter().flatten().map(|l| l["start_ms"].as_i64().or_else(|| l["start_ms"].as_f64().map(|f| f as i64)).unwrap_or(0)).collect();    let marked: HashSet<usize> = read["marks"]        .as_array()        .into_iter()        .flatten()        .filter_map(|m| m.as_i64().or_else(|| m.as_f64().map(|f| f as i64)))        .filter_map(|at| starts.iter().rposition(|start| *start <= at))        .collect();    let lines: Vec<Value> = read["lines"]        .as_array()        .into_iter()        .flatten()        .enumerate()        .map(|(index, l)| {            let l = engine::object(l.clone());            let speaker = speakers.iter().find(|s| str_of(s, "id") == str_of(&l, "speaker"));            json!({                "line": str_of(&l, "id"),                "speaker": str_of(&l, "speaker"),                "name": speaker.map(&name_of).unwrap_or_default(),                "start_ms": int_of(&l, "start_ms"),                "end_ms": int_of(&l, "end_ms"),                "text": str_of(&l, "text"),                "language": Some(str_of(&l, "language")).filter(|c| !c.is_empty()),                "edited": l.get("edited").and_then(Value::as_bool).unwrap_or(false),                "marked": marked.contains(&index),            })        })        .collect();    let search = searched(&lines, query.as_deref());    let points: Vec<String> = str_of(&meeting, "summary").lines().map(|l| l.trim().trim_start_matches(['-', '*', '•']).trim().to_string()).filter(|l| !l.is_empty()).collect();    // A summary says who made it: his Mac's local model (`mac:llama:<model>`), or his own assistant over Cotton MCP    // (`recording_summary_write`, signed with its name). With none, a ready recording points at his assistant, which    // reads the transcript inside Your Claude's grant (Recordings) and writes the summary back; one he asked his Mac    // for and it has not made yet says the Mac makes it (owner, 23 Nov 2026: Cotton has no model of its own).    let summary = if !points.is_empty() {        let by = match str_of(&meeting, "summarised_by") {            "" => Value::Null,            mac if mac.starts_with("mac:") => json!(chat_line("app.recording.summary_by.mac")),            _ => json!(chat_line("app.recording.summary_by.assistant")),        };        json!({ "points": points, "by": by })    } else {        let asked_mac = !str_of(&meeting, "summary_asked_at").is_empty() && str_of(&meeting, "summary_asked_at") > str_of(&meeting, "summarised_at");        match str_of(&meeting, "status") {            "ready" if !asked_mac => json!({ "note": chat_line("app.recording.summary_assistant") }),            _ => json!({ "note": chat_line("app.recording.where.summary_mac") }),        }    };    // His languages, else the ones Cotton heard.    let chosen = engine::chosen_languages(&meeting);    let heard: Vec<String> = str_of(&meeting, "languages").split(',').map(str::trim).filter(|l| !l.is_empty()).map(str::to_string).collect();    let shown = if chosen.is_empty() { &heard } else { &chosen };    let names: Vec<String> = shown.iter().map(|c| language_name(c)).collect();    let language_line = match (chosen.is_empty(), names.is_empty()) {        (_, true) => Value::Null,        (true, false) => json!(chat_say("app.recording.language.auto", &[("languages", &joined(&names))])),        (false, false) => json!(chat_say("app.recording.language.chosen", &[("languages", &joined(&names))])),    };    let mut codes = offered();    for c in shown {        if !codes.contains(c) {            codes.push(c.clone());        }    }    let choices: Vec<Value> = codes.iter().map(|c| json!({ "code": c, "label": language_name(c), "on": shown.contains(c) })).collect();    let status = str_of(&meeting, "status").to_string();    let by_phone = str_of(&meeting, "transcribed_by").starts_with("phone");    let again = match status.as_str() {        "ready" if by_phone => json!({ "label": chat_line("app.recording.again.mac"), "on": "mac" }),        "ready" | "failed" => json!({ "label": chat_line("app.recording.again.label") }),        _ => Value::Null,    };    let parts = stamp_parts(str_of(&meeting, "started_at"), &zone, now, DateWords::shipped());    let when = parts.map(|p| match p.clock { Some(clock) => format!("{}, {clock}", p.heading), None => p.heading }).unwrap_or_default();    let saved = !str_of(&meeting, "note").is_empty();    let actions: Vec<Value> = read["actions"]        .as_array()        .into_iter()        .flatten()        .map(|a| json!({ "id": a["id"], "words": a["words"], "who": a["who"], "due": a["due_said"], "added": a["added"], "act": a["act"], "said": a["said"] }))        .collect();    let summary_ask = (status == "ready" && points.is_empty()).then(|| json!({ "label": chat_line("app.recording.summary_again") }));    Ok(json!({        "id": id,        "title": title(&meeting),        "named": !str_of(&meeting, "title").trim().is_empty(),        "when": when,        "length": length(int_of(&meeting, "duration_ms")),        "duration_ms": int_of(&meeting, "duration_ms"),        "source": Some(str_of(&meeting, "source")).filter(|s| !s.is_empty()).unwrap_or("room"),        "mark": mark_of(&meeting),        "status": status,        // Waiting or being heard, the words say where, as the line under the title does (seen on emulator-5608: the        // title said "On this phone" and the transcript "Waiting for your Mac", Meetings' words of before).        "status_line": match (status.as_str(), where_of(&meeting, charging)["line"].as_str()) {            ("waiting" | "transcribing", Some(line)) => json!(line),            // Ready with no words at all: say so, not "Ready" over an empty transcript (android-finish, 23 Nov 2026).            ("ready", _) if lines.is_empty() => json!(chat_line("app.recording.state.silent")),            _ => read["status_words"].clone(),        },        "where": where_of(&meeting, charging),        "speakers": who,        "audio": read["audio"],        "lines": lines,        "marks": read["marks"],        "silenced": read["silenced"],        "summary": summary,        "actions": actions,        "language": { "line": language_line, "chosen": chosen, "choices": choices },        "search": search,        "buttons": {            "skip": {                "back": { "label": chat_line("app.recording.skip.back"), "ms": -SKIP_MS },                "ahead": { "label": chat_line("app.recording.skip.ahead"), "ms": SKIP_MS },            },            "export": {                "label": chat_line("app.recording.export.label"),                "choices": [                    { "format": "text", "label": chat_line("app.recording.export.text") },                    { "format": "srt", "label": chat_line("app.recording.export.srt") },                    { "format": "audio", "label": chat_line("app.recording.export.audio") },                ],            },            "note": { "label": chat_line(if saved { "app.recording.note.update" } else { "app.recording.note.save" }), "saved": saved },            "share": { "label": chat_line("app.recording.share.label") },            "again": again,            "summary": summary_ask,            "delete": { "label": chat_line("app.recording.delete.label"), "ask": chat_line("app.recording.delete.ask") },            // When it was made, his to change (`chat.recording.act { act: "date", at | date, time }`): the pickers            // start where it stands, `at` as an instant and `date` and `time` on his wall clock.            "date": chrono::DateTime::parse_from_rfc3339(str_of(&meeting, "started_at")).ok().map(|at| {                let at = at.with_timezone(&chrono::Utc);                let (date, time) = cotton_core::messages::app::recording_time::picker(at, &zone);                json!({                    "label": chat_line("app.recording.date.label"), "title": chat_line("app.recording.date.title"),                    "save": chat_line("app.recording.date.save"), "cancel": chat_line("app.recording.date.cancel"),                    "at": at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true), "date": date, "time": time,                })            }),        },        "words": {            "who": chat_line("app.recording.heading.who"),            "summary": chat_line("app.recording.heading.summary"),            "actions": chat_line("app.recording.heading.actions"),            "transcript": chat_line("app.recording.heading.transcript"),            "marked": chat_line("app.recording.live.marked"),            "language": chat_line("app.recording.heading.language"),            "title_hint": chat_line("app.recording.title_hint"),            "nothing": engine::line("transcript.waiting"),        },    }))}// ── the acts ────────────────────────────────────────────────────────────────fn act(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let id = engine::text(request, "id").ok_or_else(|| engine::bad("this names the recording: `id`"))?.to_string();    let act = engine::text(request, "act").ok_or_else(|| engine::bad("this names the `act`"))?.to_string();    let said: Value = match act.as_str() {        "title" => {            engine::call(handle, "meetings.title", &json!({ "id": id, "title": request.get("title") }))?;            Value::Null        }        "date" => {            let zone = handle.client().time_zone().unwrap_or("Etc/UTC").to_string();            engine::with_write(handle, "chat.recording.date", |ctx| engine::redate(ctx, &zone, request))?;            json!(chat_line("app.recording.date.said"))        }        "language" => {            let done = engine::call(handle, "meetings.language", &json!({ "id": id, "languages": request.get("languages") }))?;            let names: Vec<String> = done["languages"].as_array().into_iter().flatten().filter_map(Value::as_str).map(language_name).collect();            if names.is_empty() {                json!(chat_line("app.recording.again.said"))            } else {                let line = if done["on"] == "mac" { "app.recording.language.said_mac" } else { "app.recording.language.said" };                json!(chat_say(line, &[("languages", &joined(&names))]))            }        }        "again" => {            let on = engine::text(request, "on");            engine::call(handle, "meetings.transcribe", &json!({ "id": id, "on": on }))?;            json!(chat_line(if on == Some("mac") { "app.recording.again.said_mac" } else { "app.recording.again.said" }))        }        "summary" => engine::call(handle, "meetings.summarise", &json!({ "id": id }))?["said"].clone(),        "note" => engine::call(handle, "meetings.note", &json!({ "id": id }))?["said"].clone(),        "todo" => engine::call(handle, "meetings.action.todo", &json!({ "id": request.get("action") }))?["said"].clone(),        "name" => {            let mut ask = json!({ "speaker": request.get("speaker") });            if let Some(person) = request.get("person") {                ask["person"] = person.clone();            }            if let Some(name) = request.get("name") {                ask["name"] = name.clone();            }            engine::call(handle, "meetings.speaker.name", &ask)?;            Value::Null        }        "correct" => {            engine::call(handle, "meetings.line.correct", &json!({ "line": request.get("line"), "text": request.get("text") }))?;            Value::Null        }        "share" => {            let thread = engine::text(request, "thread").ok_or_else(|| engine::bad("this names the chat: `thread`"))?.to_string();            let zone = handle.client().time_zone().unwrap_or("Etc/UTC").to_string();            let words = engine::with_read(handle, "chat.recording.share", |ctx| {                let meeting = engine::meeting_of(ctx, &json!({ "id": id }))?;                let (title, body) = engine::as_text(ctx, &meeting, &zone, false)?;                Ok(json!(if body.is_empty() { title } else { format!("{title}\n\n{body}") }))            })?;            let sent = super::cotton_chat::call(handle, "chat.act", &json!({ "act": "send", "thread": thread, "text": words }))?;            return Ok(json!({ "page": page(handle, &json!({ "id": id }))?, "said": chat_line("app.recording.share.said"), "flush": sent.get("flush").cloned().unwrap_or(json!(false)) }));        }        "export" => return export(handle, &id, request),        "delete" => {            let done = engine::call(handle, "meetings.delete", &json!({ "id": id }))?;            return Ok(json!({ "deleted": true, "said": done["said"] }));        }        other => return Err(engine::bad(format!("`{other}` is not an act on a recording"))),    };    let charging = request.get("charging").and_then(Value::as_bool).unwrap_or(false);    Ok(json!({ "page": page(handle, &json!({ "id": id, "charging": charging }))?, "said": said }))}/// The ±15 s skip under the scrubber (Meetings had it; MEETINGS-RETIRE.md).const SKIP_MS: i64 = 15_000;/// Search within the transcript: every line holding the words (case and accents as typed aside), each cut into its/// parts so a phone draws the hits without counting characters. No query: none.fn searched(lines: &[Value], query: Option<&str>) -> Value {    let hint = chat_line("app.recording.search.hint");    let Some(query) = query else { return json!({ "hint": hint, "query": null, "hits": [], "line": null }) };    let needle = fold(query);    let mut hits = Vec::new();    for l in lines {        let text = l["text"].as_str().unwrap_or_default();        let parts = cut(text, &needle);        if parts.iter().any(|p| p.1) {            hits.push(json!({                "line": l["line"],                "start_ms": l["start_ms"],                "parts": parts.into_iter().map(|(text, hit)| json!({ "text": text, "hit": hit })).collect::<Vec<_>>(),            }));        }    }    let line = match hits.len() {        0 => chat_line("app.recording.search.none"),        1 => chat_line("app.recording.search.one"),        n => chat_say("app.recording.search.many", &[("count", &n.to_string())]),    };    json!({ "hint": hint, "query": query, "hits": hits, "line": line })}/// A letter as search compares it: lower case, with its accents taken off (é and e are found alike).fn fold_char(c: char) -> String {    use unicode_normalization::UnicodeNormalization;    c.to_lowercase().collect::<String>().nfd().filter(|c| !unicode_normalization::char::is_combining_mark(*c)).collect()}fn fold(text: &str) -> String {    text.chars().map(fold_char).collect()}/// The text cut into runs, each a hit of `needle` (already folded) or not, the text's own letters kept.fn cut(text: &str, needle: &str) -> Vec<(String, bool)> {    if needle.is_empty() {        return vec![(text.to_string(), false)];    }    // Each of the text's letters with what it folds to, so a match in the folded text maps back to the letters.    let letters: Vec<(char, String)> = text.chars().map(|c| (c, fold_char(c))).collect();    let mut parts: Vec<(String, bool)> = Vec::new();    let push = |parts: &mut Vec<(String, bool)>, s: String, hit: bool| {        if s.is_empty() {            return;        }        match parts.last_mut() {            Some(last) if last.1 == hit => last.0.push_str(&s),            _ => parts.push((s, hit)),        }    };    let mut i = 0;    while i < letters.len() {        let mut folded = String::new();        let mut j = i;        while j < letters.len() && folded.len() < needle.len() {            folded.push_str(&letters[j].1);            j += 1;        }        if folded == needle {            push(&mut parts, letters[i..j].iter().map(|l| l.0).collect(), true);            i = j;        } else {            push(&mut parts, letters[i].0.to_string(), false);            i += 1;        }    }    parts}/// Export to the system share sheet: the transcript as text or subtitles, or the audio, written under the/// recording's own title in a fresh folder of this phone's; the phone shares the file it names.fn export(handle: &CottonHandle, id: &str, request: &Value) -> Result<Value, MethodError> {    let format = engine::text(request, "format").ok_or_else(|| engine::bad("this names the `format`: text, srt or audio"))?.to_string();    if !matches!(format.as_str(), "text" | "srt" | "audio") {        return Err(engine::bad(format!("`{format}` is not an export: text, srt or audio")));    }    let root = handle.client().layout().root().join("exports").join("recordings").join(id).join(&format);    // not a copy: recordings.    let _ = std::fs::remove_dir_all(&root);    let made = engine::call(handle, "meetings.export", &json!({ "id": id, "format": format, "dir": root.to_string_lossy() }))?;    let Some(file) = made["files"].as_array().and_then(|f| f.first()).cloned() else {        return Err(MethodError::new("absent", chat_line("app.recording.export.absent")));    };    let from = std::path::PathBuf::from(file["path"].as_str().unwrap_or_default());    let title = page(handle, &json!({ "id": id })).ok().and_then(|p| p["title"].as_str().map(str::to_string)).unwrap_or_default();    let ext = from.extension().and_then(|e| e.to_str()).unwrap_or("txt").to_string();    let name = format!("{}.{ext}", file_name_of(&title));    let to = root.join(&name);    // not a copy: recordings.    std::fs::rename(&from, &to).map_err(|e| MethodError::new("io", format!("the export could not be named: {e}")))?;    Ok(json!({ "file": { "path": to.to_string_lossy(), "name": name, "type": file["type"] } }))}/// A title as a file's name: the characters a file system refuses taken out, never empty.fn file_name_of(title: &str) -> String {    let cleaned: String = title.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() { ' ' } else { c }).collect();    let cleaned = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");    let cleaned: String = cleaned.chars().take(80).collect();    if cleaned.trim().is_empty() { "Recording".to_string() } else { cleaned.trim().trim_matches('.').to_string() }}// ── the recording screen ────────────────────────────────────────────────────fn clock(ms: i64) -> String {    let s = ms.max(0) / 1000;    if s >= 3600 { format!("{}:{:02}:{:02}", s / 3600, (s / 60) % 60, s % 60) } else { format!("{}:{:02}", s / 60, s % 60) }}/// What the recording screen says while it records: the time, the buttons,/// and, with little room left, how long is left or that it stopped.fn live(request: &Value) -> Value {    let ms = request.get("duration_ms").and_then(Value::as_i64).unwrap_or(0);    let kind = match engine::text(request, "kind") {        Some("memo") => "memo",        Some("call") => "call",        _ => "meeting",    };    let space = request.get("free_bytes").and_then(Value::as_i64).and_then(|free| {        if free < SPACE_STOP_BYTES {            Some(json!({ "line": chat_line("app.recording.live.space_stop"), "stop": true }))        } else if free < SPACE_WARN_BYTES {            let minutes = (free - SPACE_STOP_BYTES) / BYTES_PER_MINUTE;            Some(json!({ "line": chat_say("app.recording.live.space", &[("minutes", &minutes.to_string())]), "stop": false }))        } else {            None        }    });    json!({        "title": chat_line(&format!("app.recording.live.title.{kind}")),        "time": clock(ms),        "stop": chat_line("app.recording.live.stop"),        "pause": chat_line("app.recording.live.pause"),        "resume": chat_line("app.recording.live.resume"),        "mark": chat_line("app.recording.live.mark"),        "marked": chat_line("app.recording.live.marked"),        "discard": chat_line("app.recording.live.discard"),        "discardAsk": chat_line("app.recording.live.discard_ask"),        "space": space,    })}#[cfg(test)]#[path = "chat_recordings_tests.rs"]mod tests;