From 0d68899cebdaaa871f3c47191297472a1a99a062 Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 11:25:27 -0800 Subject: [PATCH 1/3] fix: a new peer gets only what's written after pairing Catch-up sent every entry above the peer's `have`, and a new peer's is 0, so pairing with someone new after unpairing sent them everything written to the previous one. Pairing with a new key now records shared_after, my highest sequence number at that moment; shares() keeps catch-up and live sending above it, and off messages from before it. Pairing again with the same key keeps the floor, and pairings from before this have none (0), so they carry on as before. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + GLOSSARY.md | 2 +- src-tauri/src/chat.rs | 59 +++++++++++++++++++---- src-tauri/src/chat/protocol_tests.rs | 70 ++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ad9070..50c6aa4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ 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. - 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. diff --git a/GLOSSARY.md b/GLOSSARY.md index 639571f..155bb40 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -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**: diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index aec8a12..12b2029 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -253,6 +253,9 @@ 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, pairing: Option, session: Option, @@ -336,8 +339,12 @@ impl Core { }; let counter = |key| -> Result { 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()); @@ -358,6 +365,7 @@ impl Core { peer_has, peer_seen, seen, + shared_after, nearby: BTreeMap::new(), pairing: None, session: None, @@ -800,6 +808,7 @@ impl Core { db.delete("seen")?; db.delete("peer_version")?; db.delete("peer_features")?; + db.delete("shared_after")?; } let session = { let mut st = self.state(); @@ -807,6 +816,7 @@ impl Core { 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() @@ -1075,9 +1085,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. @@ -1184,13 +1195,27 @@ 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)?; + 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())); + if let Some(after) = shared_after { + st.shared_after = after; + } } - self.state().peer = Some((id, name.to_string())); self.changed(); Ok(()) } @@ -1527,7 +1552,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)); } } @@ -1714,6 +1743,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); diff --git a/src-tauri/src/chat/protocol_tests.rs b/src-tauri/src/chat/protocol_tests.rs index 93ee34a..4441723 100644 --- a/src-tauri/src/chat/protocol_tests.rs +++ b/src-tauri/src/chat/protocol_tests.rs @@ -254,6 +254,76 @@ 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 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(); From f4cd05227760f7dca49c2d439711637ffe2e99ff Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 11:28:19 -0800 Subject: [PATCH 2/3] fix: messages keep their author's name after pairing someone new The UI named every message that wasn't mine after the current peer, so after re-pairing, the previous peer's messages showed the new one's name. A people table (schema 6, filled from the current pairing) keeps everyone this computer has been paired with by their last known name; pairing and name changes keep it current, and unpairing leaves it. Status carries it, and the transcript names each author from it, through a key that only changes when a name does, so rows don't re-render. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + README.md | 1 + src-tauri/src/chat.rs | 24 +++++++++++- src-tauri/src/chat/protocol_tests.rs | 25 ++++++++++++ src-tauri/src/db.rs | 57 ++++++++++++++++++++++++++++ ui/src/api.ts | 2 + ui/src/components/Chat.tsx | 25 +++++++++--- ui/src/people.test.ts | 24 ++++++++++++ ui/src/people.ts | 17 +++++++++ 9 files changed, 169 insertions(+), 7 deletions(-) create mode 100644 ui/src/people.test.ts create mode 100644 ui/src/people.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 50c6aa4..173278f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ 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. diff --git a/README.md b/README.md index 61959a3..2d3ffe4 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index 12b2029..6f771e1 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -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, + /// 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, pub pairing: Option, pub notice: Option, /// Set when I went away with `/away`. Away from being idle isn't shown: by the time I @@ -257,6 +260,8 @@ struct State { /// write after it (see `shares`). 0 for pairings from before 0.8. shared_after: u64, nearby: BTreeMap, + /// See `Status::people`: id to name. + people: BTreeMap, pairing: Option, session: Option, next_generation: u64, @@ -348,6 +353,7 @@ impl Core { 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; @@ -367,6 +373,7 @@ impl Core { seen, shared_after, nearby: BTreeMap::new(), + people, pairing: None, session: None, next_generation: 0, @@ -427,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), @@ -1203,6 +1215,7 @@ impl Core { 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())?; @@ -1212,6 +1225,7 @@ impl Core { { 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; } @@ -1223,12 +1237,18 @@ impl Core { 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(()) diff --git a/src-tauri/src/chat/protocol_tests.rs b/src-tauri/src/chat/protocol_tests.rs index 4441723..6f66f1f 100644 --- a/src-tauri/src/chat/protocol_tests.rs +++ b/src-tauri/src/chat/protocol_tests.rs @@ -306,6 +306,31 @@ async fn a_new_peer_gets_only_what_is_written_after_pairing() { 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(); diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 2e7ad44..a0b1d44 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -257,9 +257,41 @@ impl Db { db.0.execute_batch(if result.is_ok() { "COMMIT" } else { "ROLLBACK" })?; result?; } + if version < 6 { + // 0.8: everyone this computer has been paired with, by their last known name, + // so their messages keep it after pairing with someone new. + db.0.execute_batch( + "BEGIN; + CREATE TABLE people (id TEXT PRIMARY KEY, name TEXT NOT NULL); + INSERT INTO people (id, name) + SELECT CAST(id.value AS TEXT), COALESCE(CAST(name.value AS TEXT), '') + FROM settings id LEFT JOIN settings name ON name.key = 'peer_name' + WHERE id.key = 'peer_id'; + PRAGMA user_version = 6; + COMMIT;", + )?; + } Ok(db) } + /// Everyone this computer has been paired with, as (id, last known name). + pub fn people(&self) -> Result> { + let mut stmt = self.0.prepare_cached("SELECT id, name FROM people ORDER BY id")?; + let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?; + Ok(rows.collect::>()?) + } + + /// Remembers `id`'s name, replacing an older one. + pub fn set_person(&self, id: &str, name: &str) -> Result<()> { + self.0 + .prepare_cached( + "INSERT INTO people (id, name) VALUES (?1, ?2) + ON CONFLICT (id) DO UPDATE SET name = excluded.name", + )? + .execute(params![id, name])?; + Ok(()) + } + /// Starts the countdown on `author`'s vanishing messages up to `up_to` (they've been /// seen): each vanishes its lifetime after `now`. Returns the ones started. pub fn start_vanish(&self, author: &str, up_to: u64, now: i64) -> Result> { @@ -1012,6 +1044,31 @@ mod tests { assert!(db.all().unwrap().iter().all(|m| m.author == "peer"), "never shown"); } + #[test] + fn people_from_before_0_8_are_kept() { + let path = std::env::temp_dir().join(format!( + "tightbeam-people-{}.db", + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + { + // A database from 0.7, paired with Bob. + let db = Db::open(&path).unwrap(); + db.set("peer_id", "bob-id").unwrap(); + db.set("peer_name", "Bob").unwrap(); + db.0.execute_batch("DROP TABLE people; PRAGMA user_version = 5;").unwrap(); + } + let db = Db::open(&path).unwrap(); + assert_eq!(db.people().unwrap(), [("bob-id".to_string(), "Bob".to_string())]); + db.set_person("bob-id", "Robert").unwrap(); + db.set_person("carol-id", "Carol").unwrap(); + let names: Vec<_> = db.people().unwrap().into_iter().map(|(_, name)| name).collect(); + assert_eq!(names, ["Robert", "Carol"]); + drop(db); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } + } + #[test] fn edits_and_deletes() { let db = Db::open(Path::new(":memory:")).unwrap(); diff --git a/ui/src/api.ts b/ui/src/api.ts index e002ae8..6e369d2 100644 --- a/ui/src/api.ts +++ b/ui/src/api.ts @@ -28,6 +28,8 @@ export interface Status { /** Highest of my sequence numbers the peer has seen. Always 0 with peers before 0.3. */ peer_seen: number nearby: Person[] + /** Everyone I've been paired with, by their last known name, to label their messages. */ + people: Person[] pairing: PairPrompt | null notice: string | null /** Set when I went away with `/away`. Away from being idle isn't shown to me. */ diff --git a/ui/src/components/Chat.tsx b/ui/src/components/Chat.tsx index 53ce8ba..4a512be 100644 --- a/ui/src/components/Chat.tsx +++ b/ui/src/components/Chat.tsx @@ -11,7 +11,7 @@ import { Trash2Icon, XIcon, } from 'lucide-react' -import { memo, useEffect, useRef, useState } from 'react' +import { memo, useEffect, useMemo, useRef, useState } from 'react' import { api, type Message as ChatMessage, type Quote, type Reaction } from '@/api' import { type Command, parse, suggest } from '@/commands' @@ -51,6 +51,7 @@ import { import { Spinner } from '@/components/ui/spinner' import { Textarea } from '@/components/ui/textarea' import { formatDuration, formatUntil } from '@/lib/duration' +import { namer, peopleKey } from '@/people' import { addMessage, clearHistory, @@ -192,7 +193,7 @@ function Header() { const dayOf = (m: ChatMessage) => new Date(m.ts).toDateString() function Transcript() { - const { messages, hasOlder, loadingOlder, myId, myName, peerName, peerHas, peerSeen } = + const { messages, hasOlder, loadingOlder, myId, myName, peerName, people, peerHas, peerSeen } = useSelector( store, (s) => ({ @@ -202,11 +203,14 @@ function Transcript() { myId: s.status?.me.id ?? '', myName: s.status?.me.name || 'You', peerName: s.status?.peer?.name || 'Them', + people: peopleKey(s.status?.people), peerHas: s.status?.peer_has ?? 0, peerSeen: s.status?.peer_seen ?? 0, }), { compare: shallow }, ) + // Stable while nobody's name changes, so the memoized rows stay put. + const nameOf = useMemo(() => namer(people, myId, peerName), [people, myId, peerName]) if (messages.length === 0) { return ( @@ -223,6 +227,7 @@ function Transcript() { myId={myId} myName={myName} peerName={peerName} + nameOf={nameOf} peerHas={peerHas} peerSeen={peerSeen} /> @@ -258,6 +263,7 @@ function VirtualTranscript({ myId, myName, peerName, + nameOf, peerHas, peerSeen, }: { @@ -267,6 +273,7 @@ function VirtualTranscript({ myId: string myName: string peerName: string + nameOf: (author: string) => string peerHas: number peerSeen: number }) { @@ -338,6 +345,7 @@ function VirtualTranscript({ myId={myId} myName={myName} peerName={peerName} + nameOf={nameOf} newDay={!prev || dayOf(prev) !== dayOf(m)} groupStart={!prev || !sameGroup(prev, m)} groupEnd={!next || !sameGroup(m, next)} @@ -373,6 +381,7 @@ const Row = memo(function Row({ myId, myName, peerName, + nameOf, newDay, groupStart, groupEnd, @@ -384,7 +393,10 @@ const Row = memo(function Row({ receipt: Receipt | null myId: string myName: string + /** Whoever I'm paired with now. */ peerName: string + /** An author's name: "You" for me, and the name they last had for anyone else. */ + nameOf: (author: string) => string newDay: boolean /** First in its group: space above it. */ groupStart: boolean @@ -397,7 +409,6 @@ const Row = memo(function Row({ const when = new Date(message.ts) const mine = receipt !== null const align = mine ? 'end' : 'start' - const nameOf = (author: string) => (author === myId ? 'You' : peerName) const myReaction = message.reactions.find((r) => r.author === myId)?.emoji // Picking my current reaction again takes it back. const react = (emoji: string) => @@ -442,7 +453,7 @@ const Row = memo(function Row({ ) : ( - {mine ? myName : peerName}{' '} + {mine ? myName : nameOf(message.author)}{' '} )} @@ -479,7 +490,11 @@ const Row = memo(function Row({ {file ? ( <> {/* Keyed by state: a picture that failed to load gets another go once it comes back. */} - + {(message.text || message.edited) && (
{words}
)} diff --git a/ui/src/people.test.ts b/ui/src/people.test.ts new file mode 100644 index 0000000..8b522c1 --- /dev/null +++ b/ui/src/people.test.ts @@ -0,0 +1,24 @@ +import { expect, test } from 'bun:test' + +import { namer, peopleKey } from './people' + +const people = [ + { id: 'bob', name: 'Bob' }, + { id: 'carol', name: 'Carol' }, +] + +test('each author keeps their own name', () => { + const nameOf = namer(peopleKey(people), 'me', 'Carol') + expect(['me', 'bob', 'carol'].map(nameOf)).toEqual(['You', 'Bob', 'Carol']) +}) + +test('anyone unknown gets the fallback', () => { + expect(namer(peopleKey(undefined), 'me', 'Them')('stranger')).toBe('Them') + expect(namer(peopleKey([{ id: 'x', name: '' }]), 'me', 'Them')('x')).toBe('Them') +}) + +test('the key changes only when the names do', () => { + const copy = people.map((p) => ({ ...p })) + expect(peopleKey(copy)).toBe(peopleKey(people)) + expect(peopleKey([people[0], { id: 'carol', name: 'C' }])).not.toBe(peopleKey(people)) +}) diff --git a/ui/src/people.ts b/ui/src/people.ts new file mode 100644 index 0000000..2c7cf08 --- /dev/null +++ b/ui/src/people.ts @@ -0,0 +1,17 @@ +// Whose name a message shows: mine, the peer's, or someone this computer was paired with +// before, by the name they last had. + +import type { Person } from './api' + +/** + * The people in `Status`, as one string: it stays equal across status updates that don't + * change any names, so selecting it doesn't re-render the transcript. + */ +export const peopleKey = (people: Person[] | undefined) => + JSON.stringify((people ?? []).map((p) => [p.id, p.name])) + +/** Names authors: "You" for me, otherwise their last known name, or else `fallback`. */ +export function namer(key: string, myId: string, fallback: string): (author: string) => string { + const names = new Map(JSON.parse(key)) + return (author) => (author === myId ? 'You' : names.get(author) || fallback) +} From d4a2323fe47bab22c9494e9a8645d1155cccad8c Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 11:29:06 -0800 Subject: [PATCH 3/3] test: a new pairing starts clean After unpairing, nothing of the previous peer's stays: no receipts, no version, not after a restart either. Someone new on an older build then gets a Seen of 0, and neither vanishing messages nor files. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/chat/protocol_tests.rs | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src-tauri/src/chat/protocol_tests.rs b/src-tauri/src/chat/protocol_tests.rs index 6f66f1f..2434525 100644 --- a/src-tauri/src/chat/protocol_tests.rs +++ b/src-tauri/src/chat/protocol_tests.rs @@ -932,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)); +}