git clone https://garage44.eu/jeroen/midas.git.. /src/zedthreads.rs
//! Zed's archive, followed at the hub: a thread archived (or brought back) in
//! Zed's sidebar is archived (or brought back) on the page too.
//!
//! ACP has no word for it: Zed keeps its threads' archive to itself, in its
//! own database (`sidebar_threads.archived`, by the ACP session's id), and
//! what reaches the agent is only the `session/close` it sends whenever it
//! lets go of a thread's view, archived or not. So the mirror on the editor's
//! machine (tap.rs) reads that table now and then, read-only, through the
//! `sqlite3` command, and acts on what changed since it last looked
//! (`~/.local/state/midas/zed-archived.json`): a thread that went into the
//! archive since, its mirrored session archived at the hub; one that came out,
//! brought back. Changes, not states: a session brought back on the page stays
//! so until Zed's archive changes again. Only this machine's mirrored sessions.
//!
//! The other way round it cannot go: Zed's archive is Zed's to write.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use serde_json::{json, Value};
/// How often Zed's archive is looked at.
const EVERY: Duration = Duration::from_secs(15);
/// Zed's databases, one per release channel that has run here.
fn databases() -> Vec<PathBuf> {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let roots = [
home.join("Library/Application Support/Zed/db"),
std::env::var("XDG_DATA_HOME").map(PathBuf::from).unwrap_or_else(|_| home.join(".local/share")).join("zed/db"),
];
roots.iter().flat_map(|r| std::fs::read_dir(r).into_iter().flatten().flatten())
.map(|e| e.path().join("db.sqlite")).filter(|p| p.is_file()).collect()
}
fn sqlite(db: &Path, sql: &str) -> Option<String> {
let out = Command::new("sqlite3").args(["-readonly", "-json"]).arg(db).arg(sql).output().ok().filter(|o| o.status.success())?;
Some(String::from_utf8_lossy(&out.stdout).to_string())
}
/// Every thread Zed knows with an ACP session, archived or not: `Some(None)`
/// for a database without threads (Zed's global one), `None` for one that did
/// not answer (being written, say).
fn archived_in(db: &Path) -> Option<Option<BTreeMap<String, bool>>> {
let has = sqlite(db, "select count(*) as n from sqlite_master where type = 'table' and name = 'sidebar_threads'")?;
if !has.contains("\"n\":1") {
return Some(None);
}
let text = sqlite(db, "select session_id, archived from sidebar_threads where session_id is not null and session_id != ''")?;
if text.trim().is_empty() {
return Some(Some(BTreeMap::new()));
}
let rows: Vec<Value> = serde_json::from_str(&text).ok()?;
Some(Some(rows.iter().filter_map(|r| Some((r["session_id"].as_str()?.to_string(), r["archived"].as_i64().unwrap_or(0) != 0))).collect()))
}
/// What changed since `before`: each session that went into the archive
/// (`true`) or came out (`false`). One not seen before counts as having been
/// out, so an archive made while no mirror ran is followed too.
pub fn changes(before: &BTreeMap<String, bool>, now: &BTreeMap<String, bool>) -> Vec<(String, bool)> {
now.iter().filter(|(sid, a)| before.get(*sid).copied().unwrap_or(false) != **a).map(|(sid, a)| (sid.clone(), *a)).collect()
}
fn state_path() -> PathBuf {
PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/state/midas/zed-archived.json")
}
/// Follow Zed's archive at the hub, for the sessions mirrored from `machine`; never returns.
pub fn follow(machine: String) {
loop {
let dbs = databases();
if !dbs.is_empty() {
if let Err(e) = look(&dbs, &machine) {
eprintln!("midas: following Zed's archive: {e:#}");
}
}
std::thread::sleep(EVERY);
}
}
/// `midas zed-archive`: one look now, for this machine, as the mirror takes them.
pub fn once() -> anyhow::Result<i32> {
let machine = crate::client::setting("MIDAS_MACHINE").unwrap_or_else(|| "?".into());
let dbs = databases();
if dbs.is_empty() {
anyhow::bail!("no Zed database here");
}
look(&dbs, &machine)?;
Ok(0)
}
fn look(dbs: &[PathBuf], machine: &str) -> anyhow::Result<()> {
let mut now = BTreeMap::new();
for db in dbs {
// A database being written may not answer this time: the next look will.
let Some(threads) = archived_in(db) else { return Ok(()) };
for (sid, a) in threads.unwrap_or_default() {
*now.entry(sid).or_insert(false) |= a;
}
}
let path = state_path();
let before: BTreeMap<String, bool> = crate::store::read(&path).unwrap_or_default();
let changed = changes(&before, &now);
if changed.is_empty() {
return Ok(());
}
let hosted = crate::client::get("/v1/hosted")?;
let mine: BTreeMap<&str, (&str, bool)> = hosted.as_array().into_iter().flatten()
.filter(|s| s["local"]["machine"] == machine)
.filter_map(|s| Some((s["agent_session"].as_str()?, (s["id"].as_str()?, s["archived"] == true)))).collect();
let mut seen = before.clone();
for (sid, archived) in changed {
if let Some((id, at_hub)) = mine.get(sid.as_str()) {
if *at_hub != archived {
if let Err(e) = crate::client::post(&format!("/v1/hosted/{id}/archive"), &json!({"on": archived})) {
// Not taken as seen: tried again at the next look.
eprintln!("midas: {} {id} on the hub as in Zed: {e:#}", if archived { "archiving" } else { "bringing back" });
continue;
}
eprintln!("midas: {sid} {} in Zed, so {id} on the hub", if archived { "archived" } else { "brought back" });
}
}
seen.insert(sid, archived);
}
// Threads Zed no longer has are forgotten here too.
seen.retain(|sid, _| now.contains_key(sid));
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
crate::store::write_json(&path, &seen, crate::store::PUBLIC)
}
#[cfg(test)]
mod tests {
use super::*;
fn m(v: &[(&str, bool)]) -> BTreeMap<String, bool> {
v.iter().map(|(s, a)| (s.to_string(), *a)).collect()
}
#[test]
fn only_what_changed_in_zed_is_followed() {
let before = m(&[("a", false), ("b", true), ("c", false)]);
let now = m(&[("a", true), ("b", false), ("c", false), ("d", true), ("e", false)]);
// a archived, b brought back, d archived while nobody looked; c and e as they were.
assert_eq!(changes(&before, &now), vec![("a".into(), true), ("b".into(), false), ("d".into(), true)]);
assert!(changes(&now, &now).is_empty());
}
}