0.1.6: GBrain brains — refreshed after sync, clashes never make a second page

- A vault has a kind on the hub: Obsidian (as before) or GBrain. Set it with
  `lunesync vault kind`, the canvas panel or the window; Lune suggests it when
  it finds gbrain.yml / .gbrain-source. Every change is in the access log.
- GBrain vaults: devices that have `gbrain` (looked for beyond PATH) are asked
  once whether to refresh it after sync. Lune then runs
  `gbrain sync --source <name> --no-pull` in the background after notes arrive
  or are saved; it never holds up syncing. A failed refresh turns the vault
  amber ("GBrain not refreshed") with Retry, also on the canvas.
- Clashes in GBrain vaults: lines both sides added are kept in the one note,
  incoming first. Same lines changed: the incoming version stays, this
  device's waits under Notes to tidy, stored in .git/lune/tidy (never a copy
  file GBrain would index). Applies to syncing, undo, held notes and
  handovers. Held notes moved aside stay red until decided.
- .gbrain-source is kept per device. Obsidian vaults are unchanged.
- SPEC: M8 section and decisions recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 22:55:18 +07:00
parent ac5dba46df
commit e6c3f008a0
30 changed files with 2169 additions and 101 deletions

View File

@@ -246,13 +246,15 @@ pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
})));
}
let mut stmt = conn.prepare(
"SELECT v.id, v.name, m.role FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name",
"SELECT v.id, v.name, m.role, v.kind FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name",
)?;
let vaults: Vec<Value> = stmt
.query_map([caller.account_id], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?
.query_map([caller.account_id], |r| {
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?))
})?
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) }))
.map(|(id, name, role, kind)| json!({ "id": id, "name": name, "role": role, "kind": kind, "git_url": hub.git_url(id) }))
.collect();
// A Nudge is delivered once: the device shares at once, and the flag clears.
let nudge: bool = conn

View File

@@ -106,6 +106,11 @@ pub fn open(data: &Path) -> Result<Connection> {
("devices", "last_seen INTEGER"),
("devices", "nudge INTEGER NOT NULL DEFAULT 0"),
("vaults", "archived INTEGER"),
// M8: what a vault is for (existing vaults stay Obsidian), and whether the GBrain hint was dismissed.
("vaults", "kind TEXT NOT NULL DEFAULT 'obsidian'"),
("vaults", "hint_dismissed INTEGER NOT NULL DEFAULT 0"),
("device_status", "gbrain_failed INTEGER NOT NULL DEFAULT 0"),
("device_status", "to_tidy INTEGER NOT NULL DEFAULT 0"),
] {
let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []);
}

View File

@@ -26,6 +26,12 @@ pub struct VaultReport {
waiting: i64,
held_secrets: i64,
holding: bool,
/// GBrain vaults: this device's last refresh failed.
#[serde(default)]
gbrain_failed: bool,
/// GBrain vaults: notes whose version from this device waits under Notes to tidy (older clients send none).
#[serde(default)]
to_tidy: i64,
}
#[derive(Deserialize)]
@@ -47,8 +53,8 @@ pub async fn report(State(hub): State<Shared>, headers: HeaderMap, Json(req): Js
continue;
}
conn.execute(
"INSERT INTO device_status (device_id, vault_id, last_synced, waiting, held_secrets, holding) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![caller.device_id, v.vault_id, v.last_synced, v.waiting, v.held_secrets, v.holding],
"INSERT INTO device_status (device_id, vault_id, last_synced, waiting, held_secrets, holding, gbrain_failed, to_tidy) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
params![caller.device_id, v.vault_id, v.last_synced, v.waiting, v.held_secrets, v.holding, v.gbrain_failed, v.to_tidy],
)?;
}
Ok(Json(json!({})))
@@ -57,23 +63,24 @@ pub async fn report(State(hub): State<Shared>, headers: HeaderMap, Json(req): Js
/// A device's freshness for the canvas, from its last report.
pub fn device_health(conn: &Connection, device_id: &str) -> Result<Value> {
let last_seen: Option<i64> = conn.query_row("SELECT last_seen FROM devices WHERE id = ?1", [device_id], |r| r.get(0))?;
let (oldest_sync, waiting, held_secrets, holding): (Option<i64>, i64, i64, bool) = conn.query_row(
"SELECT MIN(last_synced), COALESCE(SUM(waiting), 0), COALESCE(SUM(held_secrets), 0), COALESCE(MAX(holding), 0)
let (oldest_sync, waiting, held_secrets, holding, gbrain_failed): (Option<i64>, i64, i64, bool, bool) = conn.query_row(
"SELECT MIN(last_synced), COALESCE(SUM(waiting), 0), COALESCE(SUM(held_secrets), 0), COALESCE(MAX(holding), 0),
COALESCE(MAX(gbrain_failed), 0)
FROM device_status WHERE device_id = ?1",
[device_id],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)?;
let online = last_seen.is_some_and(|t| db::now() - t <= OFFLINE_AFTER);
let status = if !online {
"offline"
} else if waiting > 0 || holding || held_secrets > 0 {
} else if waiting > 0 || holding || held_secrets > 0 || gbrain_failed {
"behind"
} else {
"current"
};
Ok(json!({
"status": status, "last_seen": last_seen, "last_synced": oldest_sync,
"waiting": waiting, "held_secrets": held_secrets, "holding": holding
"waiting": waiting, "held_secrets": held_secrets, "holding": holding, "gbrain_failed": gbrain_failed
}))
}
@@ -103,6 +110,32 @@ pub async fn nudge(State(hub): State<Shared>, headers: HeaderMap, Json(req): Jso
Ok(Json(json!({})))
}
/// Labels of the devices whose last GBrain refresh failed, for one vault.
pub fn gbrain_stale(conn: &Connection, vault_id: i64) -> Result<Vec<String>> {
let mut stmt = conn.prepare(
"SELECT d.label FROM device_status s JOIN devices d ON d.id = s.device_id
WHERE s.vault_id = ?1 AND s.gbrain_failed = 1 AND d.removed = 0 ORDER BY d.label",
)?;
Ok(stmt.query_map([vault_id], |r| r.get(0))?.collect::<Result<_, _>>()?)
}
/// Devices holding notes to tidy for one vault: (device label, count). The versions themselves stay on the device.
pub fn tidy_on_devices(conn: &Connection, vault_id: i64) -> Result<Vec<(String, i64)>> {
let mut stmt = conn.prepare(
"SELECT d.label, s.to_tidy FROM device_status s JOIN devices d ON d.id = s.device_id
WHERE s.vault_id = ?1 AND s.to_tidy > 0 AND d.removed = 0 ORDER BY d.label",
)?;
Ok(stmt.query_map([vault_id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::<Result<_, _>>()?)
}
/// Does the vault's shared copy hold a file at its root that says "this is a GBrain"?
pub fn has_gbrain_marker(repo_path: &Path) -> bool {
let Ok(repo) = Repository::open_bare(repo_path) else { return false };
let Ok(Some(main)) = main_ref(&repo) else { return false };
let Ok(tree) = repo.find_reference(&main).and_then(|r| r.peel_to_tree()) else { return false };
["gbrain.yml", ".gbrain-source"].iter().any(|m| tree.get_name(m).is_some())
}
/// Notes kept in two versions in a vault's shared copy: (note, copy, device label).
pub fn kept_both(repo_path: &Path) -> Result<Vec<(String, String, String)>> {
let repo = Repository::open_bare(repo_path)?;

View File

@@ -289,6 +289,36 @@ pub async fn vault_settings(State(hub): State<Shared>, headers: HeaderMap, Json(
Ok(Json(json!({})))
}
#[derive(Deserialize)]
pub struct KindReq {
vault: String,
/// obsidian or gbrain; leave out to change nothing.
kind: Option<String>,
/// Hide the "this looks like a GBrain" suggestion.
#[serde(default)]
dismiss_suggestion: bool,
}
/// What a vault is for (M8): Obsidian by default, or a GBrain brain. Set here so every device agrees.
pub async fn vault_kind(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<KindReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap();
let (id, name) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
if !can_manage(&conn, &caller, id)? {
return Err(denied(format!("you need Manage on {name}")));
}
if let Some(kind) = &req.kind {
let kind = lune_core::config::VaultKind::parse(kind).ok_or_else(|| bad("a vault's kind is obsidian or gbrain"))?;
conn.execute("UPDATE vaults SET kind = ?1 WHERE id = ?2", params![kind.as_str(), id])?;
let word = if kind == lune_core::config::VaultKind::Gbrain { "GBrain" } else { "Obsidian" };
db::log(&conn, &caller.who(), "vault setting", &format!("{name}: kind set to {word}"))?;
}
if req.dismiss_suggestion {
conn.execute("UPDATE vaults SET hint_dismissed = 1 WHERE id = ?1", [id])?;
}
Ok(Json(json!({})))
}
#[derive(Deserialize)]
pub struct DoneReq {
id: i64,
@@ -361,23 +391,45 @@ fn already_shared(repo: &Repository, head: Oid) -> Result<bool> {
Ok(tip == head || repo.graph_descendant_of(tip, head)?)
}
/// Combines a handover into the vault's main line; same-lines clashes keep both, labeled with `label`.
fn keep_handover(repo_path: &Path, id: i64, label: &str) -> Result<usize> {
/// What keeping a handover did with notes both sides changed: (copies made, notes where both sides' added lines
/// were kept, notes where the handover's version went in place of the team's earlier one).
#[derive(Default)]
pub struct HandoverClashes {
pub copies: usize,
pub joined: usize,
pub replaced: usize,
}
/// Combines a handover into the vault's main line. Obsidian vaults: same-lines clashes keep both, labeled with
/// `label`. GBrain vaults never get a copy: lines both added are all kept, and where the same lines changed the
/// handover's version goes in place (the manager chose Keep); the team's earlier version stays in the vault's
/// history, so nothing is lost.
pub fn keep_handover(repo_path: &Path, id: i64, label: &str, kind: lune_core::config::VaultKind) -> Result<HandoverClashes> {
let repo = Repository::open_bare(repo_path)?;
let mut handover_ref = repo.find_reference(&format!("refs/handover/{id}"))?;
let handover = handover_ref.peel_to_commit()?;
let Some(main) = main_ref(&repo)? else {
repo.reference("refs/heads/main", handover.id(), false, "lune: kept handover")?;
handover_ref.delete()?;
return Ok(0);
return Ok(HandoverClashes::default());
};
let tip = repo.find_reference(&main)?.peel_to_commit()?;
let mut kept = vec![];
let mut out = HandoverClashes::default();
if repo.graph_descendant_of(handover.id(), tip.id())? {
repo.reference_matching(&main, handover.id(), true, tip.id(), "lune: kept handover")?;
} else if !repo.graph_descendant_of(tip.id(), handover.id())? {
let mut index = repo.merge_commits(&tip, &handover, None)?;
lune_core::vault::keep_both(&mut index, label, &mut kept)?;
let style = match kind {
lune_core::config::VaultKind::Gbrain => lune_core::vault::ClashStyle::Gbrain,
lune_core::config::VaultKind::Obsidian => lune_core::vault::ClashStyle::Copies { label },
};
for k in lune_core::vault::keep_both(&repo, &mut index, style)? {
match k {
lune_core::vault::Kept::Copied { .. } => out.copies += 1,
lune_core::vault::Kept::Joined { .. } => out.joined += 1,
lune_core::vault::Kept::Aside { .. } => out.replaced += 1,
}
}
let tree = repo.find_tree(index.write_tree_to(&repo)?)?;
let sig = Signature::now(label, "handover@lune.device")?;
let msg = format!("Kept the handover from {label}");
@@ -385,7 +437,7 @@ fn keep_handover(repo_path: &Path, id: i64, label: &str) -> Result<usize> {
repo.reference_matching(&main, id, true, tip.id(), "lune: kept handover")?;
}
handover_ref.delete()?;
Ok(kept.len())
Ok(out)
}
/// Departures in vaults the caller manages (all of them for the owner), newest first.
@@ -479,8 +531,19 @@ pub async fn handover_decide(State(hub): State<Shared>, headers: HeaderMap, Json
let (vault_id, vault, device, state) = departure_for(&conn, &caller, req.id)?;
let (new_state, message) = match (req.decision.as_str(), state.as_str()) {
("keep", "received") => {
let clashes = keep_handover(&hub.repo_path(vault_id), req.id, &device)?;
let extra = if clashes > 0 { format!(" ({clashes} note(s) changed in two places: both versions kept)") } else { String::new() };
let kind: String = conn.query_row("SELECT kind FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0))?;
let kind = lune_core::config::VaultKind::parse(&kind).unwrap_or_default();
let c = keep_handover(&hub.repo_path(vault_id), req.id, &device, kind)?;
let mut extra = String::new();
if c.copies > 0 {
extra.push_str(&format!(" ({} note(s) changed in two places: both versions kept)", c.copies));
}
if c.joined > 0 {
extra.push_str(&format!(" ({} note(s) had lines added in both places: all kept)", c.joined));
}
if c.replaced > 0 {
extra.push_str(&format!(" ({} note(s) changed in the same lines in both places: {device}'s version is in place, the earlier one stays in the vault's history)", c.replaced));
}
("kept", format!("Kept {device}'s handover in {vault}{extra}. It reaches every device on its next sync."))
}
("discard", "received") => {
@@ -503,3 +566,91 @@ pub async fn handover_decide(State(hub): State<Shared>, headers: HeaderMap, Json
db::log(&conn, &caller.who(), &format!("handover {new_state}"), &format!("{device} in {vault}"))?;
Ok(Json(json!({ "message": message })))
}
#[cfg(test)]
mod tests {
use super::*;
use lune_core::config::VaultKind;
use lune_core::git2::{TreeWalkMode, TreeWalkResult};
use lune_core::names;
/// A bare vault with main at "base", plus a handover from a device that changed the same note.
fn setup(base: &str, team: &str, away: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp.path().join("v.git");
let repo = Repository::init_bare(&path).unwrap();
let sig = Signature::now("t", "t@lune.device").unwrap();
let commit = |text: &str, parent: Option<&lune_core::git2::Commit>, update: Option<&str>| {
let blob = repo.blob(text.as_bytes()).unwrap();
let mut tb = repo.treebuilder(None).unwrap();
tb.insert("page.md", blob, 0o100644).unwrap();
let tree = repo.find_tree(tb.write().unwrap()).unwrap();
let parents: Vec<_> = parent.into_iter().collect();
repo.commit(update, &sig, &sig, "x", &tree, &parents).unwrap()
};
let root = commit(base, None, Some("refs/heads/main"));
let root = repo.find_commit(root).unwrap();
commit(team, Some(&root), Some("refs/heads/main"));
let h = commit(away, Some(&root), None);
repo.reference("refs/handover/7", h, true, "test").unwrap();
repo.set_head("refs/heads/main").unwrap();
(tmp, path)
}
fn main_files(path: &Path) -> Vec<(String, String)> {
let repo = Repository::open_bare(path).unwrap();
let tree = repo.find_reference("refs/heads/main").unwrap().peel_to_tree().unwrap();
let mut out = vec![];
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
let b = e.to_object(&repo).unwrap().peel_to_blob().unwrap();
out.push((format!("{dir}{}", e.name().unwrap()), String::from_utf8_lossy(b.content()).into_owned()));
TreeWalkResult::Ok
})
.unwrap();
out
}
fn any_copy_in_history(path: &Path) -> bool {
let repo = Repository::open_bare(path).unwrap();
let mut walk = repo.revwalk().unwrap();
walk.push_ref("refs/heads/main").unwrap();
walk.any(|id| {
let tree = repo.find_commit(id.unwrap()).unwrap().tree().unwrap();
let mut found = false;
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
found |= names::parse_copy(&format!("{dir}{}", e.name().unwrap())).is_some();
TreeWalkResult::Ok
})
.unwrap();
found
})
}
#[test]
fn keeping_a_handover_makes_no_copy_in_a_gbrain_vault() {
// Same lines changed: the handover's version goes in place, no copy anywhere.
let (_t, path) = setup("a\nb\nc\n", "a\nteam\nc\n", "a\naway\nc\n");
let c = keep_handover(&path, 7, "Old laptop", VaultKind::Gbrain).unwrap();
assert_eq!((c.copies, c.joined, c.replaced), (0, 0, 1));
assert_eq!(main_files(&path), vec![("page.md".to_string(), "a\naway\nc\n".to_string())]);
assert!(!any_copy_in_history(&path));
// Lines both added at the end: all kept, the earlier team lines first-in-place rule applies (handover first).
let (_t, path) = setup("a\n", "a\nteam\n", "a\naway\n");
let c = keep_handover(&path, 7, "Old laptop", VaultKind::Gbrain).unwrap();
assert_eq!((c.copies, c.joined, c.replaced), (0, 1, 0));
let files = main_files(&path);
assert_eq!(files.len(), 1);
assert!(files[0].1.contains("team") && files[0].1.contains("away"), "{files:?}");
assert!(!any_copy_in_history(&path));
}
#[test]
fn keeping_a_handover_in_an_obsidian_vault_still_makes_a_copy() {
let (_t, path) = setup("a\nb\nc\n", "a\nteam\nc\n", "a\naway\nc\n");
let c = keep_handover(&path, 7, "Old laptop", VaultKind::Obsidian).unwrap();
assert_eq!((c.copies, c.joined, c.replaced), (1, 0, 0));
let files = main_files(&path);
assert!(files.iter().any(|(p, _)| p == "page (Old laptop's version).md"), "{files:?}");
}
}

View File

@@ -109,6 +109,7 @@ async fn serve() -> Result<()> {
.route("/api/team/remove", post(leave::team_remove))
.route("/api/team/restore", post(leave::team_restore))
.route("/api/vaults/settings", post(leave::vault_settings))
.route("/api/vaults/kind", post(leave::vault_kind))
.route("/api/vaults/delete", post(leave::delete_vault))
.route("/api/departures/done", post(leave::departure_done))
.route("/api/handovers", get(leave::handovers))

View File

@@ -115,20 +115,20 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap();
let vault_rows: Vec<(i64, String, bool)> = {
let vault_rows: Vec<(i64, String, bool, String, bool)> = {
let sql = if caller.owner {
"SELECT id, name, delete_from_devices FROM vaults WHERE archived IS NULL ORDER BY created, id"
"SELECT id, name, delete_from_devices, kind, hint_dismissed FROM vaults WHERE archived IS NULL ORDER BY created, id"
} else {
"SELECT v.id, v.name, v.delete_from_devices FROM vaults v JOIN memberships m ON m.vault_id = v.id
"SELECT v.id, v.name, v.delete_from_devices, v.kind, v.hint_dismissed FROM vaults v JOIN memberships m ON m.vault_id = v.id
WHERE m.account_id = ?1 ORDER BY v.created, v.id"
};
let mut stmt = conn.prepare(sql)?;
let map = |r: &rusqlite::Row| Ok((r.get(0)?, r.get(1)?, r.get(2)?));
let map = |r: &rusqlite::Row| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?));
if caller.owner { stmt.query_map([], map)?.collect::<Result<_, _>>()? } else { stmt.query_map([caller.account_id], map)?.collect::<Result<_, _>>()? }
};
let mut vaults = vec![];
let mut managed = vec![];
for (id, name, delete_files) in &vault_rows {
for (id, name, delete_files, kind, dismissed) in &vault_rows {
let manage = can_manage(&conn, &caller, *id)?;
if manage {
managed.push(*id);
@@ -151,9 +151,18 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
} else {
vec![]
};
// GBrain (M8): managers see which devices couldn't refresh it, and a hint when the vault looks like one.
let gbrain_stale = if manage && kind == "gbrain" { crate::health::gbrain_stale(&conn, *id).unwrap_or_default() } else { vec![] };
let tidy_on: Vec<Value> = crate::health::tidy_on_devices(&conn, *id)
.unwrap_or_default()
.into_iter()
.map(|(device, count)| json!({ "device": device, "count": count }))
.collect();
let suggest_gbrain = manage && kind != "gbrain" && !dismissed && crate::health::has_gbrain_marker(&hub.repo_path(*id));
vaults.push(json!({
"id": format!("v{id}"), "name": name, "can_manage": manage, "delete_from_devices": delete_files,
"tidy": tidy, "handovers": handovers
"kind": kind, "gbrain_stale": gbrain_stale, "suggest_gbrain": suggest_gbrain,
"tidy": tidy, "tidy_on": tidy_on, "handovers": handovers
}));
}
let visible: Vec<i64> = vault_rows.iter().map(|v| v.0).collect();

View File

@@ -1,5 +1,6 @@
//! The hub end to end: one-time links, pairing, roles enforced by the hub, secrets refused (P3).
use lune_core::config::VaultKind;
use lune_core::hub::{self, HubLink};
use lune_core::vault::{self, Vault};
use lune_core::{remote, secrets, state};
@@ -354,7 +355,7 @@ fn health_nudge_and_tidy() {
let codex = as_device(&url, &sen_w);
std::fs::write(a.root.join("draft.md"), "unsaved\n").unwrap();
codex
.report(&[hub::VaultHealth { vault_id: devops.id, last_synced: Some(1), waiting: 1, held_secrets: 0, holding: false }])
.report(&[hub::VaultHealth { vault_id: devops.id, last_synced: Some(1), waiting: 1, held_secrets: 0, holding: false, gbrain_failed: false, to_tidy: 0 }])
.unwrap();
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
@@ -616,6 +617,7 @@ fn deleting_a_vault_and_leaving_a_team() {
branch: "main".into(),
hub_vault: Some(1),
hub_url: Some("http://127.0.0.1:9".into()),
..Default::default()
});
assert!(lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", false).is_err());
lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", true).unwrap();
@@ -818,3 +820,70 @@ fn a_folder_follows_its_settings() {
assert_eq!(v.remote_url().as_deref(), Some(cfg.remote.as_str()));
assert!(v.follow("").unwrap() && v.is_local());
}
#[test]
fn a_vaults_kind_is_set_on_the_hub_and_every_device_follows() {
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap();
unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("cfg")) };
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
let (_, sen_w) = hub::join(&owner_link, "Mac").unwrap();
let mut mac = device(&url, &sen_w, "Mac", &tmp.path().join("mac"));
mac.use_hub_credentials();
let link = mac.hubs[0].clone();
link.create_vault("Brain").unwrap();
// Existing and new vaults are Obsidian until someone says otherwise.
assert_eq!(link.me().unwrap().vaults[0].kind, VaultKind::Obsidian);
check_in(&mut mac);
assert_eq!(mac.find("Brain").unwrap().kind, VaultKind::Obsidian);
// A Read member can't change it; Manage (here the owner) can, and it's logged.
let invite = link.invite("Bob", &[("Brain".into(), "read".into())]).unwrap();
let (_, bob_w) = hub::join(&invite, "Bob pc").unwrap();
let bob = as_device(&url, &bob_w);
let err = format!("{:#}", bob.vault_kind("Brain", Some(VaultKind::Gbrain), false).unwrap_err());
assert!(err.contains("Manage"), "{err}");
assert!(link.vault_kind("Brain", Some(VaultKind::Gbrain), false).is_ok());
assert_eq!(bob.me().unwrap().vaults[0].kind, VaultKind::Gbrain);
let log = link.log(20).unwrap();
assert!(log.iter().any(|e| e.action == "vault setting" && e.detail == "Brain: kind set to GBrain"), "{log:?}");
// The device learns it at its next check-in, keeps it in its config, and ignores the per-device pin.
mac.use_hub_credentials();
let said = check_in(&mut mac);
assert!(said.iter().any(|m| m.contains("GBrain")), "{said:?}");
assert_eq!(mac.find("Brain").unwrap().kind, VaultKind::Gbrain);
assert_eq!(Config::load().unwrap().find("Brain").unwrap().kind, VaultKind::Gbrain);
let v = open(&mac, "Brain");
write_and_save(&v, ".gbrain-source", "brain\n");
write_and_save(&v, "gbrain.yml", "x: 1\n");
assert_eq!(v.tracked_files().unwrap(), vec!["gbrain.yml".to_string()]);
// A device whose refresh failed says so; the canvas shows the vault's kind and which device is stale.
let vid = link.me().unwrap().vaults[0].id;
link.report(&[hub::VaultHealth { vault_id: vid, last_synced: Some(db_now()), waiting: 0, held_secrets: 0, holding: false, gbrain_failed: true, to_tidy: 2 }])
.unwrap();
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
let res = agent.post(format!("{url}/api/web/signin")).send_json(serde_json::json!({ "code": link.pair().unwrap() })).unwrap();
let session = res.headers().get("set-cookie").unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
let canvas: serde_json::Value =
agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap().body_mut().read_json().unwrap();
assert_eq!(canvas["vaults"][0]["kind"], "gbrain");
assert_eq!(canvas["vaults"][0]["gbrain_stale"], serde_json::json!(["Mac"]));
// Versions kept on a device are counted, never shown: the canvas says how many wait on which device.
assert_eq!(canvas["vaults"][0]["tidy_on"], serde_json::json!([{ "device": "Mac", "count": 2 }]));
assert_eq!(canvas["people"][0]["devices"][0]["health"]["status"], "behind");
link.report(&[hub::VaultHealth { vault_id: vid, last_synced: Some(db_now()), waiting: 0, held_secrets: 0, holding: false, gbrain_failed: false, to_tidy: 0 }])
.unwrap();
// Back to Obsidian: the device follows that too.
link.vault_kind("Brain", Some(VaultKind::Obsidian), false).unwrap();
check_in(&mut mac);
assert_eq!(mac.find("Brain").unwrap().kind, VaultKind::Obsidian);
// The "this looks like a GBrain" hint can be dismissed.
link.vault_kind("Brain", None, true).unwrap();
}
fn db_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64
}