use maud::html;
use crate::backends::gemini::decode_transcript_bytes;
use crate::filesystem::Filesystem;
use crate::types::TranscriptRole;
use super::dom;
use super::templates;
use super::APP;
const HISTORY_FILE: &str = ".lh_history.json";
pub(crate) async fn load_into_pending() {
let fs = super::shared_opfs();
let bytes = match fs.read(HISTORY_FILE).await {
Ok(b) if !b.is_empty() => b,
_ => return,
};
match decode_transcript_bytes(&bytes) {
Ok(entries) if !entries.is_empty() => {
for entry in &entries {
let turn_id = APP.with(|cell| cell.borrow_mut().alloc_id());
let role = entry.role.as_str();
let body = match entry.role {
TranscriptRole::User => html! { (entry.text) },
TranscriptRole::Assistant => templates::rendered_markdown(&entry.text),
};
let html_str =
templates::turn(turn_id, role, body, false).into_string();
dom::append_html("transcript", &html_str);
}
}
Ok(_) => {
}
Err(err) => {
web_sys::console::warn_1(&wasm_bindgen::JsValue::from_str(&format!(
"history decode: {err}"
)));
}
}
APP.with(|cell| cell.borrow_mut().pending_history = Some(bytes));
}
pub(crate) async fn save_from_agent() {
let bytes = APP.with(|cell| {
cell.borrow()
.agent
.as_ref()
.and_then(|a| a.history_bytes().ok().flatten())
});
let Some(bytes) = bytes else { return };
let fs = super::shared_opfs();
if let Err(err) = fs.write_atomic(HISTORY_FILE, &bytes).await {
web_sys::console::warn_1(&wasm_bindgen::JsValue::from_str(&format!(
"history save: {err}"
)));
}
}
pub(crate) fn take_pending() -> Option<Vec<u8>> {
APP.with(|cell| cell.borrow_mut().pending_history.take())
}
pub(crate) async fn clear() {
let fs = super::shared_opfs();
let _ = fs.delete(HISTORY_FILE).await;
}