0.1.4: settings decide where a vault shares; leaving always finishes

- A folder found sharing somewhere other than its settings say is set back
  (every 30 s, under the vault's op lock). Two programs racing — the 0.1.1
  CLI upload against the 0.1.2 app's check-in — had left Brain's settings on
  the hub and its folder on Gitea, so it kept "syncing" to the wrong place.
- Leaving hands over to the vault's own hub, never to wherever the folder
  points. If the hub refuses the history (an older entry has a possible
  secret), the device hands over its current notes as one entry with those
  lines replaced, instead of retrying forever with the folder read-only.
- The app says "leaving" while that's in progress instead of "Synced".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 17:49:49 +07:00
parent 4ab9d580b8
commit fdcdecf0f1
9 changed files with 160 additions and 8 deletions

8
Cargo.lock generated
View File

@@ -2581,7 +2581,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]] [[package]]
name = "lune-core" name = "lune-core"
version = "0.1.3" version = "0.1.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.23.1", "base64 0.23.1",
@@ -2601,7 +2601,7 @@ dependencies = [
[[package]] [[package]]
name = "lune-desktop" name = "lune-desktop"
version = "0.1.3" version = "0.1.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
@@ -2621,7 +2621,7 @@ dependencies = [
[[package]] [[package]]
name = "lunehub" name = "lunehub"
version = "0.1.3" version = "0.1.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -2642,7 +2642,7 @@ dependencies = [
[[package]] [[package]]
name = "lunesync" name = "lunesync"
version = "0.1.3" version = "0.1.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",

View File

@@ -4,5 +4,5 @@ members = ["core", "cli", "hub", "desktop"]
# One version for every part: the hub offers clients by it (D3). # One version for every part: the hub offers clients by it (D3).
[workspace.package] [workspace.package]
version = "0.1.3" version = "0.1.4"
license = "AGPL-3.0-only" license = "AGPL-3.0-only"

View File

@@ -190,6 +190,8 @@ pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<Strin
std::thread::sleep(Duration::from_millis(250)); std::thread::sleep(Duration::from_millis(250));
}; };
let _op = state::op_lock(&v.git_dir)?; let _op = state::op_lock(&v.git_dir)?;
// The handover goes to this vault's own hub, whatever the folder was last pointed at.
v.follow(&vc.remote)?;
let mut head = None; let mut head = None;
if !d.without_saving { if !d.without_saving {
@@ -205,8 +207,14 @@ pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<Strin
if !d.without_saving if !d.without_saving
&& let Some(h) = v.head_commit()? && let Some(h) = v.head_commit()?
{ {
v.hand_over(&format!("refs/handover/{}", d.id))?; let dst = format!("refs/handover/{}", d.id);
head = Some(h.id().to_string()); head = Some(match v.hand_over(&dst) {
Ok(()) => h.id().to_string(),
// Older history has something that looks like a secret, which the hub never takes: hand over the
// current notes instead, those lines replaced. Otherwise this device could never finish leaving.
Err(e) if format!("{e:#}").contains("didn't take the handover") => v.hand_over_current(&dst, REDACTED)?.to_string(),
Err(e) => return Err(e),
});
} }
link.departure_done(d.id, head)?; link.departure_done(d.id, head)?;

View File

@@ -105,6 +105,16 @@ pub fn is_running(git_dir: &Path) -> bool {
matches!(try_run_lock(git_dir), Ok(None)) matches!(try_run_lock(git_dir), Ok(None))
} }
/// Like `op_lock`, but gives up at once if someone else holds it.
pub fn try_op_lock(git_dir: &Path) -> Result<Option<Lock>> {
let file = open_lock(git_dir, "op.lock")?;
match file.try_lock() {
Ok(()) => Ok(Some(Lock(file))),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(e)) => Err(e.into()),
}
}
/// Serializes every change to the vault's history between the background runner and one-off commands. /// Serializes every change to the vault's history between the background runner and one-off commands.
pub fn op_lock(git_dir: &Path) -> Result<Lock> { pub fn op_lock(git_dir: &Path) -> Result<Lock> {
let file = open_lock(git_dir, "op.lock")?; let file = open_lock(git_dir, "op.lock")?;

View File

@@ -118,6 +118,7 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" }); let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
let (level, headline) = match &st.last_error { let (level, headline) = match &st.last_error {
_ if v.is_local() => ("current", "Only on this device · not shared".to_string()), _ if v.is_local() => ("current", "Only on this device · not shared".to_string()),
_ if state::lune_dir(&v.git_dir).join("leaving").exists() => ("behind", "Access ended · leaving: handing over what wasn't shared".to_string()),
None if out.read_only && waiting > 0 => ("current", format!("Up to date · {changes} kept here, not shared (you have read access)")), None if out.read_only && waiting > 0 => ("current", format!("Up to date · {changes} kept here, not shared (you have read access)")),
None if out.read_only => ("current", "Up to date (read access)".to_string()), None if out.read_only => ("current", "Up to date (read access)".to_string()),
Some(e) if e == remote::TOO_OLD => ("behind", format!("Update Lune to keep syncing · {changes} saved here")), Some(e) if e == remote::TOO_OLD => ("behind", format!("Update Lune to keep syncing · {changes} saved here")),

View File

@@ -20,6 +20,7 @@ pub fn supervise(log: fn(&str, &str)) -> Result<()> {
let mut hub_check = Instant::now(); let mut hub_check = Instant::now();
// Each hub's last complaint, so an unreachable hub isn't logged every 30 s. // Each hub's last complaint, so an unreachable hub isn't logged every 30 s.
let mut hub_said: HashMap<String, String> = HashMap::new(); let mut hub_said: HashMap<String, String> = HashMap::new();
let mut follow_at = Instant::now();
while !STOP.load(Ordering::Relaxed) { while !STOP.load(Ordering::Relaxed) {
let mut config = Config::load()?; let mut config = Config::load()?;
config.use_hub_credentials(); config.use_hub_credentials();
@@ -56,6 +57,10 @@ pub fn supervise(log: fn(&str, &str)) -> Result<()> {
} }
} }
} }
if Instant::now() >= follow_at {
follow_at = Instant::now() + Duration::from_secs(30);
follow_settings(log);
}
// A vault that left (access ended) can come back later at the same place. // A vault that left (access ended) can come back later at the same place.
started.retain(|p| config.vaults.iter().any(|v| &v.path == p)); started.retain(|p| config.vaults.iter().any(|v| &v.path == p));
for cfg in &config.vaults { for cfg in &config.vaults {
@@ -92,6 +97,23 @@ pub fn supervise(log: fn(&str, &str)) -> Result<()> {
} }
/// Asks every running vault to save what has settled and share now (the menu's "Share now"). /// Asks every running vault to save what has settled and share now (the menu's "Share now").
/// Puts back any vault folder that shares somewhere other than its settings say, which another program (or an
/// older Lune) can leave behind. Done under the vault's op lock, with the settings read again inside it.
fn follow_settings(log: fn(&str, &str)) {
let Ok(config) = Config::load() else { return };
for cfg in &config.vaults {
let Ok(v) = crate::vault::Vault::open(cfg, &config.device_label()) else { continue };
let Ok(Some(_op)) = crate::state::try_op_lock(&v.git_dir) else { continue };
let Some(now) = Config::load().ok().and_then(|c| c.vaults.into_iter().find(|x| x.path == cfg.path)) else { continue };
match v.follow(&now.remote) {
Ok(true) if now.remote.is_empty() => log(&now.name, "set back to this device only, as its settings say"),
Ok(true) => log(&now.name, &format!("set back to sharing with {}, as its settings say", crate::upload::remote_host(&now.remote))),
Ok(false) => {}
Err(e) => log(&now.name, &format!("couldn't match its settings: {e:#}")),
}
}
}
pub fn share_now(config: &Config) { pub fn share_now(config: &Config) {
for vc in &config.vaults { for vc in &config.vaults {
let dir = crate::state::lune_dir(&vc.path.join(".git")); let dir = crate::state::lune_dir(&vc.path.join(".git"));

View File

@@ -290,6 +290,22 @@ impl Vault {
Ok(()) Ok(())
} }
/// Where this vault shares its history now, if anywhere.
pub fn remote_url(&self) -> Option<String> {
self.repo.find_remote("origin").ok().and_then(|r| r.url().ok().map(String::from))
}
/// Makes the folder share where its settings say: their remote, or nowhere for a vault on this device only.
/// The settings are what the app shows, so they win. Returns whether anything changed.
pub fn follow(&self, remote: &str) -> Result<bool> {
match (self.remote_url(), remote.is_empty()) {
(None, true) => Ok(false),
(Some(_), true) => self.unlink().map(|_| true),
(Some(url), false) if url == remote => Ok(false),
_ => self.relink(remote).map(|_| true),
}
}
/// A vault with no remote lives on this device only: it keeps saving history, and shares nowhere. /// A vault with no remote lives on this device only: it keeps saving history, and shares nowhere.
pub fn is_local(&self) -> bool { pub fn is_local(&self) -> bool {
self.repo.find_remote("origin").is_err() self.repo.find_remote("origin").is_err()
@@ -400,6 +416,45 @@ impl Vault {
/// Sends this device's whole history to `dst` on the remote (the hub's handover area for this device). /// Sends this device's whole history to `dst` on the remote (the hub's handover area for this device).
pub fn hand_over(&self, dst: &str) -> Result<()> { pub fn hand_over(&self, dst: &str) -> Result<()> {
self.push_handover(&self.branch_ref(), dst)
}
/// The current notes as one entry, for a handover the hub refused because older history has something that
/// looks like a secret (P3): every such line is replaced with `pointer`. It sits on top of the last shared
/// state, so reviewing it shows just what this device changed. Returns what was handed over.
pub fn hand_over_current(&self, dst: &str, pointer: &str) -> Result<Oid> {
let head = self.head_commit()?.context("nothing to hand over")?;
let tree = head.tree()?;
let mut cleaned = vec![];
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
if let Ok(blob) = e.to_object(&self.repo).and_then(|o| o.peel_to_blob()) {
let hits = secrets::scan_bytes(blob.content(), None, &HashSet::new());
if !hits.is_empty() {
let text = String::from_utf8_lossy(blob.content()).into_owned();
cleaned.push((format!("{dir}{}", e.name().unwrap_or_default()), secrets::replace_with_pointer(&text, &hits, None, pointer)));
}
}
TreeWalkResult::Ok
})?;
let mut update = TreeUpdateBuilder::new();
for (path, text) in &cleaned {
update.upsert(path, self.repo.blob(text.as_bytes())?, FileMode::Blob);
}
let tree = self.repo.find_tree(update.create_updated(&self.repo, &tree)?)?;
let parent = self.remote_commit()?;
let sig = self.signature()?;
let message = format!("Handed over by {} ({} with possible secrets removed)", self.label, cleaned.len());
let id = self.repo.commit(None, &sig, &sig, &message, &tree, &parent.iter().collect::<Vec<_>>())?;
const TEMP: &str = "refs/lune/handover";
self.repo.reference(TEMP, id, true, "lune: handover")?;
let sent = self.push_handover(TEMP, dst);
if let Ok(mut r) = self.repo.find_reference(TEMP) {
let _ = r.delete();
}
sent.map(|_| id)
}
fn push_handover(&self, src: &str, dst: &str) -> Result<()> {
let mut remote = self.repo.find_remote("origin")?; let mut remote = self.repo.find_remote("origin")?;
let rejected = RefCell::new(None::<String>); let rejected = RefCell::new(None::<String>);
let mut cb = remote::callbacks(); let mut cb = remote::callbacks();
@@ -411,7 +466,7 @@ impl Vault {
}); });
let mut opts = PushOptions::new(); let mut opts = PushOptions::new();
opts.remote_callbacks(cb); opts.remote_callbacks(cb);
remote.push(&[format!("+{}:{dst}", self.branch_ref())], Some(&mut opts))?; remote.push(&[format!("+{src}:{dst}")], Some(&mut opts))?;
drop(opts); drop(opts);
if let Some(why) = rejected.into_inner() { if let Some(why) = rejected.into_inner() {
bail!("the hub didn't take the handover: {why}"); bail!("the hub didn't take the handover: {why}");

View File

@@ -209,4 +209,5 @@ Record here: date, what changed, why, which decision number. Example:
- 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 — 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) - 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)
- 2026-10-29 — Moving a vault onto a hub (new): the team owner and anyone with Manage on a vault may create vaults, so they may upload one too (the app's **Upload**, `lunesync vault upload`). Only a vault that's on that device alone goes up; one on its own remote (GitHub, GitLab…) is **detached** first, and a check-in no longer moves a same-named vault off its own remote silently. Avoids one vault's notes living in two places (A3). (Sen) - 2026-10-29 — Moving a vault onto a hub (new): the team owner and anyone with Manage on a vault may create vaults, so they may upload one too (the app's **Upload**, `lunesync vault upload`). Only a vault that's on that device alone goes up; one on its own remote (GitHub, GitLab…) is **detached** first, and a check-in no longer moves a same-named vault off its own remote silently. Avoids one vault's notes living in two places (A3). (Sen)
- 2026-10-29 — A vault's settings decide where it shares: a folder found pointing elsewhere is set back. A leaving device whose older history has a possible secret hands over its current notes as one entry with those lines replaced, instead of never finishing (A6, P3). (Sen, after the Brain mix-up)
- 2026-10-29 — Community release without Apple signing, under AGPL-3.0-only; the public repo stays at git.senkensha.space. (Sen) - 2026-10-29 — Community release without Apple signing, under AGPL-3.0-only; the public repo stays at git.senkensha.space. (Sen)

View File

@@ -689,3 +689,58 @@ fn a_vault_moves_onto_the_hub_only_once_it_is_detached() {
assert_eq!(std::fs::read(o.root.join("idea.md")).unwrap(), b"second\n"); assert_eq!(std::fs::read(o.root.join("idea.md")).unwrap(), b"second\n");
assert_eq!(std::fs::read(o.root.join("later.md")).unwrap(), b"kept here\n"); assert_eq!(std::fs::read(o.root.join("later.md")).unwrap(), b"kept here\n");
} }
#[test]
fn leaving_finishes_even_when_the_folder_points_elsewhere_and_history_has_a_secret() {
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 ops = mac.hubs[0].create_vault("Ops").unwrap();
check_in(&mut mac);
let v = open(&mac, "Ops");
write_and_save(&v, "plan.md", "shared\n");
v.sync().unwrap();
// A line this device was told isn't a secret, which the hub never heard: it can't be shared.
std::fs::write(v.root.join("aws.md"), "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n").unwrap();
let hit = v.secret_holds().unwrap()[0].hits[0].clone();
secrets::allow(&v.git_dir, &hit, "aws.md").unwrap();
v.save_changes(None, &HashSet::new()).unwrap();
assert!(v.sync().is_err());
// And the folder was left pointing somewhere else (another program changed it), while the settings say the hub.
let elsewhere = tmp.path().join("elsewhere.git");
lune_core::git2::Repository::init_bare(&elsewhere).unwrap();
v.relink(&format!("file://{}", elsewhere.display())).unwrap();
drop(v);
// Deleting the vault: the device still finishes leaving, handing over to the hub, the key line replaced.
mac.use_hub_credentials();
mac.hubs[0].delete_vault("Ops").unwrap();
let said = check_in(&mut mac);
assert!(mac.vaults.is_empty(), "{said:?}");
let repo = lune_core::git2::Repository::open_bare(data.join(format!("repos/{}.git", ops.id))).unwrap();
let handover = repo.references_glob("refs/handover/*").unwrap().next().unwrap().unwrap().peel_to_commit().unwrap();
let blob = |name: &str| handover.tree().unwrap().get_name(name).unwrap().to_object(&repo).unwrap().peel_to_blob().unwrap().content().to_vec();
let aws = String::from_utf8(blob("aws.md")).unwrap();
assert!(!aws.contains("AKIA") && aws.contains("secret removed"), "{aws}");
assert_eq!(blob("plan.md"), b"shared\n");
assert!(lune_core::git2::Repository::open_bare(&elsewhere).unwrap().references().unwrap().count() == 0, "nothing went elsewhere");
}
#[test]
fn a_folder_follows_its_settings() {
let tmp = tempfile::TempDir::new().unwrap();
let a = tmp.path().join("a.git");
lune_core::git2::Repository::init_bare(&a).unwrap();
let (cfg, _, _) = vault::add("Notes", &tmp.path().join("notes"), &format!("file://{}", a.display()), "Mac").unwrap();
let v = Vault::open(&cfg, "Mac").unwrap();
assert!(!v.follow(&cfg.remote).unwrap());
v.relink("file:///somewhere/else.git").unwrap();
assert!(v.follow(&cfg.remote).unwrap());
assert_eq!(v.remote_url().as_deref(), Some(cfg.remote.as_str()));
assert!(v.follow("").unwrap() && v.is_local());
}