From 8be559817c334b3e2e6ce1bd98779267258f51f6 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Thu, 29 Oct 2026 09:47:28 +0700 Subject: [PATCH] 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 --- cli/src/main.rs | 3 + core/src/hub.rs | 18 +++ core/src/membership.rs | 28 +++++ core/src/runner.rs | 7 ++ docs/SPEC.md | 48 ++++---- hub/src/api.rs | 9 +- hub/src/db.rs | 11 ++ hub/src/health.rs | 230 +++++++++++++++++++++++++++++++++++ hub/src/leave.rs | 2 +- hub/src/main.rs | 5 + hub/src/web.rs | 44 +++++-- hub/tests/hub.rs | 78 ++++++++++++ web/src/Canvas.tsx | 268 +++++++++++++++++++++++++++++++++++++---- web/src/api.ts | 36 ++++++ web/src/styles.css | 14 +++ 15 files changed, 744 insertions(+), 57 deletions(-) create mode 100644 hub/src/health.rs diff --git a/cli/src/main.rs b/cli/src/main.rs index fd4efec..73ce24a 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -584,6 +584,9 @@ fn run() -> Result<()> { Ok(msgs) => { hub_said.clear(); msgs.iter().for_each(|m| log_line("hub", m)); + if let Err(e) = lune_core::membership::report(&config) { + log_line("hub", &format!("couldn't report health: {e:#}")); + } } Err(e) => { let msg = format!("can't check the hub: {e:#}"); diff --git a/core/src/hub.rs b/core/src/hub.rs index 29ed078..5b5aae0 100644 --- a/core/src/hub.rs +++ b/core/src/hub.rs @@ -32,6 +32,19 @@ pub struct Me { /// Vaults this device must leave (access ended). #[serde(default)] pub leaving: Vec, + /// Someone asked this device to share now (Nudge). + #[serde(default)] + pub nudge: bool, +} + +/// One vault's health, as a device reports it to the hub: counts only, never content. +#[derive(Debug, Serialize)] +pub struct VaultHealth { + pub vault_id: i64, + pub last_synced: Option, + pub waiting: usize, + pub held_secrets: usize, + pub holding: bool, } /// A vault this device has to hand over and leave (A6). @@ -186,6 +199,11 @@ impl HubLink { Ok(v["url"].as_str().unwrap_or_default().to_string()) } + pub fn report(&self, vaults: &[VaultHealth]) -> Result<()> { + let _: Value = self.post("/api/report", json!({ "vaults": vaults }))?; + Ok(()) + } + pub fn remove(&self, person: &str, vault: &str, without_saving: bool) -> Result { let v: Value = self.post("/api/remove", json!({"person": person, "vault": vault, "without_saving": without_saving}))?; Ok(v["devices"].as_u64().unwrap_or(0) as usize) diff --git a/core/src/membership.rs b/core/src/membership.rs index ff7b242..3ad5b3a 100644 --- a/core/src/membership.rs +++ b/core/src/membership.rs @@ -34,6 +34,16 @@ pub fn arrive(config: &mut Config) -> Result> { for d in &me.leaving { said.push(leave(config, &h, d)?); } + if me.nudge { + // Each vault's runner sees this and shares at once. + for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some()) { + let dir = state::lune_dir(&vc.path.join(".git")); + if dir.exists() { + std::fs::write(dir.join("nudge"), "")?; + } + } + said.push("Someone asked this device to share now — sharing".into()); + } for hv in me.vaults { if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) { @@ -72,6 +82,24 @@ pub fn arrive(config: &mut Config) -> Result> { Ok(said) } +/// Tells the hub how each of this device's hub vaults is doing (M6 freshness). +pub fn report(config: &Config) -> Result<()> { + let Some(h) = &config.hub else { return Ok(()) }; + let label = config.device_label(); + let mut out = vec![]; + for vc in config.vaults.iter().filter(|v| v.hub_vault.is_some()) { + let Ok(v) = Vault::open(vc, &label) else { continue }; + out.push(hub::VaultHealth { + vault_id: vc.hub_vault.unwrap(), + last_synced: state::SyncState::load(&v.git_dir).last_synced, + waiting: v.waiting_files().unwrap_or(0), + held_secrets: v.secret_holds().map(|n| n.len()).unwrap_or(0), + holding: !crate::guard::load(&v.git_dir).is_empty(), + }); + } + h.report(&out) +} + /// Leaves one vault: stop syncing, save, make read-only, hand over what wasn't shared, and once the /// hub has it, delete the folder if the app created it. pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result { diff --git a/core/src/runner.rs b/core/src/runner.rs index 1d8d13a..5e272a7 100644 --- a/core/src/runner.rs +++ b/core/src/runner.rs @@ -95,11 +95,18 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: let mut was_read_only = false; let mut announced: HashSet = HashSet::new(); let leaving = state::lune_dir(&vault.git_dir).join("leaving"); + let nudge = state::lune_dir(&vault.git_dir).join("nudge"); loop { if leaving.exists() { say("access to this vault ended — stopped syncing it"); return Ok(()); } + if nudge.exists() { + // Nudged from the canvas: save what has settled and share right away. + let _ = std::fs::remove_file(&nudge); + rescan_at = Instant::now(); + sync_at = Instant::now(); + } let first = rx.recv_timeout(Duration::from_millis(250)); for ev in first.into_iter().chain(rx.try_iter()) { match ev { diff --git a/docs/SPEC.md b/docs/SPEC.md index d948283..5c3c91f 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -153,40 +153,38 @@ Only the current milestone gets detailed below. The next one is detailed when th --- -## 6. Milestone 5 — Canvas for access +## 6. Milestone 6 — Canvas for health and leaving -Milestones 1–4 (sync, safety checks, the hub, taking access back) are built; their detail lives in the code and tests now. The canvas follows Sen's clickable prototype (team canvas artboard) and the X decisions. +Milestones 1–5 (sync, safety checks, the hub, taking access back, the canvas for access) are built; their detail lives in the code and tests now. ### Goal -The hub serves a web canvas where access is managed by touch: drag a vault onto a person to grant, pull a ribbon until it snaps to revoke (with Undo), and every gesture has a button in the details panel. Invites and device labels live here too. +Before you need someone's work, you can see whether it has reached the team, and ask for it. Everything that needs a human decision — a note changed in two places, a handover, removing someone from the team — can be done on the canvas, including from a phone. -### What Sen does -```bash -lunesync open # opens the canvas in the browser, already signed in -``` -Or on a phone / another browser: open the hub's address, type a code from `lunesync pair`. - -On the canvas: drag DevOps onto Alice (she gets Edit; change the role in the panel), pull the dot on a ribbon until it pinches and snaps (Undo for 8 s), **Invite person** (name + vaults → a one-time link to copy), rename or remove a device in a person's panel, switch **Float** / **Dock**, create a vault (owner), turn "delete from their devices" on or off per vault. +### What Sen does (on the canvas) +- Sees each person ringed by freshness and each device dotted the same way: green current, amber behind, grey offline (X6). A red dot means a possible secret was held back on that device. +- Opens a behind device: "4 changes not shared · 2 days" → **Nudge**. +- A vault shows "1 note to tidy" → **Compare** shows both versions side by side → keep one, or keep both. +- A vault shows a handover → see which notes it changes → **Keep** / **Discard**. A device that never came back → **Delete without saving**. +- A person → **Remove from team** (owner, asks to confirm, says how much unshared work will come back first). A removed person stays visible to the owner, dimmed, with **Restore** (gives a one-time sign-in link). ### Behavior -- **Sign-in (decided, §8)**: no passwords. `lunesync open` makes a one-time sign-in link (2 minutes) from a signed-in device; or type a pairing code on the hub's sign-in page. The session cookie lasts 30 days (HttpOnly, SameSite=Strict, Secure on HTTPS); signing out, or removal from the team, ends it. The canvas acts as the person ("Sen (web)" in the access log), never as a device: it holds no vault content. -- **What you see**: the owner sees every vault and person; others see the vaults they're in. Everyone sees the team's people (to grant). Devices are visible to their owner, the team owner, and managers of a vault the person is in. Gestures only work on vaults you manage. -- **Grant** = drop a vault on a person (Edit). Dropping on an invited person who hasn't joined yet adds it to their invite. No confirmation (X2). -- **Revoke** = pull a ribbon's dot until it snaps. The ribbon disappears and an 8 s Undo toast shows; the hub holds the removal until the window passes, so nothing reaches the person's devices before then. Then the M4 flow runs (handover, delete). -- **Panels (X1, X3, X11)**: overview (vaults, people, recent activity for the owner), vault (members with role and Remove, Give access, the delete-from-devices setting), person (devices: rename, remove; vaults). Back navigation remembers where a panel was opened from. Bottom sheet on phones. -- **Look**: X4–X8 as in the prototype — metaball ribbons with the goo filter, identity colors fading vault→person, focus with veils, Float (shared bobbing clock) and Dock, reduced motion respected. Status colors stay unused until M6. -- **Invite link in a browser** shows how to join (`lunesync join --name …`) instead of an error. -- The hub serves the canvas itself (built into the binary); nothing else to deploy. +- **Health reports**: while `lunesync run` is going, each device tells the hub every ~30 s, per vault: when it last synced, how many changes are waiting, and whether something is held (a big change, or a possible secret — counts only, never content). The hub knows work exists, not what it is. +- **Freshness**: current = reported in the last 2 minutes with nothing waiting; behind = something waiting or held; offline = not heard from in 2 minutes (shown with when it was last seen). A person's ring shows their worst device. +- **Nudge** reaches the device on its next check-in (~30 s): it saves what has settled and syncs at once. If something is held, the panel says so instead of pretending a nudge will help. +- **Tidy on the canvas** reads the two versions from the hub's copy of the vault (members only; Edit to decide). Keeping one, or both as separate notes, is a normal change on the hub that every device receives — same outcome as `lunesync tidy keep`. +- **Handovers on the canvas** are the M4 review (show / keep / discard / delete without saving), shown in the vault and person panels. +- **Remove from team / Restore** are the M4 flows; this is the only gesture on the canvas that asks for confirmation (X2). +- Status colors are used only for status; red only for a held secret (X6). ### Acceptance — Sen acts this out -1. `lunesync open` → the canvas, signed in. A phone signs in with a code. -2. Drag a vault onto a teammate: the vault arrives on their devices. Change their role in the panel. -3. Pull a ribbon until it snaps, press Undo: nothing changed on their devices. Pull again and wait: the M4 removal runs. -4. Invite a person with a vault; they join from the link; they appear on the canvas with their device. -5. Rename and remove a device from the panel; switch Float/Dock; everything works with buttons alone (keyboard). +1. Laptop offline with edits: its ring turns amber, then grey with "last seen"; back online it turns green on its own. +2. A behind laptop that's online but idle: **Nudge** → green within a minute. +3. Same lines edited on two devices: the vault shows 1 to tidy; compare side by side on the canvas; keep one; the copy disappears on every device. +4. Remove someone from a vault with unshared work: review and keep the handover on the canvas. +5. From a phone: remove someone from the team (confirm), see their devices leave; restore them. -### Out of scope for M5 -Freshness glow, Nudge, tidy and handover review, remove from team (M6). Desktop app (M7). +### Out of scope for M6 +Desktop app, tray, installers, updates (M7). Push notifications for Nudge (the next check-in is enough for now). ## 7. Open questions None open. diff --git a/hub/src/api.rs b/hub/src/api.rs index 7e9ff04..207b250 100644 --- a/hub/src/api.rs +++ b/hub/src/api.rs @@ -247,9 +247,16 @@ pub async fn me(State(hub): State, 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 }))) } diff --git a/hub/src/db.rs b/hub/src/db.rs index 8f09a99..3b6f669 100644 --- a/hub/src/db.rs +++ b/hub/src/db.rs @@ -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 { ("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}"), []); } diff --git a/hub/src/health.rs b/hub/src/health.rs new file mode 100644 index 0000000..2f5ff3e --- /dev/null +++ b/hub/src/health.rs @@ -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, + waiting: i64, + held_secrets: i64, + holding: bool, +} + +#[derive(Deserialize)] +pub struct ReportReq { + vaults: Vec, +} + +/// 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, headers: HeaderMap, Json(req): Json) -> 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 { + let last_seen: Option = 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, 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, headers: HeaderMap, Json(req): Json) -> 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> { + 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, headers: HeaderMap, Json(req): Json) -> 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)> { + 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>> { + Ok(match tree.get_path(Path::new(p)) { + Ok(e) => Some(repo.find_blob(e.id())?.content().to_vec()), + Err(_) => None, + }) + }; + Ok((blob(¬e)?, blob(&req.copy)?.context("that copy isn't in the vault any more")?)) + })()?; + let text = |b: &[u8]| -> Option { + 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, headers: HeaderMap, Json(req): Json) -> 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 { + 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(¬e, &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.") }))) +} diff --git a/hub/src/leave.rs b/hub/src/leave.rs index 78cbbf5..54fbee1 100644 --- a/hub/src/leave.rs +++ b/hub/src/leave.rs @@ -311,7 +311,7 @@ pub async fn departure_done(State(hub): State, headers: HeaderMap, Json( } /// The vault's main line: whatever HEAD points to, or the only branch there is. -fn main_ref(repo: &Repository) -> Result> { +pub fn main_ref(repo: &Repository) -> Result> { if let Ok(head) = repo.find_reference("HEAD") && let Some(target) = head.symbolic_target().ok().flatten() && repo.find_reference(target).is_ok() diff --git a/hub/src/main.rs b/hub/src/main.rs index 6ab059a..95139e9 100644 --- a/hub/src/main.rs +++ b/hub/src/main.rs @@ -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)) diff --git a/hub/src/web.rs b/hub/src/web.rs index 605b28b..698d783 100644 --- a/hub/src/web.rs +++ b/hub/src/web.rs @@ -133,7 +133,28 @@ pub async fn canvas(State(hub): State, 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 = 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 = 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::>()? + } 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 = vault_rows.iter().map(|v| v.0).collect(); @@ -148,21 +169,28 @@ pub async fn canvas(State(hub): State, 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::>()?; - 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::>()?; + 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 = 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::>()? + let devices: Vec<(String, String)> = d.query_map([id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::>()?; + 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, 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": [] })); } } diff --git a/hub/tests/hub.rs b/hub/tests/hub.rs index 06bef28..c5754c3 100644 --- a/hub/tests/hub.rs +++ b/hub/tests/hub.rs @@ -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(©).exists()); + assert!(get("/api/canvas")["vaults"][0]["tidy"].as_array().unwrap().is_empty()); +} diff --git a/web/src/Canvas.tsx b/web/src/Canvas.tsx index b77d76a..f6f2cea 100644 --- a/web/src/Canvas.tsx +++ b/web/src/Canvas.tsx @@ -3,7 +3,7 @@ // also has a button in the details panel (X3). import { useEffect, useMemo, useRef, useState } from 'react'; -import { api, type CanvasData, type LogEntry, type Member, type Person, type Role, type Vault } from './api'; +import { api, type CanvasData, type Comparison, type Health, type LogEntry, type Member, type Person, type Role, type Status, type Vault } from './api'; import { HANDLE_T, W, boardHeight, circle, easeBack, lerp, personColor, positions, ribbon, roundRect, vaultColor, type Layout, type Pt, @@ -15,6 +15,37 @@ const roleName = (r: Role) => r.charAt(0).toUpperCase() + r.slice(1); const plural = (n: number, word: string, many = word + 's') => `${n} ${n === 1 ? word : many}`; const keyOf = (m: { vault: string; person: string }) => `${m.vault}|${m.person}`; +/** Status colors are reserved for status (X6): green current, amber behind or needs a decision, grey offline, + * red only for a possible secret held back. */ +const STATUS: Record = { current: '#2E8B5F', behind: '#E09A2B', offline: '#A9A5B6' }; +const STATUS_WORDS: Record = { current: 'Current', behind: 'Behind', offline: 'Offline' }; +const PILL: Record = { current: ['#E3F2EA', '#1F6B47'], behind: ['#FBEBD3', '#7A4500'], offline: ['#EEECF2', '#5C5770'] }; +const SECRET_RED = '#C8323B'; + +/** A person's freshness is their worst device. */ +function worst(p: Person): Status { + if (!p.devices.length) return 'offline'; + if (p.devices.some((d) => d.health.status === 'behind')) return 'behind'; + if (p.devices.some((d) => d.health.status === 'offline')) return 'offline'; + return 'current'; +} + +function ago(unix: number | null): string { + if (!unix) return 'never'; + const s = Math.max(0, Date.now() / 1000 - unix); + if (s < 90) return 'just now'; + if (s < 3600) return `${Math.round(s / 60)} min ago`; + if (s < 86400) return `${Math.round(s / 3600)} h ago`; + return plural(Math.round(s / 86400), 'day') + ' ago'; +} + +function healthLine(h: Health): string { + const waiting = h.waiting > 0 ? `${plural(h.waiting, 'change')} not shared` : ''; + if (h.status === 'offline') return `Offline · last seen ${ago(h.last_seen)}${waiting ? ' · ' + waiting : ''}`; + if (h.status === 'behind') return [waiting, h.last_synced ? `last synced ${ago(h.last_synced)}` : ''].filter(Boolean).join(' · ') || 'Something is held on this device'; + return `Synced ${ago(h.last_synced)}`; +} + type Sel = | { kind: 'overview'; back?: Sel } | { kind: 'vault'; id: string; back?: Sel } @@ -25,6 +56,12 @@ type Drag = | { kind: 'detach'; key: string; p: Pt } | { kind: 'snap'; key: string; p: Pt }; type Toast = { text: string; undo?: () => void }; +type Sheet = + | 'invite' + | 'vault' + | { kind: 'compare'; vault: Vault; copy: string } + | { kind: 'team'; p: Person } + | { kind: 'restored'; p: Person; link: string }; function store(key: string, value?: string): string | null { try { @@ -45,7 +82,7 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: const [drag, setDrag] = useState(null); const [pinched, setPinched] = useState<{ key: string; p: Pt; t: number } | null>(null); const [toast, setToast] = useState(null); - const [sheet, setSheet] = useState<'invite' | 'vault' | null>(null); + const [sheet, setSheet] = useState(null); const [onboarded, setOnboarded] = useState(store('lune.onboarded') === '1'); const [hidden, setHidden] = useState>(new Set()); const [extra, setExtra] = useState([]); @@ -203,6 +240,7 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: const target = (p: Pt) => { let best: string | null = null, bd = 1e9; for (const pr of people) { + if (pr.removed) continue; const q = pos(pr.id), d = Math.hypot(p.x - q.x, p.y - q.y); if (d < bd) { bd = d; best = pr.id; } } @@ -278,6 +316,16 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: vaults.forEach((v, i) => { const p = pos(v.id), delay = (i * 0.7).toFixed(1), vo = relV(v.id) ? 1 : 0.35; + // Amber means a decision is waiting (X6): notes to tidy, handovers to review. + const review = v.handovers.filter((h) => h.state === 'received').length, tidy = v.tidy.length; + const decide = review + tidy; + if (decide > 0) { + labels.push({ + text: tidy && !review ? `${tidy} to tidy` : review && !tidy ? plural(review, 'handover') : `${decide} to decide`, + style: { ...pct(p.x + 34, p.y - 40), transform: 'translate(-50%,-50%)', opacity: vo }, + inner: { display: 'inline-block', whiteSpace: 'nowrap', fontWeight: 700, fontSize: 'max(1.05cqw, 9px)', color: '#7A4500', background: '#FBEBD3', border: '1px solid #E09A2B', borderRadius: 999, padding: '0.15em 0.7em', animationDelay: `${delay}s` }, + }); + } blobs.push({ d: roundRect(p.x, p.y, 138, 70, 26), fill: vaultColor(v.id).fill, delay, op: focus && relV(v.id) ? 1 : 0 }); labels.push({ text: v.name, @@ -286,11 +334,11 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: }); }); people.forEach((pr, i) => { - const p = pos(pr.id), delay = (0.35 + i * 0.6).toFixed(1), po = relP(pr.id) ? 1 : 0.35; - if (!pr.invited) blobs.push({ d: circle(p.x, p.y, 38), fill: personColor(pr.id).fill, delay, op: focus && relP(pr.id) ? 1 : 0 }); + const p = pos(pr.id), delay = (0.35 + i * 0.6).toFixed(1), po = pr.removed ? 0.45 : relP(pr.id) ? 1 : 0.35; + if (!pr.invited && !pr.removed) blobs.push({ d: circle(p.x, p.y, 38), fill: personColor(pr.id).fill, delay, op: focus && relP(pr.id) ? 1 : 0 }); labels.push({ text: pr.name.charAt(0).toUpperCase(), style: { ...pct(p.x, p.y), transform: 'translate(-50%,-50%)', opacity: po }, inner: { display: 'inline-block', fontWeight: 700, fontSize: 'max(2cqw, 12px)', animationDelay: `${delay}s` } }); labels.push({ - text: pr.invited ? `${pr.name} · invited` : pr.name, + text: pr.invited ? `${pr.name} · invited` : pr.removed ? `${pr.name} · removed` : pr.name, style: { ...pct(p.x, p.y + 48), transform: 'translate(-50%,-50%)', opacity: po }, inner: { display: 'inline-block', whiteSpace: 'nowrap', fontSize: 'max(1.3cqw, 10px)', animationDelay: `${delay}s` }, }); @@ -446,12 +494,12 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: return ( - + 0 ? SECRET_RED : STATUS[d.health.status]} stroke="#FFFFFF" strokeWidth="2" /> ); })} { if (!drag) setSel({ kind: 'person', id: pr.id }); }} onPointerEnter={() => enter('person', pr.id)} onPointerLeave={leave} style={{ cursor: 'pointer' }}> - + @@ -490,7 +538,13 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: )} -
{hint && {hint}}
+
+ {hint && {hint}} + + {(Object.keys(STATUS) as Status[]).map((s) => {STATUS_WORDS[s]})} + Possible secret held + +
{!onboarded && manages && vaults.length > 0 && (
@@ -508,16 +562,38 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: {sel.kind === 'overview' && setSel(null)} newVault={() => setSheet('vault')} signOut={onSignOut} />} {sel.kind === 'vault' && vault(sel.id) && ( setSel(null)} - cycleRole={cycleRole} remove={(m) => revoke(keyOf(m))} grant={grant} + cycleRole={cycleRole} remove={(m) => revoke(keyOf(m))} grant={grant} run={run} + compare={(copy) => setSheet({ kind: 'compare', vault: vault(sel.id), copy })} toggleDelete={(v) => run(() => api.vaultSetting(v.name, !v.delete_from_devices), v.delete_from_devices ? `Removed people keep a read-only copy of ${v.name}.` : `Removed people's copies of ${v.name} are deleted from their devices.`)} /> )} {sel.kind === 'person' && person(sel.id) && ( - setSel(null)} run={run} /> + setSel(null)} run={run} + removeFromTeam={(p) => setSheet({ kind: 'team', p })} + restore={(p) => api.teamRestore(p.name).then((r) => { setSheet({ kind: 'restored', p, link: r.link }); reload(); }).catch((e) => say(e.message))} /> )} )} {sheet === 'invite' && v.can_manage)} owner={data.me.owner} close={() => { setSheet(null); reload(); }} />} + {typeof sheet === 'object' && sheet?.kind === 'compare' && ( + m.vault === sheet.vault.id && m.person === data.me.id)?.role ?? '')} + close={() => setSheet(null)} + resolve={(keep) => { const s = sheet; setSheet(null); run(async () => say((await api.resolve(s.vault.name, s.copy, keep)).message)); }} /> + )} + {typeof sheet === 'object' && sheet?.kind === 'team' && ( + setSheet(null)} + confirm={() => { const p = sheet.p; setSheet(null); setSel({ kind: 'person', id: p.id }); run(() => api.teamRemove(p.name), `${p.name} was removed from the team. Their devices send unshared work, then delete every vault copy.`); }} /> + )} + {typeof sheet === 'object' && sheet?.kind === 'restored' && ( +
{ if (e.target === e.currentTarget) setSheet(null); }}> +
+

{sheet.p.name} is back on the team

+

They start with no vaults — give them some by dragging. Send them this one-time sign-in link (7 days):

+
lunesync join {sheet.link} --name "<their device>"
+
+
+
+ )} {sheet === 'vault' && setSheet(null)} create={(name) => { setSheet(null); run(() => api.createVault(name), `${name} is ready. Drag it onto people to share it.`); }} />}
@@ -534,7 +610,8 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: function Avatar({ p }: { p: Person }) { const c = personColor(p.id); - return {p.name.charAt(0).toUpperCase()}; + const ring = p.invited ? c.ring : p.removed ? STATUS.offline : STATUS[worst(p)]; + return {p.name.charAt(0).toUpperCase()}; } function Swatch({ v }: { v: Vault }) { @@ -574,8 +651,9 @@ function Overview({ data, members, log, open, close, newVault, signOut }: { {p.name} - {p.invited ? 'Invited, not joined yet' : p.owner ? 'Team owner' : plural(members.filter((m) => m.person === p.id).length, 'vault')} + {p.invited ? 'Invited, not joined yet' : p.removed ? 'Removed from team' : p.owner ? 'Team owner' : plural(members.filter((m) => m.person === p.id).length, 'vault')} + {!p.invited && !p.removed && (() => { const st = worst(p), [bg, fg] = PILL[st]; return {STATUS_WORDS[st]}; })()} ))} @@ -598,12 +676,13 @@ function Overview({ data, members, log, open, close, newVault, signOut }: { ); } -function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete }: { +function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete, run, compare }: { v: Vault; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void; cycleRole: (m: Member) => void; remove: (m: Member) => void; grant: (v: string, p: string) => void; toggleDelete: (v: Vault) => void; + run: (action: () => Promise, ok?: string) => Promise; compare: (copy: string) => void; }) { const inVault = members.filter((m) => m.vault === v.id); - const outside = data.people.filter((p) => !inVault.some((m) => m.person === p.id)); + const outside = data.people.filter((p) => !p.removed && !inVault.some((m) => m.person === p.id)); const mine = inVault.find((m) => m.person === data.me.id); return ( <> @@ -612,6 +691,19 @@ function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, t
{!v.can_manage && mine &&
You have {roleName(mine.role)} access. People with Manage decide who else can sync it.
} + {v.tidy.length > 0 && ( +
+ {plural(v.tidy.length, 'note')} to tidy + Changed in two places at once. Both versions are kept, so nothing is lost. + {v.tidy.map((t) => ( +
+ {t.note} + +
+ ))} +
+ )} + {v.handovers.map((h) => )}

People with access

{inVault.map((m) => { @@ -654,14 +746,15 @@ function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, t ); } -function PersonPanel({ p, data, members, open, close, run }: { +function PersonPanel({ p, data, members, open, close, run, removeFromTeam, restore }: { p: Person; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void; - run: (action: () => Promise, ok?: string) => Promise; + run: (action: () => Promise, ok?: string) => Promise; removeFromTeam: (p: Person) => void; restore: (p: Person) => void; }) { const [renaming, setRenaming] = useState<{ id: string; value: string } | null>(null); const theirs = members.filter((m) => m.person === p.id); const canEditDevices = p.id === data.me.id || data.me.owner; - const eyebrow = p.invited ? 'Invited' : p.owner ? 'Team owner' : 'Team member'; + const eyebrow = p.invited ? 'Invited' : p.removed ? 'Removed from team' : p.owner ? 'Team owner' : 'Team member'; + const leaving = data.vaults.flatMap((v) => v.handovers.filter((h) => h.person === p.name && h.state === 'waiting').map((h) => ({ ...h, vault: v }))); return ( <>
@@ -669,7 +762,24 @@ function PersonPanel({ p, data, members, open, close, run }: {
{p.invited &&
{p.name} hasn't joined yet. Vaults you give them now arrive once they join with their invite link.
} - {!p.invited && ( + {p.removed && ( +
+

This account is disabled. Past changes keep this name in history.

+ {data.me.owner && } +
+ )} + {leaving.length > 0 && ( +
+ Leaving + {leaving.map((h) => ( +
+ {h.device} hasn't reported in since losing {h.vault.name}. Its unshared work comes back when it's next online. + +
+ ))} +
+ )} + {!p.invited && !p.removed && (

Devices

{p.devices.length === 0 &&

{canEditDevices ? 'No devices yet.' : "Only their vault managers see someone's devices."}

} @@ -683,13 +793,24 @@ function PersonPanel({ p, data, members, open, close, run }: { ) : ( -
- - {d.label} -
+ <> +
+ + {d.label} + {STATUS_WORDS[d.health.status]} +
+ {healthLine(d.health)} + {d.health.held_secrets > 0 && ( + {plural(d.health.held_secrets, 'note')} held back: possible secret, not shared. Its owner decides with lunesync held. + )} + {d.health.holding && A big change is held here, waiting for its owner to share or undo it.} + )} {canEditDevices && renaming?.id !== d.id && (
+ {d.health.waiting > 0 && ( + + )}
@@ -710,10 +831,113 @@ function PersonPanel({ p, data, members, open, close, run }: { ); })}
+ {data.me.owner && !p.owner && !p.removed && !p.invited && ( +
+ +

Ends every vault and device for this person. The account is disabled and can be restored.

+
+ )} ); } +/** A handover waiting for a manager: received work to review, or a device that hasn't reported in. */ +function HandoverCard({ h, vault, run }: { h: Vault['handovers'][number]; vault: Vault; run: (action: () => Promise, ok?: string) => Promise }) { + const [files, setFiles] = useState(null); + if (h.state === 'waiting') { + return ( +
+ {h.person} is leaving {vault.name} + {h.device} hasn't reported in yet. Its unshared work comes to you when it's next online. + +
+ ); + } + return ( +
+ {h.person}'s last changes from {h.device} + These arrived in a final sync after the removal. Review before they join the vault. + {files === null ? ( + + ) : ( +
    {files.map((f) =>
  • {f}
  • )}
+ )} +
+ + +
+
+ ); +} + +/** Both versions of a note side by side (J3); lines only in one version are highlighted. */ +function CompareDialog({ vault, copy, canEdit, close, resolve }: { + vault: Vault; copy: string; canEdit: boolean; close: () => void; resolve: (keep: 'note' | 'copy' | 'both') => void; +}) { + const [c, setC] = useState(null); + const [error, setError] = useState(''); + useEffect(() => { api.compare(vault.name, copy).then(setC).catch((e) => setError(e.message)); }, [vault, copy]); + const column = (title: string, text: string | null, other: string | null, tint: string) => { + const others = new Set((other ?? '').split('\n')); + return ( +
+
{title}
+
+ {text === null ? Not shown (not a text note, or very large). + : text.split('\n').map((line, i) =>
{line || '\u00a0'}
)} +
+
+ ); + }; + return ( +
{ if (e.target === e.currentTarget) close(); }}> +
+
{vault.name} · {c?.note ?? ''}

Two versions of the same lines

+ {error &&

{error}

} + {c && ( +
+ {column(c.note_exists ? 'In the vault' : 'In the vault (removed since)', c.note_text, c.copy_text, '#FBEBD3')} + {column(`${c.label}'s version · kept beside it`, c.copy_text, c.note_text, '#E8E1FB')} +
+ )} + {c && !canEdit &&

You have read access, so you can look but not choose.

} +
+ + {c && canEdit && ( + <> + + {c.note_exists && } + + + )} +
+
+
+ ); +} + +/** The only gesture on the canvas that asks first (X2, A8). */ +function TeamDialog({ p, data, members, close, confirm }: { p: Person; data: CanvasData; members: Member[]; close: () => void; confirm: () => void }) { + const theirs = members.filter((m) => m.person === p.id).map((m) => data.vaults.find((v) => v.id === m.vault)?.name ?? ''); + const waiting = p.devices.reduce((n, d) => n + d.health.waiting, 0); + return ( +
{ if (e.target === e.currentTarget) close(); }}> +
+

Remove {p.name} from the team?

+

+ {p.name} is in {plural(theirs.length, 'vault')}{theirs.length ? ` (${theirs.join(', ')})` : ''} on {plural(p.devices.length, 'device')}. All access ends and every vault copy is deleted from those devices. +

+ {waiting > 0 &&

{plural(waiting, 'change')} haven't been shared yet. They'll be sent to the team for review before anything is deleted.

} +

The account is disabled, not deleted, and can be restored. Past changes keep {p.name}'s name in history. Copies made elsewhere can't be recalled.

+
+ + +
+
+
+ ); +} + function InviteDialog({ vaults, owner, close }: { vaults: Vault[]; owner: boolean; close: () => void }) { const [name, setName] = useState(''); const [picked, setPicked] = useState>(new Set()); diff --git a/web/src/api.ts b/web/src/api.ts index 8d98e44..6156d7d 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -7,11 +7,27 @@ export interface Vault { name: string; can_manage: boolean; delete_from_devices: boolean; + /** Notes kept in two versions (S4), from the hub's copy. */ + tidy: { note: string; copy: string; label: string }[]; + /** Departures needing a manager: waiting for the device, or received for review. */ + handovers: { id: number; person: string; device: string; state: 'waiting' | 'received' }[]; +} + +export type Status = 'current' | 'behind' | 'offline'; + +export interface Health { + status: Status; + last_seen: number | null; + last_synced: number | null; + waiting: number; + held_secrets: number; + holding: boolean; } export interface Device { id: string; label: string; + health: Health; } export interface Person { @@ -20,6 +36,8 @@ export interface Person { owner: boolean; /** Invited but not joined yet. */ invited: boolean; + /** Removed from the team (shown to the owner, restorable). */ + removed: boolean; devices: Device[]; } @@ -45,6 +63,15 @@ export interface LogEntry { detail: string; } +export interface Comparison { + note: string; + copy: string; + label: string; + note_text: string | null; + copy_text: string | null; + note_exists: boolean; +} + export class SignedOut extends Error {} async function call(method: string, path: string, body?: unknown): Promise { @@ -77,5 +104,14 @@ export const api = { vaultSetting: (vault: string, deleteFromDevices: boolean) => call('POST', '/api/vaults/settings', { vault, delete_from_devices: deleteFromDevices }), renameDevice: (deviceId: string, label: string) => call('POST', '/api/devices/rename', { device_id: deviceId, label }), + nudge: (deviceId: string) => call('POST', '/api/nudge', { device_id: deviceId }), + compare: (vault: string, copy: string) => call('POST', '/api/tidy/compare', { vault, copy }), + resolve: (vault: string, copy: string, keep: 'note' | 'copy' | 'both') => + call<{ message: string }>('POST', '/api/tidy/resolve', { vault, copy, keep }), + handoverShow: (id: number) => call('POST', '/api/handovers/show', { id }), + handoverDecide: (id: number, decision: 'keep' | 'discard' | 'skip') => + call<{ message: string }>('POST', '/api/handovers/decide', { id, decision }), + teamRemove: (person: string) => call('POST', '/api/team/remove', { person }), + teamRestore: (person: string) => call<{ link: string }>('POST', '/api/team/restore', { person }), removeDevice: (deviceId: string) => call('POST', '/api/device/remove', { device_id: deviceId }), }; diff --git a/web/src/styles.css b/web/src/styles.css index db600ff..abe55a0 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -102,6 +102,19 @@ button:focus-visible, input:focus-visible, a:focus-visible { outline: 3px solid .tip { display: flex; gap: 10px; font-size: 14px; line-height: 1.45; } .tipn { width: 22px; height: 22px; border-radius: 50%; background: var(--accent-tint); color: #4B2FB0; font-weight: 700; font-size: 12px; display: flex; align-items: center; justify-content: center; flex: none; } +.note.amber { background: #FBEBD3; border-color: #EBC28A; } +.warn-box { margin: 0; font-size: 14px; line-height: 1.5; background: #FBEBD3; border-radius: 12px; padding: 10px 12px; } +.secret-note { font-size: 13px; line-height: 1.45; color: #8E1F27; background: #FBEDED; border-radius: 10px; padding: 6px 10px; } +.pill { font-size: 12px; font-weight: 700; padding: 2px 9px; border-radius: 999px; flex: none; } +.files { margin: 0; padding-left: 18px; font-family: ui-monospace, Menlo, monospace; font-size: 13px; } +.legend { display: inline-flex; gap: 14px; flex-wrap: wrap; } +.legend span { display: inline-flex; align-items: center; gap: 6px; } +.legend i { width: 10px; height: 10px; border-radius: 50%; display: inline-block; } +.dialog.wide { max-width: 820px; } +.cmp { display: flex; flex-wrap: wrap; gap: 12px; } +.cmp-col { flex: 1 1 300px; min-width: 0; border: 1px solid var(--line); border-radius: 16px; overflow: hidden; } +.cmp-head { padding: 10px 14px; background: var(--accent-soft); font-weight: 700; font-size: 14px; } +.cmp-body { padding: 10px 14px; font-family: ui-monospace, Menlo, monospace; font-size: 13px; line-height: 1.7; overflow-x: auto; max-height: 50vh; overflow-y: auto; white-space: pre; } .scrim { position: fixed; inset: 0; background: rgba(34, 30, 51, 0.38); display: flex; align-items: center; justify-content: center; padding: 16px; z-index: 20; } .dialog { background: #FFFFFF; border-radius: 24px; padding: 24px; width: 100%; max-width: 460px; display: flex; flex-direction: column; gap: 14px; max-height: calc(100dvh - 32px); overflow-y: auto; } .dialog h2 { margin: 0; font-size: 22px; } @@ -121,6 +134,7 @@ button:focus-visible, input:focus-visible, a:focus-visible { outline: 3px solid .panel { top: auto; left: 8px; right: 8px; bottom: 8px; width: auto; max-width: none; height: 56vh; animation-name: slideup; } .open .bottombar { display: none; } .coach { bottom: 16px; } + .legend { display: none; } } @media (prefers-reduced-motion: reduce) { .bob { animation: none; }