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

@@ -584,6 +584,9 @@ fn run() -> Result<()> {
Ok(msgs) => { Ok(msgs) => {
hub_said.clear(); hub_said.clear();
msgs.iter().for_each(|m| log_line("hub", m)); 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) => { Err(e) => {
let msg = format!("can't check the hub: {e:#}"); let msg = format!("can't check the hub: {e:#}");

View File

@@ -32,6 +32,19 @@ pub struct Me {
/// Vaults this device must leave (access ended). /// Vaults this device must leave (access ended).
#[serde(default)] #[serde(default)]
pub leaving: Vec<Departure>, pub leaving: Vec<Departure>,
/// 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<i64>,
pub waiting: usize,
pub held_secrets: usize,
pub holding: bool,
} }
/// A vault this device has to hand over and leave (A6). /// 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()) 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<usize> { pub fn remove(&self, person: &str, vault: &str, without_saving: bool) -> Result<usize> {
let v: Value = self.post("/api/remove", json!({"person": person, "vault": vault, "without_saving": without_saving}))?; 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) Ok(v["devices"].as_u64().unwrap_or(0) as usize)

View File

@@ -34,6 +34,16 @@ pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
for d in &me.leaving { for d in &me.leaving {
said.push(leave(config, &h, d)?); 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 { for hv in me.vaults {
if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) { 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<Vec<String>> {
Ok(said) 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 /// 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. /// hub has it, delete the folder if the app created it.
pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<String> { pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<String> {

View File

@@ -95,11 +95,18 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
let mut was_read_only = false; let mut was_read_only = false;
let mut announced: HashSet<String> = HashSet::new(); let mut announced: HashSet<String> = HashSet::new();
let leaving = state::lune_dir(&vault.git_dir).join("leaving"); let leaving = state::lune_dir(&vault.git_dir).join("leaving");
let nudge = state::lune_dir(&vault.git_dir).join("nudge");
loop { loop {
if leaving.exists() { if leaving.exists() {
say("access to this vault ended — stopped syncing it"); say("access to this vault ended — stopped syncing it");
return Ok(()); 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)); let first = rx.recv_timeout(Duration::from_millis(250));
for ev in first.into_iter().chain(rx.try_iter()) { for ev in first.into_iter().chain(rx.try_iter()) {
match ev { match ev {

View File

@@ -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 ### 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 ### What Sen does (on the canvas)
```bash - 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.
lunesync open # opens the canvas in the browser, already signed in - 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.
Or on a phone / another browser: open the hub's address, type a code from `lunesync pair`. - 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).
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.
### Behavior ### 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. - **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.
- **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. - **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.
- **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). - **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.
- **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). - **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`.
- **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. - **Handovers on the canvas** are the M4 review (show / keep / discard / delete without saving), shown in the vault and person panels.
- **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. - **Remove from team / Restore** are the M4 flows; this is the only gesture on the canvas that asks for confirmation (X2).
- **Invite link in a browser** shows how to join (`lunesync join <link> --name …`) instead of an error. - Status colors are used only for status; red only for a held secret (X6).
- The hub serves the canvas itself (built into the binary); nothing else to deploy.
### Acceptance — Sen acts this out ### Acceptance — Sen acts this out
1. `lunesync open` → the canvas, signed in. A phone signs in with a code. 1. Laptop offline with edits: its ring turns amber, then grey with "last seen"; back online it turns green on its own.
2. Drag a vault onto a teammate: the vault arrives on their devices. Change their role in the panel. 2. A behind laptop that's online but idle: **Nudge** → green within a minute.
3. Pull a ribbon until it snaps, press Undo: nothing changed on their devices. Pull again and wait: the M4 removal runs. 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. Invite a person with a vault; they join from the link; they appear on the canvas with their device. 4. Remove someone from a vault with unshared work: review and keep the handover on the canvas.
5. Rename and remove a device from the panel; switch Float/Dock; everything works with buttons alone (keyboard). 5. From a phone: remove someone from the team (confirm), see their devices leave; restore them.
### Out of scope for M5 ### Out of scope for M6
Freshness glow, Nudge, tidy and handover review, remove from team (M6). Desktop app (M7). Desktop app, tray, installers, updates (M7). Push notifications for Nudge (the next check-in is enough for now).
## 7. Open questions ## 7. Open questions
None open. None open.

View File

@@ -247,9 +247,16 @@ pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
.into_iter() .into_iter()
.map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) })) .map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) }))
.collect(); .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!({ Ok(Json(json!({
"person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults, "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, due INTEGER NOT NULL,
by_who TEXT 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 ( CREATE TABLE IF NOT EXISTS log (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
at INTEGER NOT NULL, at INTEGER NOT NULL,
@@ -94,6 +103,8 @@ pub fn open(data: &Path) -> Result<Connection> {
("devices", "removed INTEGER NOT NULL DEFAULT 0"), ("devices", "removed INTEGER NOT NULL DEFAULT 0"),
("vaults", "delete_from_devices INTEGER NOT NULL DEFAULT 1"), ("vaults", "delete_from_devices INTEGER NOT NULL DEFAULT 1"),
("invites", "account_id INTEGER"), ("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}"), []); 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. /// 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") if let Ok(head) = repo.find_reference("HEAD")
&& let Some(target) = head.symbolic_target().ok().flatten() && let Some(target) = head.symbolic_target().ok().flatten()
&& repo.find_reference(target).is_ok() && repo.find_reference(target).is_ok()

View File

@@ -3,6 +3,7 @@
mod api; mod api;
mod db; mod db;
mod git; mod git;
mod health;
mod hook; mod hook;
mod leave; mod leave;
mod web; mod web;
@@ -102,6 +103,10 @@ async fn serve() -> Result<()> {
.route("/api/web/link", post(web::link)) .route("/api/web/link", post(web::link))
.route("/api/web/signout", post(web::signout)) .route("/api/web/signout", post(web::signout))
.route("/api/canvas", get(web::canvas)) .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/invites/grant", post(web::invite_grant))
.route("/api/devices/rename", post(web::rename_device)) .route("/api/devices/rename", post(web::rename_device))
.route("/signin/{token}", get(web::signin_link)) .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 { if manage {
managed.push(*id); 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(); 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 people = vec![];
{ {
let mut stmt = conn.prepare("SELECT id, name, owner FROM accounts WHERE disabled = 0 ORDER BY created, id")?; // The owner also sees people removed from the team (dimmed, restorable).
let rows: Vec<(i64, String, bool)> = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?; let mut stmt = conn.prepare("SELECT id, name, owner, disabled FROM accounts WHERE disabled = 0 OR ?1 ORDER BY created, id")?;
for (id, name, owner) in rows { 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). // Devices: your own, the owner sees all, managers see their members' (blueprint J6).
let shares_managed = members.iter().any(|m| { let shares_managed = members.iter().any(|m| {
m["person"] == format!("a{id}") && managed.iter().any(|v| m["vault"] == format!("v{v}")) 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 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")?; 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)? })))? let devices: Vec<(String, String)> = d.query_map([id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::<Result<_, _>>()?;
.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 { } else {
vec![] 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)) { for (v, role) in grants.iter().filter(|(v, _)| visible.contains(v)) {
members.push(json!({ "vault": format!("v{v}"), "person": key, "role": role })); 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(); let res = agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap();
assert_eq!(res.status(), 401); 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());
}

View File

@@ -3,7 +3,7 @@
// also has a button in the details panel (X3). // also has a button in the details panel (X3).
import { useEffect, useMemo, useRef, useState } from 'react'; 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 { import {
HANDLE_T, W, boardHeight, circle, easeBack, lerp, personColor, positions, ribbon, roundRect, vaultColor, HANDLE_T, W, boardHeight, circle, easeBack, lerp, personColor, positions, ribbon, roundRect, vaultColor,
type Layout, type Pt, 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 plural = (n: number, word: string, many = word + 's') => `${n} ${n === 1 ? word : many}`;
const keyOf = (m: { vault: string; person: string }) => `${m.vault}|${m.person}`; 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<Status, string> = { current: '#2E8B5F', behind: '#E09A2B', offline: '#A9A5B6' };
const STATUS_WORDS: Record<Status, string> = { current: 'Current', behind: 'Behind', offline: 'Offline' };
const PILL: Record<Status, [string, string]> = { 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 = type Sel =
| { kind: 'overview'; back?: Sel } | { kind: 'overview'; back?: Sel }
| { kind: 'vault'; id: string; back?: Sel } | { kind: 'vault'; id: string; back?: Sel }
@@ -25,6 +56,12 @@ type Drag =
| { kind: 'detach'; key: string; p: Pt } | { kind: 'detach'; key: string; p: Pt }
| { kind: 'snap'; key: string; p: Pt }; | { kind: 'snap'; key: string; p: Pt };
type Toast = { text: string; undo?: () => void }; 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 { function store(key: string, value?: string): string | null {
try { try {
@@ -45,7 +82,7 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
const [drag, setDrag] = useState<Drag | null>(null); const [drag, setDrag] = useState<Drag | null>(null);
const [pinched, setPinched] = useState<{ key: string; p: Pt; t: number } | null>(null); const [pinched, setPinched] = useState<{ key: string; p: Pt; t: number } | null>(null);
const [toast, setToast] = useState<Toast | null>(null); const [toast, setToast] = useState<Toast | null>(null);
const [sheet, setSheet] = useState<'invite' | 'vault' | null>(null); const [sheet, setSheet] = useState<Sheet | null>(null);
const [onboarded, setOnboarded] = useState(store('lune.onboarded') === '1'); const [onboarded, setOnboarded] = useState(store('lune.onboarded') === '1');
const [hidden, setHidden] = useState<Set<string>>(new Set()); const [hidden, setHidden] = useState<Set<string>>(new Set());
const [extra, setExtra] = useState<Member[]>([]); const [extra, setExtra] = useState<Member[]>([]);
@@ -203,6 +240,7 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
const target = (p: Pt) => { const target = (p: Pt) => {
let best: string | null = null, bd = 1e9; let best: string | null = null, bd = 1e9;
for (const pr of people) { 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); const q = pos(pr.id), d = Math.hypot(p.x - q.x, p.y - q.y);
if (d < bd) { bd = d; best = pr.id; } 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) => { vaults.forEach((v, i) => {
const p = pos(v.id), delay = (i * 0.7).toFixed(1), vo = relV(v.id) ? 1 : 0.35; 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 }); 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({ labels.push({
text: v.name, text: v.name,
@@ -286,11 +334,11 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
}); });
}); });
people.forEach((pr, i) => { people.forEach((pr, i) => {
const p = pos(pr.id), delay = (0.35 + i * 0.6).toFixed(1), po = relP(pr.id) ? 1 : 0.35; 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) blobs.push({ d: circle(p.x, p.y, 38), fill: personColor(pr.id).fill, delay, op: focus && relP(pr.id) ? 1 : 0 }); 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.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({ 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 }, 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` }, 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 ( return (
<g key={d.id} className="fade" opacity={veil ? 0.35 : 1}> <g key={d.id} className="fade" opacity={veil ? 0.35 : 1}>
<line x1="0" y1="0" x2={cx} y2={cy} stroke="#E2DDF0" strokeWidth="1.5" /> <line x1="0" y1="0" x2={cx} y2={cy} stroke="#E2DDF0" strokeWidth="1.5" />
<circle cx={cx} cy={cy} r="6.5" fill={c.ring} stroke="#FFFFFF" strokeWidth="2" /> <circle cx={cx} cy={cy} r="6.5" fill={d.health.held_secrets > 0 ? SECRET_RED : STATUS[d.health.status]} stroke="#FFFFFF" strokeWidth="2" />
</g> </g>
); );
})} })}
<g data-person={pr.name} onClick={() => { if (!drag) setSel({ kind: 'person', id: pr.id }); }} onPointerEnter={() => enter('person', pr.id)} onPointerLeave={leave} style={{ cursor: 'pointer' }}> <g data-person={pr.name} onClick={() => { if (!drag) setSel({ kind: 'person', id: pr.id }); }} onPointerEnter={() => enter('person', pr.id)} onPointerLeave={leave} style={{ cursor: 'pointer' }}>
<circle r="30" fill={pr.id === hot ? c.fill : c.tint} stroke={c.ring} strokeWidth={pr.id === hot ? 6 : on ? 4.5 : 3} strokeDasharray={pr.invited ? '5 5' : 'none'} /> <circle r="30" fill={pr.id === hot ? c.fill : c.tint} stroke={pr.invited ? c.ring : pr.removed ? STATUS.offline : STATUS[worst(pr)]} strokeWidth={pr.id === hot ? 6 : on ? 4.5 : 3} strokeDasharray={pr.invited || pr.removed ? '5 5' : 'none'} opacity={pr.removed ? 0.45 : 1} />
<circle className="fade" r="34" fill="#F5F3FB" opacity={veil} pointerEvents="none" /> <circle className="fade" r="34" fill="#F5F3FB" opacity={veil} pointerEvents="none" />
</g> </g>
</g> </g>
@@ -490,7 +538,13 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
)} )}
</div> </div>
<div className="bottombar">{hint && <span className={`chipbar${hintHot ? ' hot' : ''}`}>{hint}</span>}</div> <div className="bottombar">
{hint && <span className={`chipbar${hintHot ? ' hot' : ''}`}>{hint}</span>}
<span className="chipbar legend" style={{ marginLeft: 'auto' }}>
{(Object.keys(STATUS) as Status[]).map((s) => <span key={s}><i style={{ background: STATUS[s] }} />{STATUS_WORDS[s]}</span>)}
<span><i style={{ background: SECRET_RED }} />Possible secret held</span>
</span>
</div>
{!onboarded && manages && vaults.length > 0 && ( {!onboarded && manages && vaults.length > 0 && (
<div className="coach" role="note" aria-label="Getting started"> <div className="coach" role="note" aria-label="Getting started">
@@ -508,16 +562,38 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
{sel.kind === 'overview' && <Overview data={data} members={members} log={log} open={open} close={() => setSel(null)} newVault={() => setSheet('vault')} signOut={onSignOut} />} {sel.kind === 'overview' && <Overview data={data} members={members} log={log} open={open} close={() => setSel(null)} newVault={() => setSheet('vault')} signOut={onSignOut} />}
{sel.kind === 'vault' && vault(sel.id) && ( {sel.kind === 'vault' && vault(sel.id) && (
<VaultPanel v={vault(sel.id)} data={data} members={members} open={open} close={() => setSel(null)} <VaultPanel v={vault(sel.id)} data={data} members={members} open={open} close={() => 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.`)} /> 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) && ( {sel.kind === 'person' && person(sel.id) && (
<PersonPanel p={person(sel.id)} data={data} members={members} open={open} close={() => setSel(null)} run={run} /> <PersonPanel p={person(sel.id)} data={data} members={members} open={open} close={() => 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))} />
)} )}
</aside> </aside>
)} )}
{sheet === 'invite' && <InviteDialog vaults={vaults.filter((v) => v.can_manage)} owner={data.me.owner} close={() => { setSheet(null); reload(); }} />} {sheet === 'invite' && <InviteDialog vaults={vaults.filter((v) => v.can_manage)} owner={data.me.owner} close={() => { setSheet(null); reload(); }} />}
{typeof sheet === 'object' && sheet?.kind === 'compare' && (
<CompareDialog vault={sheet.vault} copy={sheet.copy} canEdit={['edit', 'manage'].includes(members.find((m) => 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' && (
<TeamDialog p={sheet.p} data={data} members={members} close={() => 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' && (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) setSheet(null); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`${sheet.p.name} restored`}>
<h2 className="disp">{sheet.p.name} is back on the team</h2>
<p style={{ margin: 0, lineHeight: 1.5 }}>They start with no vaults — give them some by dragging. Send them this one-time sign-in link (7 days):</p>
<pre className="cmd">lunesync join {sheet.link} --name "&lt;their device&gt;"</pre>
<div className="actions"><button className="btn btn-primary" onClick={() => setSheet(null)}>Done</button></div>
</div>
</div>
)}
{sheet === 'vault' && <NewVaultDialog close={() => setSheet(null)} create={(name) => { setSheet(null); run(() => api.createVault(name), `${name} is ready. Drag it onto people to share it.`); }} />} {sheet === 'vault' && <NewVaultDialog close={() => setSheet(null)} create={(name) => { setSheet(null); run(() => api.createVault(name), `${name} is ready. Drag it onto people to share it.`); }} />}
<div className="toast-wrap" aria-live="polite"> <div className="toast-wrap" aria-live="polite">
@@ -534,7 +610,8 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
function Avatar({ p }: { p: Person }) { function Avatar({ p }: { p: Person }) {
const c = personColor(p.id); const c = personColor(p.id);
return <span className="avatar" style={{ background: c.tint, borderColor: c.ring, borderStyle: p.invited ? 'dashed' : 'solid' }}>{p.name.charAt(0).toUpperCase()}</span>; const ring = p.invited ? c.ring : p.removed ? STATUS.offline : STATUS[worst(p)];
return <span className="avatar" style={{ background: c.tint, borderColor: ring, borderStyle: p.invited || p.removed ? 'dashed' : 'solid' }}>{p.name.charAt(0).toUpperCase()}</span>;
} }
function Swatch({ v }: { v: Vault }) { function Swatch({ v }: { v: Vault }) {
@@ -574,8 +651,9 @@ function Overview({ data, members, log, open, close, newVault, signOut }: {
<Avatar p={p} /> <Avatar p={p} />
<span style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}> <span style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}>
<b>{p.name}</b> <b>{p.name}</b>
<span className="sub">{p.invited ? 'Invited, not joined yet' : p.owner ? 'Team owner' : plural(members.filter((m) => m.person === p.id).length, 'vault')}</span> <span className="sub">{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')}</span>
</span> </span>
{!p.invited && !p.removed && (() => { const st = worst(p), [bg, fg] = PILL[st]; return <span className="pill" style={{ background: bg, color: fg }}>{STATUS_WORDS[st]}</span>; })()}
<span aria-hidden="true" className="chev">›</span> <span aria-hidden="true" className="chev">›</span>
</button> </button>
))} ))}
@@ -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; 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; cycleRole: (m: Member) => void; remove: (m: Member) => void; grant: (v: string, p: string) => void; toggleDelete: (v: Vault) => void;
run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; compare: (copy: string) => void;
}) { }) {
const inVault = members.filter((m) => m.vault === v.id); 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); const mine = inVault.find((m) => m.person === data.me.id);
return ( return (
<> <>
@@ -612,6 +691,19 @@ function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, t
<CloseButton close={close} /> <CloseButton close={close} />
</div> </div>
{!v.can_manage && mine && <div className="note">You have {roleName(mine.role)} access. People with Manage decide who else can sync it.</div>} {!v.can_manage && mine && <div className="note">You have {roleName(mine.role)} access. People with Manage decide who else can sync it.</div>}
{v.tidy.length > 0 && (
<div className="note amber">
<b>{plural(v.tidy.length, 'note')} to tidy</b>
<span>Changed in two places at once. Both versions are kept, so nothing is lost.</span>
{v.tidy.map((t) => (
<div key={t.copy} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ flex: 1, minWidth: 0, overflowWrap: 'anywhere' }}>{t.note}</span>
<button className="btn btn-small" onClick={() => compare(t.copy)}>Compare</button>
</div>
))}
</div>
)}
{v.handovers.map((h) => <HandoverCard key={h.id} h={h} vault={v} run={run} />)}
<div> <div>
<h3>People with access</h3> <h3>People with access</h3>
{inVault.map((m) => { {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; p: Person; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void;
run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; removeFromTeam: (p: Person) => void; restore: (p: Person) => void;
}) { }) {
const [renaming, setRenaming] = useState<{ id: string; value: string } | null>(null); const [renaming, setRenaming] = useState<{ id: string; value: string } | null>(null);
const theirs = members.filter((m) => m.person === p.id); const theirs = members.filter((m) => m.person === p.id);
const canEditDevices = p.id === data.me.id || data.me.owner; 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 ( return (
<> <>
<div className="panel-head"> <div className="panel-head">
@@ -669,7 +762,24 @@ function PersonPanel({ p, data, members, open, close, run }: {
<CloseButton close={close} /> <CloseButton close={close} />
</div> </div>
{p.invited && <div className="note">{p.name} hasn't joined yet. Vaults you give them now arrive once they join with their invite link.</div>} {p.invited && <div className="note">{p.name} hasn't joined yet. Vaults you give them now arrive once they join with their invite link.</div>}
{!p.invited && ( {p.removed && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<p style={{ margin: 0, fontSize: 14, lineHeight: 1.5 }}>This account is disabled. Past changes keep this name in history.</p>
{data.me.owner && <button className="btn" style={{ alignSelf: 'flex-start' }} onClick={() => restore(p)}>Restore account</button>}
</div>
)}
{leaving.length > 0 && (
<div className="note">
<b>Leaving</b>
{leaving.map((h) => (
<div key={h.id} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<span>{h.device} hasn't reported in since losing {h.vault.name}. Its unshared work comes back when it's next online.</span>
<button className="btn btn-small btn-danger" style={{ alignSelf: 'flex-start' }} onClick={() => run(() => api.handoverDecide(h.id, 'skip'), `${h.device} will delete its copy of ${h.vault.name} without sending anything.`)}>Delete without saving</button>
</div>
))}
</div>
)}
{!p.invited && !p.removed && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<h3>Devices</h3> <h3>Devices</h3>
{p.devices.length === 0 && <p className="muted">{canEditDevices ? 'No devices yet.' : "Only their vault managers see someone's devices."}</p>} {p.devices.length === 0 && <p className="muted">{canEditDevices ? 'No devices yet.' : "Only their vault managers see someone's devices."}</p>}
@@ -683,13 +793,24 @@ function PersonPanel({ p, data, members, open, close, run }: {
<button className="btn btn-small" type="button" onClick={() => setRenaming(null)}>Cancel</button> <button className="btn btn-small" type="button" onClick={() => setRenaming(null)}>Cancel</button>
</form> </form>
) : ( ) : (
<>
<div className="device-head"> <div className="device-head">
<i style={{ width: 12, height: 12, borderRadius: '50%', background: personColor(p.id).ring, display: 'inline-block', flex: 'none' }} /> <i style={{ width: 12, height: 12, borderRadius: '50%', background: STATUS[d.health.status], display: 'inline-block', flex: 'none' }} />
<b style={{ flex: 1 }}>{d.label}</b> <b style={{ flex: 1 }}>{d.label}</b>
<span className="muted">{STATUS_WORDS[d.health.status]}</span>
</div> </div>
<span style={{ fontSize: 14, color: '#4A4560' }}>{healthLine(d.health)}</span>
{d.health.held_secrets > 0 && (
<span className="secret-note">{plural(d.health.held_secrets, 'note')} held back: possible secret, not shared. Its owner decides with <code>lunesync held</code>.</span>
)}
{d.health.holding && <span className="muted">A big change is held here, waiting for its owner to share or undo it.</span>}
</>
)} )}
{canEditDevices && renaming?.id !== d.id && ( {canEditDevices && renaming?.id !== d.id && (
<div className="chips"> <div className="chips">
{d.health.waiting > 0 && (
<button className="btn btn-small btn-primary" onClick={() => run(() => api.nudge(d.id), `Nudge sent to ${d.label}. It shares at its next check-in, as soon as it's online.`)}>Nudge</button>
)}
<button className="btn btn-small" onClick={() => setRenaming({ id: d.id, value: d.label })}>Rename</button> <button className="btn btn-small" onClick={() => setRenaming({ id: d.id, value: d.label })}>Rename</button>
<button className="btn btn-small btn-danger" aria-label={`Remove device ${d.label}`} onClick={() => run(() => api.removeDevice(d.id), `${d.label} is removed. It sends anything unshared, then deletes its vault copies and stops working.`)}>Remove device</button> <button className="btn btn-small btn-danger" aria-label={`Remove device ${d.label}`} onClick={() => run(() => api.removeDevice(d.id), `${d.label} is removed. It sends anything unshared, then deletes its vault copies and stops working.`)}>Remove device</button>
</div> </div>
@@ -710,10 +831,113 @@ function PersonPanel({ p, data, members, open, close, run }: {
); );
})} })}
</div> </div>
{data.me.owner && !p.owner && !p.removed && !p.invited && (
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
<button className="btn btn-danger" style={{ alignSelf: 'flex-start' }} onClick={() => removeFromTeam(p)}>Remove from team</button>
<p className="muted">Ends every vault and device for this person. The account is disabled and can be restored.</p>
</div>
)}
</> </>
); );
} }
/** 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<unknown>, ok?: string) => Promise<void> }) {
const [files, setFiles] = useState<string[] | null>(null);
if (h.state === 'waiting') {
return (
<div className="note">
<b>{h.person} is leaving {vault.name}</b>
<span>{h.device} hasn't reported in yet. Its unshared work comes to you when it's next online.</span>
<button className="btn btn-small btn-danger" style={{ alignSelf: 'flex-start' }} onClick={() => run(() => api.handoverDecide(h.id, 'skip'), `${h.device} will delete its copy without sending anything.`)}>Delete without saving</button>
</div>
);
}
return (
<div className="note amber">
<b>{h.person}'s last changes from {h.device}</b>
<span>These arrived in a final sync after the removal. Review before they join the vault.</span>
{files === null ? (
<button className="btn btn-small" style={{ alignSelf: 'flex-start' }} onClick={() => api.handoverShow(h.id).then(setFiles).catch(() => setFiles([]))}>Show changes</button>
) : (
<ul className="files">{files.map((f) => <li key={f}>{f}</li>)}</ul>
)}
<div className="chips">
<button className="btn btn-small btn-primary" onClick={() => run(async () => (await api.handoverDecide(h.id, 'keep')).message, `Kept ${h.person}'s changes in ${vault.name}.`)}>Keep</button>
<button className="btn btn-small" onClick={() => run(() => api.handoverDecide(h.id, 'discard'), `${h.person}'s handover was discarded.`)}>Discard</button>
</div>
</div>
);
}
/** 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<Comparison | null>(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 (
<div className="cmp-col">
<div className="cmp-head">{title}</div>
<div className="cmp-body">
{text === null ? <span className="muted">Not shown (not a text note, or very large).</span>
: text.split('\n').map((line, i) => <div key={i} style={others.has(line) ? undefined : { background: tint, margin: '0 -14px', padding: '0 14px' }}>{line || '\u00a0'}</div>)}
</div>
</div>
);
};
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog wide" role="dialog" aria-modal="true" aria-label={`Compare versions of ${c?.note ?? copy}`}>
<div><span className="eyebrow">{vault.name} · {c?.note ?? ''}</span><h2 className="disp">Two versions of the same lines</h2></div>
{error && <p className="error">{error}</p>}
{c && (
<div className="cmp">
{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')}
</div>
)}
{c && !canEdit && <p className="muted">You have read access, so you can look but not choose.</p>}
<div className="actions">
<button className="btn" onClick={close}>Keep both for now</button>
{c && canEdit && (
<>
<button className="btn" onClick={() => resolve('both')}>Keep both as separate notes</button>
{c.note_exists && <button className="btn" onClick={() => resolve('note')}>Keep the one in the vault</button>}
<button className="btn btn-primary" onClick={() => resolve('copy')}>Keep {c.label}'s</button>
</>
)}
</div>
</div>
</div>
);
}
/** 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 (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`Remove ${p.name} from the team?`}>
<h2 className="disp">Remove {p.name} from the team?</h2>
<p style={{ margin: 0, lineHeight: 1.5 }}>
{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.
</p>
{waiting > 0 && <p className="warn-box">{plural(waiting, 'change')} haven't been shared yet. They'll be sent to the team for review before anything is deleted.</p>}
<p className="muted">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.</p>
<div className="actions">
<button className="btn" onClick={close}>Cancel</button>
<button className="btn btn-primary" style={{ background: '#A52A2F', borderColor: '#A52A2F' }} onClick={confirm}>Remove from team</button>
</div>
</div>
</div>
);
}
function InviteDialog({ vaults, owner, close }: { vaults: Vault[]; owner: boolean; close: () => void }) { function InviteDialog({ vaults, owner, close }: { vaults: Vault[]; owner: boolean; close: () => void }) {
const [name, setName] = useState(''); const [name, setName] = useState('');
const [picked, setPicked] = useState<Set<string>>(new Set()); const [picked, setPicked] = useState<Set<string>>(new Set());

View File

@@ -7,11 +7,27 @@ export interface Vault {
name: string; name: string;
can_manage: boolean; can_manage: boolean;
delete_from_devices: 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 { export interface Device {
id: string; id: string;
label: string; label: string;
health: Health;
} }
export interface Person { export interface Person {
@@ -20,6 +36,8 @@ export interface Person {
owner: boolean; owner: boolean;
/** Invited but not joined yet. */ /** Invited but not joined yet. */
invited: boolean; invited: boolean;
/** Removed from the team (shown to the owner, restorable). */
removed: boolean;
devices: Device[]; devices: Device[];
} }
@@ -45,6 +63,15 @@ export interface LogEntry {
detail: string; 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 {} export class SignedOut extends Error {}
async function call<T>(method: string, path: string, body?: unknown): Promise<T> { async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
@@ -77,5 +104,14 @@ export const api = {
vaultSetting: (vault: string, deleteFromDevices: boolean) => vaultSetting: (vault: string, deleteFromDevices: boolean) =>
call<object>('POST', '/api/vaults/settings', { vault, delete_from_devices: deleteFromDevices }), call<object>('POST', '/api/vaults/settings', { vault, delete_from_devices: deleteFromDevices }),
renameDevice: (deviceId: string, label: string) => call<object>('POST', '/api/devices/rename', { device_id: deviceId, label }), renameDevice: (deviceId: string, label: string) => call<object>('POST', '/api/devices/rename', { device_id: deviceId, label }),
nudge: (deviceId: string) => call<object>('POST', '/api/nudge', { device_id: deviceId }),
compare: (vault: string, copy: string) => call<Comparison>('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<string[]>('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<object>('POST', '/api/team/remove', { person }),
teamRestore: (person: string) => call<{ link: string }>('POST', '/api/team/restore', { person }),
removeDevice: (deviceId: string) => call<object>('POST', '/api/device/remove', { device_id: deviceId }), removeDevice: (deviceId: string) => call<object>('POST', '/api/device/remove', { device_id: deviceId }),
}; };

View File

@@ -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; } .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; } .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; } .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 { 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; } .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; } .panel { top: auto; left: 8px; right: 8px; bottom: 8px; width: auto; max-width: none; height: 56vh; animation-name: slideup; }
.open .bottombar { display: none; } .open .bottombar { display: none; }
.coach { bottom: 16px; } .coach { bottom: 16px; }
.legend { display: none; }
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.bob { animation: none; } .bob { animation: none; }