Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Changes people using Tightbeam will notice. Add a line under **Unreleased** as t

## Unreleased

- After unpairing and pairing with someone new, they get only the messages written from then on. Before, they also received every message sent to the previous person. Editing or deleting those older messages stays on your computer.
- Messages from someone you were paired with before keep their name, instead of showing the name of whoever you're paired with now.
- Clicking the quote in a reply jumps to the original message even when it's further back than the history loaded so far. Before, it did nothing until you'd scrolled back that far.
- A reply quoting a vanishing message shows "Message vanished" as soon as it vanishes, instead of "Deleted message" until the app restarts.

Expand Down
2 changes: 1 addition & 1 deletion GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ The one other person's app this one is paired with. Before pairing, the apps nea
_Avoid_: contact, friend, remote

**Pairing**:
Two apps agreeing to trust each other's key, after both screens show the same code. Each app pairs with one peer at a time.
Two apps agreeing to trust each other's key, after both screens show the same code. Each app pairs with one peer at a time, and a new peer gets only what's written after pairing with them.
_Avoid_: linking, connecting

**Session**:
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Windows and macOS. Rust + [Tauri](https://tauri.app) for the app, [iroh](https:/
ui/src/api.ts typed wrappers for the Rust commands, plus the shared types
ui/src/store.ts app state (TanStack Store), fed by events from Rust; history paging
ui/src/transcript.ts the transcript: what a page, a live message or an update does to it
ui/src/people.ts whose name each message shows
ui/src/commands.ts slash commands
ui/src/components/ the screens: Setup, Pair, Chat, Search, Files, PairDialog, Notice
ui/src/components/ui/ shadcn/ui components (generated; update with the shadcn CLI)
Expand Down
83 changes: 73 additions & 10 deletions src-tauri/src/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,9 @@ pub struct Status {
/// Highest of my sequence numbers the peer has seen. Mine at or below are seen.
pub peer_seen: u64,
pub nearby: Vec<Person>,
/// Everyone I've been paired with, by their last known name, to label their messages
/// (the peer's, and anyone's from before).
pub people: Vec<Person>,
pub pairing: Option<PairPrompt>,
pub notice: Option<String>,
/// Set when I went away with `/away`. Away from being idle isn't shown: by the time I
Expand Down Expand Up @@ -253,7 +256,12 @@ struct State {
peer_seen: u64,
/// Highest of the peer's sequence numbers I've seen; what our `Seen` frames say.
seen: u64,
/// My highest sequence number when I paired with this peer: they get only what I
/// write after it (see `shares`). 0 for pairings from before 0.8.
shared_after: u64,
nearby: BTreeMap<String, String>,
/// See `Status::people`: id to name.
people: BTreeMap<String, String>,
pairing: Option<Pairing>,
session: Option<Session>,
next_generation: u64,
Expand Down Expand Up @@ -336,11 +344,16 @@ impl Core {
};
let counter =
|key| -> Result<u64> { Ok(db.get_str(key)?.and_then(|s| s.parse().ok()).unwrap_or(0)) };
let (peer_has, peer_seen, seen) =
(counter("peer_has")?, counter("peer_seen")?, counter("seen")?);
let (peer_has, peer_seen, seen, shared_after) = (
counter("peer_has")?,
counter("peer_seen")?,
counter("seen")?,
counter("shared_after")?,
);
let peer_version = db.get_str("peer_version")?;
let peer_features = features_from(db.get_str("peer_features")?.as_deref());
let dnd_until = db.get_str("dnd_until")?.and_then(|s| s.parse().ok());
let people = db.people()?.into_iter().collect();

let net = network(secret).await?;
let discoveries = net.discoveries().await;
Expand All @@ -358,7 +371,9 @@ impl Core {
peer_has,
peer_seen,
seen,
shared_after,
nearby: BTreeMap::new(),
people,
pairing: None,
session: None,
next_generation: 0,
Expand Down Expand Up @@ -419,6 +434,11 @@ impl Core {
.iter()
.map(|(id, name)| Person { id: id.clone(), name: name.clone() })
.collect(),
people: st
.people
.iter()
.map(|(id, name)| Person { id: id.clone(), name: name.clone() })
.collect(),
pairing: st.pairing.as_ref().map(|p| p.prompt.clone()),
notice: st.notice.clone(),
away: st.away.clone().filter(|_| st.away_by_hand),
Expand Down Expand Up @@ -800,13 +820,15 @@ impl Core {
db.delete("seen")?;
db.delete("peer_version")?;
db.delete("peer_features")?;
db.delete("shared_after")?;
}
let session = {
let mut st = self.state();
st.peer = None;
st.peer_has = 0;
st.peer_seen = 0;
st.seen = 0;
st.shared_after = 0;
st.peer_version = None;
st.peer_features.clear();
st.session.take()
Expand Down Expand Up @@ -1075,9 +1097,10 @@ impl Core {
}
generation
};
for wire in
self.db().since(&self.id(), their_have)?.into_iter().filter_map(Entry::into_wire)
{
let shared_after = self.state().shared_after;
let mine = self.db().since(&self.id(), their_have.max(shared_after))?;
let shared = mine.into_iter().filter(|e| shares(e, shared_after, &peer_str));
for wire in shared.filter_map(Entry::into_wire) {
let _ = out.send(Frame::Msg(wire));
}
// Covers anything seen while we were apart.
Expand Down Expand Up @@ -1184,26 +1207,48 @@ impl Core {
self.net.advertise(&self.name());
}

/// Pairs with `id`. Someone new gets only what I write from now on; pairing again
/// with the same key carries on as before.
fn save_peer(&self, id: EndpointId, name: &str) -> Result<()> {
{
let known = self.peer_id() == Some(id);
let shared_after = {
let db = self.db();
db.set("peer_id", id.to_string())?;
db.set("peer_name", name)?;
db.set_person(&id.to_string(), name)?;
let shared_after = if known { None } else { Some(db.max_seq(&self.id())?) };
if let Some(after) = shared_after {
db.set("shared_after", after.to_string())?;
}
shared_after
};
{
let mut st = self.state();
st.peer = Some((id, name.to_string()));
st.people.insert(id.to_string(), name.to_string());
if let Some(after) = shared_after {
st.shared_after = after;
}
}
self.state().peer = Some((id, name.to_string()));
self.changed();
Ok(())
}

fn update_peer_name(&self, name: &str) -> Result<()> {
let name = clean(name, MAX_NAME_CHARS);
let mut st = self.state();
if let Some((_, current)) = &mut st.peer
if let Some((id, current)) = &mut st.peer
&& *current != name
{
*current = name.clone();
let id = id.to_string();
st.people.insert(id.clone(), name.clone());
drop(st);
self.db().set("peer_name", &name)?;
{
let db = self.db();
db.set("peer_name", &name)?;
db.set_person(&id, &name)?;
}
self.changed();
}
Ok(())
Expand Down Expand Up @@ -1527,7 +1572,11 @@ impl Core {

/// Sends one of my entries now, if connected. Otherwise it goes with the catch-up.
fn send_live(&self, entry: Entry) {
if let (Some(s), Some(wire)) = (&self.state().session, entry.into_wire()) {
let st = self.state();
let (Some(s), Some((peer, _))) = (&st.session, &st.peer) else { return };
if shares(&entry, st.shared_after, &peer.to_string())
&& let Some(wire) = entry.into_wire()
{
let _ = s.out.send(Frame::Msg(wire));
}
}
Expand Down Expand Up @@ -1714,6 +1763,20 @@ impl Drop for Progress {
}
}

/// Whether one of my entries goes to `peer`: only what I wrote after pairing with them
/// (`shared_after`), and only about messages they have, theirs or mine since then. A
/// reply always goes: its text is new, and a quote they don't have shows as missing.
fn shares(entry: &Entry, shared_after: u64, peer: &str) -> bool {
let about = match &entry.kind {
Kind::Reaction { to } | Kind::Edit { of: to } | Kind::Delete { of: to } => Some(to),
Kind::Message { .. } | Kind::Inert { .. } => None,
};
entry.seq > shared_after
&& about.is_none_or(|to| {
to.author == peer || (to.author == entry.author && to.seq > shared_after)
})
}

/// Aborts a task when dropped.
struct AbortOnDrop(tokio::task::AbortHandle);

Expand Down
129 changes: 129 additions & 0 deletions src-tauri/src/chat/protocol_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,101 @@ async fn a_new_session_replaces_a_half_dead_one() {

// ---- Catch-up ------------------------------------------------------------------------

#[test]
fn only_entries_from_after_pairing_are_shared() {
let (me, peer) = ("me", "carol");
let at = |author: &str, seq| Ref { author: author.into(), seq };
let entry = |seq, kind| Entry { kind, ..Entry::message(me, seq, 1, "x") };
let after = 4;
assert!(!shares(&Entry::message(me, 4, 1, "for bob"), after, peer));
assert!(shares(&Entry::message(me, 5, 1, "for carol"), after, peer));
// About her messages, or mine since: shared.
assert!(shares(&entry(5, Kind::Reaction { to: at(peer, 1) }), after, peer));
assert!(shares(&entry(6, Kind::Edit { of: at(me, 5) }), after, peer));
// About mine from before, or bob's: kept here.
assert!(!shares(&entry(6, Kind::Edit { of: at(me, 3) }), after, peer));
assert!(!shares(&entry(6, Kind::Delete { of: at(me, 3) }), after, peer));
assert!(!shares(&entry(6, Kind::Reaction { to: at("bob", 2) }), after, peer));
// A reply's text is new, whatever it quotes.
let reply = Kind::Message { reply_to: Some(at("bob", 2)), vanish: None, file: None };
assert!(shares(&entry(6, reply), after, peer));
}

#[tokio::test(start_paused = true)]
async fn a_new_peer_gets_only_what_is_written_after_pairing() {
let world = World::new();
let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await);
world.pair(&alice, &bob).await;
let for_bob = alice.send_message("a secret for bob", None, None).unwrap();
let from_bob = bob.send_message("one for alice", None, None).unwrap();
until("both arrive", || alice.texts().len() == 2 && bob.texts().len() == 2).await;
alice.unpair().unwrap();
bob.stop().await;

let carol = world.start("carol", "Carol").await;
world.pair(&alice, &carol).await;
// Alice changes her old conversation: it stays on her computer.
let old = Ref { author: alice.id(), seq: for_bob.seq };
alice.edit(old.clone(), "still a secret").unwrap();
let bobs = Ref { author: from_bob.author.clone(), seq: from_bob.seq };
assert!(alice.react(bobs, "👍").is_err(), "bob's messages are no one's to react to now");
alice.delete(old.clone()).unwrap();
assert!(alice.find(&old).unwrap().deleted, "done here");

let hi = alice.send_message("hi carol", None, None).unwrap();
until("carol gets it", || carol.texts() == ["hi carol"]).await;
let to_carol = Ref { author: alice.id(), seq: hi.seq };
alice.edit(to_carol.clone(), "hi carol!").unwrap();
until("and the edit", || carol.find(&to_carol).is_some_and(|m| m.edited)).await;

let reached: Vec<_> = carol.db().since(&alice.id(), 0).unwrap();
assert_eq!(reached.len(), 2, "the message and its edit, nothing from before: {reached:?}");
until("delivered", || alice.status().peer_has == hi.seq + 1).await;
}

#[tokio::test(start_paused = true)]
async fn messages_keep_their_author_s_name_after_pairing_someone_new() {
let world = World::new();
let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await);
world.pair(&alice, &bob).await;
let names = |peer: &Peer| -> Vec<(String, String)> {
peer.status().people.into_iter().map(|p| (p.id, p.name)).collect()
};
assert_eq!(names(&alice), [(bob.id(), "Bob".to_string())]);
bob.set_name("Robert").unwrap();
until("alice hears his new name", || names(&alice) == [(bob.id(), "Robert".into())]).await;

alice.unpair().unwrap();
let carol = world.start("carol", "Carol").await;
world.pair(&alice, &carol).await;
let mut expected = vec![(bob.id(), "Robert".to_string()), (carol.id(), "Carol".to_string())];
expected.sort();
assert_eq!(names(&alice), expected, "bob's name stays for his messages");

// And it lasts across a restart.
alice.stop().await;
let alice = world.start("alice", "Alice").await;
assert_eq!(names(&alice), expected);
}

#[tokio::test(start_paused = true)]
async fn pairing_again_with_the_same_key_still_catches_up() {
let world = World::new();
let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await);
world.pair(&alice, &bob).await;
alice.send_message("before", None, None).unwrap();
until("bob gets it", || bob.texts() == ["before"]).await;
bob.stop().await;
until("alice notices", || !alice.status().connected).await;
alice.send_message("while he was off", None, None).unwrap();

// He asks again (say, from the pairing screen); she already trusts his key.
let bob = world.start("bob", "Bob").await;
until("reconnected", || alice.status().connected && bob.status().connected).await;
until("he catches up", || bob.texts() == ["before", "while he was off"]).await;
assert_eq!(alice.state().shared_after, 0, "the first pairing's floor stands");
}

#[tokio::test(start_paused = true)]
async fn catch_up_after_being_offline() {
let world = World::new();
Expand Down Expand Up @@ -837,3 +932,37 @@ async fn do_not_disturb_ends_on_its_own() {
assert!(bob.set_dnd(Some(world.clock.now_ms() - 1)).is_ok(), "a time past turns it off");
assert!(!bob.dnd());
}

#[tokio::test(start_paused = true)]
async fn a_new_pairing_starts_clean() {
let world = World::new();
let (alice, bob) = (world.start("alice", "Alice").await, world.start("bob", "Bob").await);
world.pair(&alice, &bob).await;
alice.send_message("hi", None, None).unwrap();
bob.send_message("hi yourself", None, None).unwrap();
until("both arrive", || alice.texts().len() == 2 && bob.texts().len() == 2).await;
alice.mark_seen().unwrap();
bob.mark_seen().unwrap();
until("receipts", || alice.status().peer_seen == 1).await;
alice.unpair().unwrap();
bob.stop().await;

let clean = |alice: &Peer| {
let (status, info) = (alice.status(), alice.connection_info());
assert!(status.peer.is_none());
assert_eq!((status.peer_has, status.peer_seen), (0, 0));
assert_eq!(info.peer_version, None);
};
clean(&alice);
alice.stop().await;
let alice = world.start("alice", "Alice").await;
clean(&alice); // nothing of bob's came back from the log either

// Someone new, on an older build: nothing bob's build allowed carries over.
let mut old = Played::pair(&world, &alice, hello_from(None, &[])).await;
let seen = old.next("her seen receipt", |f| matches!(f, Frame::Seen { .. })).await;
assert!(matches!(seen, Frame::Seen { up_to: 0 }), "she's seen nothing of theirs: {seen:?}");
assert!(alice.send_message("psst", None, Some(60)).is_err(), "no vanishing messages");
assert!(alice.send_file(b"png", picture()).is_err(), "no files");
assert_eq!((alice.status().peer_has, alice.status().peer_seen), (0, 0));
}
Loading
Loading