Milestone 6: canvas for health and leaving

Devices report freshness per vault every 30 s (counts only); the canvas
shows current / behind / offline, held secrets in red, and a Nudge that
reaches the device at its next check-in. Notes kept in two versions can
be compared side by side and tidied on the hub's copy. Handovers are
reviewed in the vault panel; people can be removed from the team and
restored with a one-time link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 09:47:28 +07:00
parent 193cb06f85
commit 8be559817c
15 changed files with 744 additions and 57 deletions

View File

@@ -247,9 +247,16 @@ pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
.into_iter()
.map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "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
.query_row("SELECT nudge FROM devices WHERE id = ?1", [&caller.device_id], |r| r.get(0))
.unwrap_or(false);
if nudge {
conn.execute("UPDATE devices SET nudge = 0 WHERE id = ?1", [&caller.device_id])?;
}
Ok(Json(json!({
"person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults,
"leaving": leaving
"leaving": leaving, "nudge": nudge
})))
}

View File

@@ -75,6 +75,15 @@ CREATE TABLE IF NOT EXISTS pending_removals (
due INTEGER NOT NULL,
by_who TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS device_status (
device_id TEXT NOT NULL,
vault_id INTEGER NOT NULL,
last_synced INTEGER,
waiting INTEGER NOT NULL,
held_secrets INTEGER NOT NULL,
holding INTEGER NOT NULL,
PRIMARY KEY (device_id, vault_id)
);
CREATE TABLE IF NOT EXISTS log (
id INTEGER PRIMARY KEY,
at INTEGER NOT NULL,
@@ -94,6 +103,8 @@ pub fn open(data: &Path) -> Result<Connection> {
("devices", "removed INTEGER NOT NULL DEFAULT 0"),
("vaults", "delete_from_devices INTEGER NOT NULL DEFAULT 1"),
("invites", "account_id INTEGER"),
("devices", "last_seen INTEGER"),
("devices", "nudge INTEGER NOT NULL DEFAULT 0"),
] {
let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []);
}

230
hub/src/health.rs Normal file
View File

@@ -0,0 +1,230 @@
//! Health and tidying (M6): devices report freshness, managers nudge, and notes changed in two places
//! are compared and tidied from the hub's copy of the vault.
use crate::api::{ApiResult, Shared, authenticate, bad, denied};
use crate::db;
use crate::leave::main_ref;
use anyhow::{Context, Result};
use axum::Json;
use axum::extract::State;
use axum::http::HeaderMap;
use lune_core::git2::build::TreeUpdateBuilder;
use lune_core::git2::{FileMode, ObjectType, Repository, Signature, TreeWalkMode, TreeWalkResult};
use lune_core::names;
use rusqlite::{Connection, params};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::Path;
/// Not heard from in this long: offline (grey).
pub const OFFLINE_AFTER: i64 = 120;
#[derive(Deserialize)]
pub struct VaultReport {
vault_id: i64,
last_synced: Option<i64>,
waiting: i64,
held_secrets: i64,
holding: bool,
}
#[derive(Deserialize)]
pub struct ReportReq {
vaults: Vec<VaultReport>,
}
/// A device's check-in: per vault, when it last synced and what's waiting. Counts only, never content.
pub async fn report(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<ReportReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
if caller.device_id.is_empty() {
return Err(bad("only devices report their health"));
}
let conn = hub.db.lock().unwrap();
conn.execute("UPDATE devices SET last_seen = ?1 WHERE id = ?2", params![db::now(), caller.device_id])?;
conn.execute("DELETE FROM device_status WHERE device_id = ?1", [&caller.device_id])?;
for v in req.vaults {
if db::role(&conn, caller.account_id, v.vault_id)?.is_none() {
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],
)?;
}
Ok(Json(json!({})))
}
/// 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)
FROM device_status WHERE device_id = ?1",
[device_id],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)?;
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 {
"behind"
} else {
"current"
};
Ok(json!({
"status": status, "last_seen": last_seen, "last_synced": oldest_sync,
"waiting": waiting, "held_secrets": held_secrets, "holding": holding
}))
}
#[derive(Deserialize)]
pub struct NudgeReq {
device_id: String,
}
/// Ask a device to share what it has, at its next check-in.
pub async fn nudge(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<NudgeReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap();
let (account_id, label): (i64, String) = conn
.query_row("SELECT account_id, label FROM devices WHERE id = ?1 AND removed = 0", [&req.device_id], |r| Ok((r.get(0)?, r.get(1)?)))
.map_err(|_| bad("no such device"))?;
let shares_managed: bool = conn.query_row(
"SELECT COUNT(*) > 0 FROM memberships theirs JOIN memberships mine ON mine.vault_id = theirs.vault_id
WHERE theirs.account_id = ?1 AND mine.account_id = ?2 AND mine.role = 'manage'",
[account_id, caller.account_id],
|r| r.get(0),
)?;
if account_id != caller.account_id && !caller.owner && !shares_managed {
return Err(denied("you can nudge your own devices, or those of people in vaults you manage"));
}
conn.execute("UPDATE devices SET nudge = 1 WHERE id = ?1", [&req.device_id])?;
db::log(&conn, &caller.who(), "nudged", &label)?;
Ok(Json(json!({})))
}
/// 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)?;
let Some(main) = main_ref(&repo)? else { return Ok(vec![]) };
let tree = repo.find_reference(&main)?.peel_to_tree()?;
let mut out = vec![];
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
if e.kind() == Some(ObjectType::Blob)
&& let Ok(name) = e.name()
{
let path = format!("{dir}{name}");
if let Some((note, label)) = names::parse_copy(&path) {
out.push((note, path, label));
}
}
TreeWalkResult::Ok
})?;
out.sort();
Ok(out)
}
/// The vault's id and name, if the caller is a member (any role); `edit` requires Edit or Manage.
fn member_vault(conn: &Connection, caller: &db::Caller, vault: &str, edit: bool) -> Result<(i64, String), crate::api::ApiError> {
let (id, name) = db::vault_id(conn, vault)?.ok_or_else(|| bad(format!("no vault named {vault}")))?;
let role = db::role(conn, caller.account_id, id)?;
let ok = match role.as_deref() {
Some("edit") | Some("manage") => true,
Some(_) => !edit,
None => false,
};
if !ok {
return Err(denied(if edit { format!("you need Edit on {name} to tidy it") } else { format!("you're not a member of {name}") }));
}
Ok((id, name))
}
#[derive(Deserialize)]
pub struct CompareReq {
vault: String,
copy: String,
}
/// Both versions of a kept-both note, for comparing side by side.
pub async fn compare(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<CompareReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let (id, _) = {
let conn = hub.db.lock().unwrap();
member_vault(&conn, &caller, &req.vault, false)?
};
let (note, label) = names::parse_copy(&req.copy).ok_or_else(|| bad("that isn't a kept-both copy"))?;
let read = (|| -> Result<(Option<Vec<u8>>, Vec<u8>)> {
let repo = Repository::open_bare(hub.repo_path(id))?;
let main = main_ref(&repo)?.context("the vault is empty")?;
let tree = repo.find_reference(&main)?.peel_to_tree()?;
let blob = |p: &str| -> Result<Option<Vec<u8>>> {
Ok(match tree.get_path(Path::new(p)) {
Ok(e) => Some(repo.find_blob(e.id())?.content().to_vec()),
Err(_) => None,
})
};
Ok((blob(&note)?, blob(&req.copy)?.context("that copy isn't in the vault any more")?))
})()?;
let text = |b: &[u8]| -> Option<String> {
if b.len() > 200_000 || b.iter().take(8000).any(|&c| c == 0) { None } else { Some(String::from_utf8_lossy(b).into_owned()) }
};
Ok(Json(json!({
"note": note, "copy": req.copy, "label": label,
"note_text": read.0.as_deref().and_then(text), "copy_text": text(&read.1),
"note_exists": read.0.is_some()
})))
}
#[derive(Deserialize)]
pub struct ResolveReq {
vault: String,
copy: String,
/// note (the version in place), copy (the version kept beside it), or both (as separate notes)
keep: String,
}
/// Tidies a kept-both pair on the hub's copy; every device receives it as a normal change.
pub async fn resolve(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<ResolveReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
let (id, vault) = {
let conn = hub.db.lock().unwrap();
member_vault(&conn, &caller, &req.vault, true)?
};
let (note, label) = names::parse_copy(&req.copy).ok_or_else(|| bad("that isn't a kept-both copy"))?;
let done = (|| -> Result<String> {
let repo = Repository::open_bare(hub.repo_path(id))?;
let main = main_ref(&repo)?.context("the vault is empty")?;
let tip = repo.find_reference(&main)?.peel_to_commit()?;
let tree = tip.tree()?;
let copy = tree.get_path(Path::new(&req.copy)).context("that copy isn't in the vault any more")?;
let mode = if copy.filemode() == 0o100755 { FileMode::BlobExecutable } else { FileMode::Blob };
let mut update = TreeUpdateBuilder::new();
update.remove(req.copy.as_str());
let what = match req.keep.as_str() {
"note" => format!("kept the version in place of {note}"),
"copy" => {
update.upsert(note.as_str(), copy.id(), mode);
format!("kept {label}'s version of {note}")
}
"both" => {
let new = (1..)
.map(|n| names::kept_name(&note, &label, n))
.find(|p| tree.get_path(Path::new(p)).is_err())
.unwrap();
update.upsert(new.as_str(), copy.id(), mode);
format!("kept both versions of {note} ({new})")
}
_ => anyhow::bail!("keep note, copy or both"),
};
let new_tree = repo.find_tree(update.create_updated(&repo, &tree)?)?;
let sig = Signature::now(&format!("{} (web)", caller.person), "web@lune.device")?;
let commit = repo.commit(None, &sig, &sig, &format!("Tidied {note}"), &new_tree, &[&tip])?;
// Only if nobody shared something in the meantime; otherwise the person tries again.
repo.reference_matching(&main, commit, true, tip.id(), "lune: tidied on the canvas")
.context("the vault changed just now — try again")?;
Ok(what)
})()?;
let conn = hub.db.lock().unwrap();
db::log(&conn, &caller.who(), "tidied", &format!("{vault}: {done}"))?;
Ok(Json(json!({ "message": format!("Done — {done}. Every device gets it on its next sync.") })))
}

View File

@@ -311,7 +311,7 @@ pub async fn departure_done(State(hub): State<Shared>, headers: HeaderMap, Json(
}
/// The vault's main line: whatever HEAD points to, or the only branch there is.
fn main_ref(repo: &Repository) -> Result<Option<String>> {
pub fn main_ref(repo: &Repository) -> Result<Option<String>> {
if let Ok(head) = repo.find_reference("HEAD")
&& let Some(target) = head.symbolic_target().ok().flatten()
&& repo.find_reference(target).is_ok()

View File

@@ -3,6 +3,7 @@
mod api;
mod db;
mod git;
mod health;
mod hook;
mod leave;
mod web;
@@ -102,6 +103,10 @@ async fn serve() -> Result<()> {
.route("/api/web/link", post(web::link))
.route("/api/web/signout", post(web::signout))
.route("/api/canvas", get(web::canvas))
.route("/api/report", post(health::report))
.route("/api/nudge", post(health::nudge))
.route("/api/tidy/compare", post(health::compare))
.route("/api/tidy/resolve", post(health::resolve))
.route("/api/invites/grant", post(web::invite_grant))
.route("/api/devices/rename", post(web::rename_device))
.route("/signin/{token}", get(web::signin_link))

View File

@@ -133,7 +133,28 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
if manage {
managed.push(*id);
}
vaults.push(json!({ "id": format!("v{id}"), "name": name, "can_manage": manage, "delete_from_devices": delete_files }));
let tidy: Vec<Value> = crate::health::kept_both(&hub.repo_path(*id))
.unwrap_or_default()
.into_iter()
.map(|(note, copy, label)| json!({ "note": note, "copy": copy, "label": label }))
.collect();
// Handovers waiting for a decision, and devices that haven't reported in yet (managers only).
let handovers: Vec<Value> = if manage {
let mut stmt = conn.prepare(
"SELECT d.id, a.name, dev.label, d.state FROM departures d JOIN accounts a ON a.id = d.account_id
JOIN devices dev ON dev.id = d.device_id WHERE d.vault_id = ?1 AND d.state IN ('waiting', 'received') ORDER BY d.id",
)?;
stmt.query_map([id], |r| {
Ok(json!({ "id": r.get::<_, i64>(0)?, "person": r.get::<_, String>(1)?, "device": r.get::<_, String>(2)?, "state": r.get::<_, String>(3)? }))
})?
.collect::<Result<_, _>>()?
} else {
vec![]
};
vaults.push(json!({
"id": format!("v{id}"), "name": name, "can_manage": manage, "delete_from_devices": delete_files,
"tidy": tidy, "handovers": handovers
}));
}
let visible: Vec<i64> = vault_rows.iter().map(|v| v.0).collect();
@@ -148,21 +169,28 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
let mut people = vec![];
{
let mut stmt = conn.prepare("SELECT id, name, owner FROM accounts WHERE disabled = 0 ORDER BY created, id")?;
let rows: Vec<(i64, String, bool)> = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?;
for (id, name, owner) in rows {
// The owner also sees people removed from the team (dimmed, restorable).
let mut stmt = conn.prepare("SELECT id, name, owner, disabled FROM accounts WHERE disabled = 0 OR ?1 ORDER BY created, id")?;
let rows: Vec<(i64, String, bool, bool)> =
stmt.query_map([caller.owner], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))?.collect::<Result<_, _>>()?;
for (id, name, owner, removed) in rows {
// Devices: your own, the owner sees all, managers see their members' (blueprint J6).
let shares_managed = members.iter().any(|m| {
m["person"] == format!("a{id}") && managed.iter().any(|v| m["vault"] == format!("v{v}"))
});
let devices: Vec<Value> = if id == caller.account_id || caller.owner || shares_managed {
let mut d = conn.prepare("SELECT id, label FROM devices WHERE account_id = ?1 AND removed = 0 ORDER BY created")?;
d.query_map([id], |r| Ok(json!({ "id": r.get::<_, String>(0)?, "label": r.get::<_, String>(1)? })))?
.collect::<Result<_, _>>()?
let devices: Vec<(String, String)> = d.query_map([id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::<Result<_, _>>()?;
let mut out = vec![];
for (device_id, label) in devices {
let health = crate::health::device_health(&conn, &device_id)?;
out.push(json!({ "id": device_id, "label": label, "health": health }));
}
out
} else {
vec![]
};
people.push(json!({ "id": format!("a{id}"), "name": name, "owner": owner, "invited": false, "devices": devices }));
people.push(json!({ "id": format!("a{id}"), "name": name, "owner": owner, "invited": false, "removed": removed, "devices": devices }));
}
}
@@ -181,7 +209,7 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
for (v, role) in grants.iter().filter(|(v, _)| visible.contains(v)) {
members.push(json!({ "vault": format!("v{v}"), "person": key, "role": role }));
}
people.push(json!({ "id": key, "name": person, "owner": false, "invited": true, "devices": [] }));
people.push(json!({ "id": key, "name": person, "owner": false, "invited": true, "removed": false, "devices": [] }));
}
}

View File

@@ -311,3 +311,81 @@ fn canvas_session_and_undo_window() {
let res = agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap();
assert_eq!(res.status(), 401);
}
// ---- Milestone 6: freshness, Nudge, tidying on the canvas ----
#[test]
fn health_nudge_and_tidy() {
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap();
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap();
let codex = as_device(&url, &sen_w);
let devops = codex.create_vault("DevOps").unwrap();
let hermes_w = hub::login(&url, &codex.pair().unwrap(), "Hermes").unwrap();
// The same lines changed on two devices: the hub's copy keeps both.
as_device(&url, &sen_w);
let (cfg_a, _, _) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap();
let a = Vault::open(&cfg_a, "Codex").unwrap();
std::fs::write(a.root.join("runbook.md"), "restart: TODO\n").unwrap();
a.save_changes(None, &HashSet::new()).unwrap();
a.sync().unwrap();
let hermes = as_device(&url, &hermes_w);
let (cfg_h, _, _) = vault::add("DevOps", &tmp.path().join("hermes"), &devops.git_url, "Hermes").unwrap();
let h = Vault::open(&cfg_h, "Hermes").unwrap();
as_device(&url, &sen_w);
std::fs::write(a.root.join("runbook.md"), "restart: systemctl\n").unwrap();
a.save_changes(None, &HashSet::new()).unwrap();
a.sync().unwrap();
as_device(&url, &hermes_w);
std::fs::write(h.root.join("runbook.md"), "restart: docker\n").unwrap();
h.save_changes(None, &HashSet::new()).unwrap();
h.sync().unwrap();
// Codex reports something waiting; Hermes never reports.
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 }])
.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": codex.pair().unwrap() })).unwrap();
let session = res.headers().get("set-cookie").unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
let get = |path: &str| -> serde_json::Value {
agent.get(format!("{url}{path}")).header("Cookie", &session).header("X-Lune", "1").call().unwrap().body_mut().read_json().unwrap()
};
let post = |path: &str, body: serde_json::Value| -> serde_json::Value {
agent.post(format!("{url}{path}")).header("Cookie", &session).header("X-Lune", "1").send_json(body).unwrap().body_mut().read_json().unwrap()
};
let canvas = get("/api/canvas");
let devices = canvas["people"][0]["devices"].as_array().unwrap().clone();
let status = |label: &str| devices.iter().find(|d| d["label"] == label).unwrap()["health"]["status"].clone();
assert_eq!(status("Codex"), "behind");
assert_eq!(status("Hermes"), "offline");
let tidy = canvas["vaults"][0]["tidy"].as_array().unwrap().clone();
assert_eq!(tidy.len(), 1, "{canvas}");
let copy = tidy[0]["copy"].as_str().unwrap().to_string();
// Nudge reaches Hermes exactly once.
let hermes_id = devices.iter().find(|d| d["label"] == "Hermes").unwrap()["id"].as_str().unwrap().to_string();
post("/api/nudge", serde_json::json!({ "device_id": hermes_id }));
as_device(&url, &hermes_w);
assert!(hermes.me().unwrap().nudge);
assert!(!hermes.me().unwrap().nudge);
// Compare side by side, then keep the copy's version: the copy disappears everywhere.
let c = post("/api/tidy/compare", serde_json::json!({ "vault": "DevOps", "copy": copy }));
assert_eq!(c["note_text"], "restart: systemctl\n");
assert_eq!(c["copy_text"], "restart: docker\n");
let r = post("/api/tidy/resolve", serde_json::json!({ "vault": "DevOps", "copy": copy, "keep": "copy" }));
assert!(r["message"].as_str().unwrap().contains("kept Hermes's version"), "{r}");
as_device(&url, &sen_w);
a.save_changes(None, &HashSet::new()).unwrap();
a.sync().unwrap();
assert_eq!(std::fs::read(a.root.join("runbook.md")).unwrap(), b"restart: docker\n");
assert!(!a.root.join(&copy).exists());
assert!(get("/api/canvas")["vaults"][0]["tidy"].as_array().unwrap().is_empty());
}