Leave a team, delete a vault; keep tests out of the real settings

- A hub test unset LUNE_HOME for the whole test run, so later tests saved
  into the real user's config. Tests now always keep their own settings
  folder.
- Leaving a team: `lunesync leave` and the app's Leave hand over and remove
  this device there; a hub that's gone can be forgotten (folders stay).
- Deleting a vault (owner): everyone is removed the usual way, the history
  is archived on the hub and the name is freed. Canvas asks first.
- Connect this Mac says what to do when Lune isn't installed.
- Update checks skip http hubs instead of failing for all of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 14:36:46 +07:00
parent 7d1437e3ec
commit 4f6414b256
16 changed files with 278 additions and 10 deletions

View File

@@ -125,7 +125,7 @@ Lists each vault with its status, and anything that needs you:
- **A big change is waiting:** **Undo** brings back everything it removed or rewrote; **Share anyway** sends it. - **A big change is waiting:** **Undo** brings back everything it removed or rewrote; **Share anyway** sends it.
- **A note may contain a secret:** type where the secret really lives and click **Replace**, or click **Not a secret**. - **A note may contain a secret:** type where the secret really lives and click **Replace**, or click **Not a secret**.
- **A note was changed in two places:** **Compare** shows both versions with the differences highlighted. Keep one, or keep both as separate notes. - **A note was changed in two places:** **Compare** shows both versions with the differences highlighted. Keep one, or keep both as separate notes.
- **Join another team:** add a second hub, such as your workplace's. - **Join another team:** add a second hub, such as your workplace's. **Leave** next to a team removes this Mac from it (anything unshared is handed over first).
### The team canvas ### The team canvas
@@ -133,7 +133,7 @@ Open it from the menu (**Open team canvas**), or with `lunesync open`. Managers
- **Grant:** drag a vault onto a person. - **Grant:** drag a vault onto a person.
- **Revoke:** pull the ribbon between them until it snaps. You get an **Undo** for about 8 seconds; nothing reaches their devices before that. - **Revoke:** pull the ribbon between them until it snaps. You get an **Undo** for about 8 seconds; nothing reaches their devices before that.
- **Invite person**, change roles, rename devices, **Nudge** a device that's behind, tidy notes changed in two places, review **handovers**, and (team owner only) **Remove from team** or **Restore**. - **Invite person**, **New vault**, **Delete vault…** (team owner; asks first, and the history stays archived on the hub), change roles, rename devices, **Nudge** a device that's behind, tidy notes changed in two places, review **handovers**, and (team owner only) **Remove from team** or **Restore**.
Every gesture also has a button in the side panel. Every access change is recorded in the hub's access log. Every gesture also has a button in the side panel. Every access change is recorded in the hub's access log.
@@ -161,6 +161,8 @@ lunesync remove Alice --vault DevOps # her unshared work comes back as
lunesync handovers # then: lunesync handover show|keep|discard|skip <id> lunesync handovers # then: lunesync handover show|keep|discard|skip <id>
lunesync device remove "Old laptop" # a lost device: hands over and leaves, then its key stops working lunesync device remove "Old laptop" # a lost device: hands over and leaves, then its key stops working
lunesync team remove Alice # owner only: ends everything, account can be restored lunesync team remove Alice # owner only: ends everything, account can be restored
lunesync vault delete Sandbox --yes # owner only: everyone's copy goes, the history stays archived on the hub
lunesync leave --team work.example.com # this device leaves a team (add --forget if that hub is gone)
lunesync hub log # owner only: the access log lunesync hub log # owner only: the access log
``` ```

View File

@@ -121,6 +121,12 @@ enum Command {
#[arg(long)] #[arg(long)]
without_saving: bool, without_saving: bool,
}, },
/// Leave a team on this device: hands over anything unshared and removes this device there (--team picks which)
Leave {
/// The team's hub is gone for good: just forget it here (its folders stay, no longer synced)
#[arg(long)]
forget: bool,
},
/// Remove someone from the team, or bring them back (team owner) /// Remove someone from the team, or bring them back (team owner)
Team { Team {
#[command(subcommand)] #[command(subcommand)]
@@ -183,6 +189,13 @@ enum VaultCmd {
#[arg(long)] #[arg(long)]
delete_from_devices: OnOff, delete_from_devices: OnOff,
}, },
/// Delete a vault (team owner): everyone's devices send unshared work, then remove their copy; the history stays archived on the hub
Delete {
name: String,
/// Yes, delete it
#[arg(long)]
yes: bool,
},
/// Move a vault from its plain Git remote onto the hub /// Move a vault from its plain Git remote onto the hub
Upload { Upload {
name: String, name: String,
@@ -303,6 +316,12 @@ fn run_cli(cli: Cli) -> Result<()> {
Command::Join { link, name, vaults_dir } => team::join(&mut config, &link, &name, vaults_dir)?, Command::Join { link, name, vaults_dir } => team::join(&mut config, &link, &name, vaults_dir)?,
Command::Login { hub, code, name, vaults_dir } => team::login(&mut config, &hub, &code, &name, vaults_dir)?, Command::Login { hub, code, name, vaults_dir } => team::login(&mut config, &hub, &code, &name, vaults_dir)?,
Command::Pair => team::pair(&config)?, Command::Pair => team::pair(&config)?,
Command::Leave { forget } => {
let url = team::link(&config)?.url.clone();
for msg in lune_core::membership::leave_hub(&mut config, &url, forget)? {
println!("{msg}");
}
}
Command::Open => { Command::Open => {
let url = team::link(&config)?.web_link()?; let url = team::link(&config)?.web_link()?;
let opener = if cfg!(target_os = "macos") { "open" } else { "xdg-open" }; let opener = if cfg!(target_os = "macos") { "open" } else { "xdg-open" };
@@ -325,6 +344,13 @@ fn run_cli(cli: Cli) -> Result<()> {
HandoverCmd::Discard { id } => team::handover_decide(&config, id, "discard")?, HandoverCmd::Discard { id } => team::handover_decide(&config, id, "discard")?,
HandoverCmd::Skip { id } => team::handover_decide(&config, id, "skip")?, HandoverCmd::Skip { id } => team::handover_decide(&config, id, "skip")?,
}, },
Command::Vault { action: VaultCmd::Delete { name, yes } } => {
if !yes {
bail!("deleting {name} ends everyone's access to it; run again with --yes if that's what you want");
}
let n = team::link(&config)?.delete_vault(&name)?;
println!("Deleted {name}. {n} device(s) send anything unshared, then remove their copy; the history stays archived on the hub.");
}
Command::Vault { action: VaultCmd::Set { name, delete_from_devices } } => { Command::Vault { action: VaultCmd::Set { name, delete_from_devices } } => {
team::link(&config)?.vault_setting(&name, matches!(delete_from_devices, OnOff::On))?; team::link(&config)?.vault_setting(&name, matches!(delete_from_devices, OnOff::On))?;
let what = match delete_from_devices { let what = match delete_from_devices {

View File

@@ -241,6 +241,12 @@ impl HubLink {
Ok(v["message"].as_str().unwrap_or_default().to_string()) Ok(v["message"].as_str().unwrap_or_default().to_string())
} }
/// Deletes a vault (team owner); returns how many devices will hand over and remove their copy.
pub fn delete_vault(&self, vault: &str) -> Result<usize> {
let v: Value = self.post("/api/vaults/delete", json!({ "vault": vault }))?;
Ok(v["devices"].as_u64().unwrap_or(0) as usize)
}
pub fn vault_setting(&self, vault: &str, delete_from_devices: bool) -> Result<()> { pub fn vault_setting(&self, vault: &str, delete_from_devices: bool) -> Result<()> {
let _: Value = self.post("/api/vaults/settings", json!({"vault": vault, "delete_from_devices": delete_from_devices}))?; let _: Value = self.post("/api/vaults/settings", json!({"vault": vault, "delete_from_devices": delete_from_devices}))?;
Ok(()) Ok(())

View File

@@ -210,6 +210,36 @@ pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<Strin
} }
} }
/// Leaves one team's hub on this device. If the hub answers, this device removes itself there, which hands
/// over anything unshared and leaves its vaults the usual way (A6). If the hub is gone or no longer knows this
/// device, `forget` drops it from this device only: its folders stay where they are, no longer synced.
pub fn leave_hub(config: &mut Config, url: &str, forget: bool) -> Result<Vec<String>> {
let Some(link) = config.hub(url).cloned() else { bail!("this device isn't on the hub at {url}") };
let label = config.device_label();
let reached = link.remove_device(&label, None).and_then(|_| link.me());
let mut said = vec![];
match reached {
Ok(me) => {
for d in &me.leaving {
said.push(leave(config, &link, d)?);
}
}
Err(e) if !forget => {
bail!("can't reach the hub at {url} ({e:#}). If that team is gone for good, forget it on this device only")
}
Err(_) => said.push(format!("Couldn't reach {url}, so this device only forgot it; its folders stay, no longer synced")),
}
for vc in config.vaults.iter().filter(|v| v.hub_url.as_deref() == Some(url)) {
let _ = set_read_only(&vc.path, false);
said.push(format!("{} stays at {}, no longer synced", vc.name, vc.path.display()));
}
config.vaults.retain(|v| v.hub_url.as_deref() != Some(url));
config.hubs.retain(|h| h.url != url);
config.save()?;
said.push(format!("Left the team at {url}"));
Ok(said)
}
/// What uninstalling did, in plain words. /// What uninstalling did, in plain words.
#[derive(Debug, Default, Serialize)] #[derive(Debug, Default, Serialize)]
pub struct Uninstalled { pub struct Uninstalled {

View File

@@ -249,6 +249,15 @@ pub fn tidy(vault: String, copy: String, keep: String) -> Answer<()> {
}) })
} }
/// Leaves a team on this Mac. `forget` drops a hub that can't be reached (its folders stay).
#[tauri::command(async)]
pub fn leave_team(team: String, forget: bool) -> Answer<String> {
let mut config = Config::load().map_err(plain)?;
config.use_hub_credentials();
let said = lune_core::membership::leave_hub(&mut config, &team, forget).map_err(plain)?;
Ok(said.last().cloned().unwrap_or_default())
}
pub fn open_canvas_now(app: &AppHandle, team: Option<&str>) -> Answer<()> { pub fn open_canvas_now(app: &AppHandle, team: Option<&str>) -> Answer<()> {
let config = Config::load().map_err(plain)?; let config = Config::load().map_err(plain)?;
let hub = config.pick_hub(team).map_err(plain)?; let hub = config.pick_hub(team).map_err(plain)?;

View File

@@ -224,7 +224,8 @@ pub async fn check_for_update(app: &AppHandle) {
if !configured { if !configured {
return; // a build without the hub's public key can't verify updates, so it doesn't take any return; // a build without the hub's public key can't verify updates, so it doesn't take any
} }
let endpoints = hubs.iter().filter_map(|h| format!("{}/api/update/{{{{target}}}}/{{{{arch}}}}/{{{{current_version}}}}", h.url).parse().ok()); // Updates only come over https (the updater refuses anything else, and one http hub would stop them all).
let endpoints = hubs.iter().filter(|h| h.url.starts_with("https://")).filter_map(|h| format!("{}/api/update/{{{{target}}}}/{{{{arch}}}}/{{{{current_version}}}}", h.url).parse().ok());
let result = async { let result = async {
let updater = app let updater = app
.updater_builder() .updater_builder()
@@ -354,6 +355,7 @@ fn main() {
commands::compare, commands::compare,
commands::tidy, commands::tidy,
commands::open_canvas, commands::open_canvas,
commands::leave_team,
commands::open_folder, commands::open_folder,
commands::restart, commands::restart,
]) ])

View File

@@ -206,3 +206,5 @@ Record here: date, what changed, why, which decision number. Example:
- 2026-10-29 — The update-signing key lives on the hub's server and `lunehub` signs releases there, so losing a laptop doesn't lose the key (D3). (Sen) - 2026-10-29 — The update-signing key lives on the hub's server and `lunehub` signs releases there, so losing a laptop doesn't lose the key (D3). (Sen)
- 2026-10-29 — A device can connect to several hubs at once (Sen's own and a workplace hub), each with its own device key (A1, new in M7). (Sen) - 2026-10-29 — A device can connect to several hubs at once (Sen's own and a workplace hub), each with its own device key (A1, new in M7). (Sen)
- 2026-10-29 — One update-signing key, on Sen's VPS, signs releases for every hub; other hubs import signed releases (D3). Accepted trade-off: that server is trusted by every hub's Macs. (Sen) - 2026-10-29 — One update-signing key, on Sen's VPS, signs releases for every hub; other hubs import signed releases (D3). Accepted trade-off: that server is trusted by every hub's Macs. (Sen)
- 2026-10-29 — Leaving a team (new): a device can leave a team's hub itself (`lunesync leave`, the app's Leave), handing over first; a hub that's gone can be forgotten locally, folders kept. (Sen, after testing)
- 2026-10-29 — Deleting a vault (new, team owner): everyone is removed the usual way (handover, then copies removed), the history stays archived on the hub and the name is freed. Asks for confirmation, like Remove from team (X2). (Sen, after testing)

View File

@@ -105,6 +105,7 @@ pub fn open(data: &Path) -> Result<Connection> {
("invites", "account_id INTEGER"), ("invites", "account_id INTEGER"),
("devices", "last_seen INTEGER"), ("devices", "last_seen INTEGER"),
("devices", "nudge INTEGER NOT NULL DEFAULT 0"), ("devices", "nudge INTEGER NOT NULL DEFAULT 0"),
("vaults", "archived INTEGER"),
] { ] {
let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []); let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []);
} }
@@ -208,7 +209,9 @@ pub fn new_device(conn: &Connection, account_id: i64, label: &str) -> Result<(St
} }
pub fn vault_id(conn: &Connection, name: &str) -> Result<Option<(i64, String)>> { pub fn vault_id(conn: &Connection, name: &str) -> Result<Option<(i64, String)>> {
Ok(conn.query_row("SELECT id, name FROM vaults WHERE name = ?1", [name], |r| Ok((r.get(0)?, r.get(1)?))).optional()?) Ok(conn
.query_row("SELECT id, name FROM vaults WHERE name = ?1 AND archived IS NULL", [name], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?)
} }
pub fn role(conn: &Connection, account_id: i64, vault_id: i64) -> Result<Option<String>> { pub fn role(conn: &Connection, account_id: i64, vault_id: i64) -> Result<Option<String>> {

View File

@@ -240,6 +240,35 @@ pub async fn team_restore(State(hub): State<Shared>, headers: HeaderMap, Json(re
Ok(Json(json!({ "link": format!("{}/join/{token}", hub.url) }))) Ok(Json(json!({ "link": format!("{}/join/{token}", hub.url) })))
} }
#[derive(Deserialize)]
pub struct DeleteVaultReq {
vault: String,
}
/// Deleting a vault (team owner): everyone is removed from it the usual way, so every device hands over what it
/// hadn't shared and removes its copy (A6, A7). The history stays archived on the hub; the name is free again.
pub async fn delete_vault(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<DeleteVaultReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
if !caller.owner {
return Err(denied("only the team owner can delete a vault"));
}
let conn = hub.db.lock().unwrap();
let (vault_id, vault) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
conn.execute("DELETE FROM pending_removals WHERE vault_id = ?1", [vault_id])?;
let members: Vec<i64> = {
let mut stmt = conn.prepare("SELECT account_id FROM memberships WHERE vault_id = ?1")?;
stmt.query_map([vault_id], |r| r.get(0))?.collect::<Result<_, _>>()?
};
let mut devices = 0;
for account_id in members {
devices += apply_removal(&conn, &caller.who(), account_id, vault_id, false)?;
}
let archived = format!("{vault} (deleted {} #{vault_id})", chrono::Utc::now().format("%Y-%m-%d"));
conn.execute("UPDATE vaults SET archived = ?1, name = ?2 WHERE id = ?3", params![db::now(), archived, vault_id])?;
db::log(&conn, &caller.who(), "vault deleted", &format!("{vault} ({}; its history is archived on the hub)", devices_phrase(devices)))?;
Ok(Json(json!({ "devices": devices })))
}
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct SettingsReq { pub struct SettingsReq {
vault: String, vault: String,

View File

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

View File

@@ -117,7 +117,7 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
let vault_rows: Vec<(i64, String, bool)> = { let vault_rows: Vec<(i64, String, bool)> = {
let sql = if caller.owner { let sql = if caller.owner {
"SELECT id, name, delete_from_devices FROM vaults ORDER BY created, id" "SELECT id, name, delete_from_devices FROM vaults WHERE archived IS NULL ORDER BY created, id"
} else { } else {
"SELECT v.id, v.name, v.delete_from_devices FROM vaults v JOIN memberships m ON m.vault_id = v.id "SELECT v.id, v.name, v.delete_from_devices FROM vaults v JOIN memberships m ON m.vault_id = v.id
WHERE m.account_id = ?1 ORDER BY v.created, v.id" WHERE m.account_id = ?1 ORDER BY v.created, v.id"

View File

@@ -18,7 +18,14 @@ impl Drop for HubProcess {
} }
} }
/// A settings folder for every test that doesn't pick its own: check-ins save settings, and without
/// `LUNE_HOME` that would be the real user's.
static HOME: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) { fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) {
if std::env::var_os("LUNE_HOME").is_none() {
unsafe { std::env::set_var("LUNE_HOME", HOME.get_or_init(|| tempfile::TempDir::new().unwrap()).path()) };
}
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let url = format!("http://127.0.0.1:{port}"); let url = format!("http://127.0.0.1:{port}");
let mut child = Command::new(env!("CARGO_BIN_EXE_lunehub")) let mut child = Command::new(env!("CARGO_BIN_EXE_lunehub"))
@@ -473,6 +480,8 @@ fn releases_are_signed_on_the_hub_and_old_clients_are_asked_to_update() {
fn one_device_on_two_hubs_keeps_the_teams_apart() { fn one_device_on_two_hubs_keeps_the_teams_apart() {
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap(); let tmp = tempfile::TempDir::new().unwrap();
// Check-ins save the settings; keep them in this test's folder.
unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("cfg")) };
let (_own, own_url, own_link) = start_hub(&tmp.path().join("own")); let (_own, own_url, own_link) = start_hub(&tmp.path().join("own"));
let (_work, work_url, work_link) = start_hub(&tmp.path().join("work")); let (_work, work_url, work_link) = start_hub(&tmp.path().join("work"));
@@ -539,10 +548,76 @@ fn a_single_hub_config_from_before_moves_into_the_list() {
) )
.unwrap(); .unwrap();
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
// Put back whatever home the other tests use: without one, saving would write the real user's settings.
let before = std::env::var_os("LUNE_HOME");
unsafe { std::env::set_var("LUNE_HOME", tmp.path()) }; unsafe { std::env::set_var("LUNE_HOME", tmp.path()) };
let c = Config::load().unwrap(); let c = Config::load().unwrap();
unsafe { std::env::remove_var("LUNE_HOME") }; match before {
Some(home) => unsafe { std::env::set_var("LUNE_HOME", home) },
None => unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("unused")) },
}
assert_eq!(c.hubs.len(), 1); assert_eq!(c.hubs.len(), 1);
assert_eq!(c.vaults[0].hub_url.as_deref(), Some("https://hub.example")); assert_eq!(c.vaults[0].hub_url.as_deref(), Some("https://hub.example"));
assert_eq!(c.hub_of(&c.vaults[0]).unwrap().device_id, "dev_1"); assert_eq!(c.hub_of(&c.vaults[0]).unwrap().device_id, "dev_1");
} }
#[test]
fn deleting_a_vault_and_leaving_a_team() {
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile::TempDir::new().unwrap();
let data = tmp.path().join("data");
let (_hub, url, owner_link) = start_hub(&data);
let (_, sen_w) = hub::join(&owner_link, "Mac").unwrap();
let mut mac = device(&url, &sen_w, "Mac", &tmp.path().join("mac"));
mac.use_hub_credentials();
let sandbox = mac.hubs[0].create_vault("Sandbox").unwrap();
check_in(&mut mac);
let v = open(&mac, "Sandbox");
write_and_save(&v, "try.md", "hello\n");
v.sync().unwrap();
write_and_save(&v, "unshared.md", "not sent yet\n");
let folder = v.root.clone();
drop(v);
// Deleting: the device hands over what it hadn't shared, then its copy goes; the history stays on the hub.
assert_eq!(mac.hubs[0].delete_vault("Sandbox").unwrap(), 1);
let said = check_in(&mut mac);
assert!(!folder.exists(), "{said:?}");
assert!(mac.vaults.is_empty());
let repo = lune_core::git2::Repository::open_bare(data.join(format!("repos/{}.git", sandbox.id))).unwrap();
assert!(repo.references_glob("refs/handover/*").unwrap().count() == 1, "the unshared note was handed over");
// The name is free again, and a non-owner can't delete.
mac.use_hub_credentials();
assert_eq!(mac.hubs[0].create_vault("Sandbox").unwrap().name, "Sandbox");
let invite = mac.hubs[0].invite("Alice", &[("Sandbox".into(), "manage".into())]).unwrap();
let (_, alice_w) = hub::join(&invite, "Alice pc").unwrap();
let alice = as_device(&url, &alice_w);
assert!(alice.delete_vault("Sandbox").is_err());
// Leaving a team: the hub is told, the device's vaults leave, and the team is gone from this device.
let mut a = device(&url, &alice_w, "Alice pc", &tmp.path().join("alice"));
check_in(&mut a);
assert_eq!(a.vaults.len(), 1);
let alice_folder = a.vaults[0].path.clone();
let said = lune_core::membership::leave_hub(&mut a, &url, false).unwrap();
assert!(a.hubs.is_empty() && a.vaults.is_empty(), "{said:?}");
assert!(!alice_folder.exists());
mac.use_hub_credentials();
assert!(mac.hubs[0].members("Sandbox").unwrap().iter().all(|m| m.devices.is_empty() || m.person != "Alice"));
// A team whose hub is gone: leaving needs `forget`, and the folder stays.
let mut stale = device("http://127.0.0.1:9", &alice_w, "Old", &tmp.path().join("stale"));
let kept = tmp.path().join("stale-notes");
std::fs::create_dir_all(&kept).unwrap();
stale.vaults.push(lune_core::config::VaultConfig {
name: "Notes".into(),
path: kept.clone(),
remote: "http://127.0.0.1:9/git/1.git".into(),
branch: "main".into(),
hub_vault: Some(1),
hub_url: Some("http://127.0.0.1:9".into()),
});
assert!(lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", false).is_err());
lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", true).unwrap();
assert!(stale.hubs.is_empty() && stale.vaults.is_empty() && kept.exists());
}

View File

@@ -62,6 +62,7 @@ type Sheet =
| 'vault' | 'vault'
| { kind: 'compare'; vault: Vault; copy: string } | { kind: 'compare'; vault: Vault; copy: string }
| { kind: 'team'; p: Person } | { kind: 'team'; p: Person }
| { kind: 'delete'; v: Vault }
| { kind: 'restored'; p: Person; link: string }; | { kind: 'restored'; p: Person; link: string };
function store(key: string, value?: string): string | null { function store(key: string, value?: string): string | null {
@@ -565,6 +566,7 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
<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} run={run} cycleRole={cycleRole} remove={(m) => revoke(keyOf(m))} grant={grant} run={run}
compare={(copy) => setSheet({ kind: 'compare', vault: vault(sel.id), copy })} compare={(copy) => setSheet({ kind: 'compare', vault: vault(sel.id), copy })}
deleteVault={data.me.owner ? (v) => setSheet({ kind: 'delete', v }) : undefined}
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) && (
@@ -585,6 +587,10 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
<TeamDialog p={sheet.p} data={data} members={members} close={() => setSheet(null)} <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.`); }} /> 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 === 'delete' && (
<DeleteVaultDialog v={sheet.v} members={members} close={() => setSheet(null)}
confirm={() => { const v = sheet.v; setSheet(null); setSel(null); run(() => api.deleteVault(v.name), `${v.name} was deleted. Every device sends unshared work, then removes its copy.`); }} />
)}
{typeof sheet === 'object' && sheet?.kind === 'restored' && ( {typeof sheet === 'object' && sheet?.kind === 'restored' && (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) setSheet(null); }}> <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`}> <div className="dialog" role="dialog" aria-modal="true" aria-label={`${sheet.p.name} restored`}>
@@ -678,8 +684,8 @@ function Overview({ data, members, log, open, close, newVault, signOut }: {
); );
} }
function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete, run, compare }: { function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete, run, compare, deleteVault }: {
v: Vault; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void; v: Vault; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void; deleteVault?: (v: Vault) => 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; run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; compare: (copy: string) => void;
}) { }) {
@@ -744,10 +750,35 @@ function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, t
<p className="muted">Removing someone only affects this vault. Copies made elsewhere can't be recalled.</p> <p className="muted">Removing someone only affects this vault. Copies made elsewhere can't be recalled.</p>
</div> </div>
)} )}
{deleteVault && (
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16 }}>
<button className="btn btn-danger" onClick={() => deleteVault(v)}>Delete vault…</button>
</div>
)}
</> </>
); );
} }
/** Deleting a vault asks first: it ends everyone's access at once (team owner only). */
function DeleteVaultDialog({ v, members, close, confirm }: { v: Vault; members: Member[]; close: () => void; confirm: () => void }) {
const people = members.filter((m) => m.vault === v.id).length;
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`Delete ${v.name}?`}>
<h2 className="disp">Delete {v.name}?</h2>
<p style={{ margin: 0, lineHeight: 1.5 }}>
{plural(people, 'person', 'people')} lose access. Their devices first send anything not yet shared, then remove their copy{v.delete_from_devices ? '' : ' (or keep it read-only, as this vault is set)'}.
</p>
<p className="muted">The vault's history stays archived on the hub, so nothing is lost; the name {v.name} is free for a new vault. 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}>Delete vault</button>
</div>
</div>
</div>
);
}
function PersonPanel({ p, data, members, open, close, run, removeFromTeam, restore }: { 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>; removeFromTeam: (p: Person) => void; restore: (p: Person) => void; run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; removeFromTeam: (p: Person) => void; restore: (p: Person) => void;

View File

@@ -16,6 +16,7 @@ const FIRST_OPEN = 'This pilot build isn’t signed by Apple yet: the first time
/** On an invite page: download, then join from the app with this link. */ /** On an invite page: download, then join from the app with this link. */
export function JoinWithApp({ link }: { link: string }) { export function JoinWithApp({ link }: { link: string }) {
const r = useRelease(); const r = useRelease();
const [tried, setTried] = useState(false);
return ( return (
<> <>
<ol className="steps"> <ol className="steps">
@@ -24,8 +25,9 @@ export function JoinWithApp({ link }: { link: string }) {
{r?.mac && <span className="muted">Open the download and drag Lune to Applications, then open it. {FIRST_OPEN}</span>} {r?.mac && <span className="muted">Open the download and drag Lune to Applications, then open it. {FIRST_OPEN}</span>}
</li> </li>
<li> <li>
<a className="btn" href={`lune://join?link=${encodeURIComponent(link)}`}>Open Lune to join</a> <a className="btn" href={`lune://join?link=${encodeURIComponent(link)}`} onClick={() => setTried(true)}>Open Lune to join</a>
<span className="muted">Lune asks for a name for this Mac and where shared vaults should go. This link works once.</span> <span className="muted">Lune asks for a name for this Mac and where shared vaults should go. This link works once.</span>
{tried && <span className="muted" role="status">Nothing happened? Install and open Lune first (step 1), then click again.</span>}
</li> </li>
</ol> </ol>
</> </>
@@ -36,10 +38,13 @@ export function JoinWithApp({ link }: { link: string }) {
export function MacSection() { export function MacSection() {
const r = useRelease(); const r = useRelease();
const [error, setError] = useState(''); const [error, setError] = useState('');
// A lune:// link does nothing visible when Lune isn't installed, so say what to do instead.
const [sent, setSent] = useState<string | null>(null);
const connect = async () => { const connect = async () => {
setError(''); setError('');
try { try {
const { code } = await api.pair(); const { code } = await api.pair();
setSent(code);
location.href = `lune://pair?hub=${encodeURIComponent(location.origin)}&code=${encodeURIComponent(code)}`; location.href = `lune://pair?hub=${encodeURIComponent(location.origin)}&code=${encodeURIComponent(code)}`;
} catch (e) { } catch (e) {
setError((e as Error).message); setError((e as Error).message);
@@ -52,6 +57,13 @@ export function MacSection() {
{r?.mac && <a className="btn btn-small" href={r.mac}>Get the Mac app</a>} {r?.mac && <a className="btn btn-small" href={r.mac}>Get the Mac app</a>}
<button className="btn btn-small" onClick={connect}>Connect this Mac</button> <button className="btn btn-small" onClick={connect}>Connect this Mac</button>
</div> </div>
{sent && (
<p className="muted" role="status" style={{ padding: '4px 6px 0' }}>
Opening Lune… Nothing happened? Lune isn't installed on this Mac yet: {r?.mac ? <a href={r.mac}>download it</a> : 'install it'}, open it, then
click Connect this Mac again. Or in Lune choose <b>I have a pairing code instead</b> and enter <b>{location.host}</b> with
the code <b>{sent}</b> (works once, for 10 minutes).
</p>
)}
{error && <p className="error" style={{ padding: '0 6px' }}>{error}</p>} {error && <p className="error" style={{ padding: '0 6px' }}>{error}</p>}
</section> </section>
); );

View File

@@ -101,6 +101,7 @@ export const api = {
undoRemove: (pending: number) => call<object>('POST', '/api/remove/undo', { pending }), undoRemove: (pending: number) => call<object>('POST', '/api/remove/undo', { pending }),
invite: (person: string, grants: { vault: string; role: Role }[]) => invite: (person: string, grants: { vault: string; role: Role }[]) =>
call<{ link: string }>('POST', '/api/invites', { person, grants }), call<{ link: string }>('POST', '/api/invites', { person, grants }),
deleteVault: (name: string) => call<{ devices: number }>('POST', '/api/vaults/delete', { vault: name }),
createVault: (name: string) => call<object>('POST', '/api/vaults', { name }), createVault: (name: string) => call<object>('POST', '/api/vaults', { name }),
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 }),

View File

@@ -233,12 +233,47 @@ function CompareSheet({ vault, copy, close, done }: { vault: string; copy: strin
); );
} }
/** Leaving a team on this Mac. A team whose hub is gone can be forgotten here instead. */
function LeaveSheet({ team, close, done }: { team: string; close: () => void; done: (msg: string) => void }) {
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const leave = async (forget: boolean) => {
setBusy(true);
setError('');
try {
done(await invoke<string>('leave_team', { team, forget }));
} catch (e) {
setError(String(e));
} finally {
setBusy(false);
}
};
const unreachable = error.includes("can't reach");
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`Leave ${host(team)}?`}>
<h2 className="disp">Leave {host(team)}?</h2>
<p className="muted">This Mac hands anything not yet shared to that team, then stops syncing its vaults. The team can add you back later.</p>
{error && <p className="error">{error}</p>}
{unreachable && <p className="muted">If that team is gone for good, forget it on this Mac only: its folders stay where they are, no longer synced.</p>}
<div className="actions">
<button className="btn" onClick={close}>Cancel</button>
{unreachable
? <button className="btn btn-danger" disabled={busy} onClick={() => leave(true)}>Forget it on this Mac</button>
: <button className="btn btn-danger" disabled={busy} onClick={() => leave(false)}>{busy ? 'Leaving…' : 'Leave'}</button>}
</div>
</div>
</div>
);
}
function App() { function App() {
const [o, setO] = useState<Overview | null>(null); const [o, setO] = useState<Overview | null>(null);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [toast, setToast] = useState(''); const [toast, setToast] = useState('');
const [comparing, setComparing] = useState<{ vault: string; copy: string } | null>(null); const [comparing, setComparing] = useState<{ vault: string; copy: string } | null>(null);
const [joining, setJoining] = useState(false); const [joining, setJoining] = useState(false);
const [leaving, setLeaving] = useState<string | null>(null);
const load = useCallback(() => invoke<Overview>('overview').then(setO).catch((e) => setError(String(e))), []); const load = useCallback(() => invoke<Overview>('overview').then(setO).catch((e) => setError(String(e))), []);
useEffect(() => { useEffect(() => {
@@ -292,7 +327,10 @@ function App() {
{o.teams.map((t) => ( {o.teams.map((t) => (
<li key={t}> <li key={t}>
<span>{host(t)}</span> <span>{host(t)}</span>
<span>
<button className="btn btn-small btn-ghost" onClick={() => act('open_canvas', { team: t }, '')}>Open canvas</button> <button className="btn btn-small btn-ghost" onClick={() => act('open_canvas', { team: t }, '')}>Open canvas</button>
<button className="btn btn-small btn-ghost" onClick={() => setLeaving(t)}>Leave</button>
</span>
</li> </li>
))} ))}
</ul> </ul>
@@ -310,6 +348,7 @@ function App() {
</> </>
)} )}
{comparing && <CompareSheet {...comparing} close={() => setComparing(null)} done={(msg) => { setComparing(null); setToast(msg); load(); }} />} {comparing && <CompareSheet {...comparing} close={() => setComparing(null)} done={(msg) => { setComparing(null); setToast(msg); load(); }} />}
{leaving && <LeaveSheet team={leaving} close={() => setLeaving(null)} done={(msg) => { setLeaving(null); setToast(msg); load(); }} />}
{toast && <div className="toast-d" role="status">{toast}</div>} {toast && <div className="toast-d" role="status">{toast}</div>}
</main> </main>
); );