From 96ce9e723d9586170b96f3afc18a3bdf7f260c09 Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 01:29:30 +0100 Subject: [PATCH 1/8] Test that both Info.plists and the entitlements keep the camera entries that stop macOS killing mediad when it opens a camera --- crates/mediad/src/main.rs | 105 +++++++++++++++++++++++++++++++++++++- 1 file changed, 104 insertions(+), 1 deletion(-) diff --git a/crates/mediad/src/main.rs b/crates/mediad/src/main.rs index f5f6e2f0..92b9e53b 100644 --- a/crates/mediad/src/main.rs +++ b/crates/mediad/src/main.rs @@ -8,7 +8,8 @@ use std::process::ExitCode; /// responsible. Inside `tinyclient.app` that is the app, whose Info.plist says it. When mediad is /// responsible for itself (its parents were started by hand and are gone), this copy, in the /// section a single-file tool keeps its Info.plist in, is what the system reads; without one -/// the system kills the process the moment it opens the microphone. +/// the system kills the process the moment it opens the microphone. The camera is asked about +/// the same way, so the copy says why that is opened too. #[used] #[link_section = "__TEXT,__info_plist"] static INFO_PLIST: [u8; include_bytes!("../Info.plist").len()] = *include_bytes!("../Info.plist"); @@ -160,3 +161,105 @@ fn main() -> ExitCode { mediad::out::flush(); ExitCode::from(code) } + +#[cfg(test)] +mod tests { + use super::INFO_PLIST; + + /// What an XML plist holds for `key`: the tag of the value after the first `` with that + /// name, and the text between that value's tags, trimmed. `None` when there is no such key. + fn value<'a>(plist: &'a str, key: &str) -> Option<(&'a str, &'a str)> { + let mut found = false; + let mut commented = false; + // Each piece is one tag and the text up to the next tag. + for piece in plist.split('<').skip(1) { + // A comment runs to its `-->`, whatever stands inside it: a tag commented out is not read. + if commented || piece.starts_with("!--") { + commented = !piece.contains("-->"); + continue; + } + let Some((tag, text)) = piece.split_once('>') else { continue }; + // A closing tag, the header and the doctype are not an element. + if tag.starts_with(['/', '?', '!']) { + continue; + } + // `` and `` are one element, and an element may carry attributes. + let Some(name) = tag.strip_suffix('/').unwrap_or(tag).split_whitespace().next() else { continue }; + let text = text.trim(); + if found { + return Some((name, text)); + } + found = name == "key" && text == key; + } + None + } + + #[test] + fn a_plist_value_is_the_element_after_its_key() { + let plist = r#" + + + + One + Twoin a dict + Three + + Why & how + + Four + + Five + + Six + + Seven + + + Eight + after the comment + + +"#; + assert_eq!(value(plist, "One"), Some(("array", ""))); + assert_eq!(value(plist, "Two"), Some(("string", "in a dict"))); + assert_eq!(value(plist, "Three"), Some(("string", "Why & how"))); + assert_eq!(value(plist, "Four"), Some(("string", ""))); + assert_eq!(value(plist, "Five"), Some(("true", ""))); + assert_eq!(value(plist, "Six"), Some(("true", ""))); + assert_eq!(value(plist, "Seven"), Some(("false", ""))); + assert_eq!(value(plist, "Eight"), Some(("string", "after the comment"))); + assert_eq!(value(plist, "Nine"), None, "a key inside a comment is not in the plist"); + assert_eq!(value(plist, "Missing"), None); + assert_eq!(value("Last", "Last"), None, "a key with no value after it"); + } + + #[test] + fn both_info_plists_say_why_the_camera_is_opened() { + // macOS ends a process that opens a camera when the Info.plist of the app it holds + // responsible gives no reason, instead of asking the person (#1019). Inside + // `tinyclient.app` that is the app's plist, which `packaging/bundle.sh` makes from + // `packaging/Info.plist`. When mediad is responsible for itself, the system reads the copy + // embedded above. An empty reason tells the person nothing, so it fails too. + let embedded = std::str::from_utf8(&INFO_PLIST).expect("the embedded Info.plist is UTF-8"); + for (file, plist) in [ + ("packaging/Info.plist", include_str!("../../../packaging/Info.plist")), + ("crates/mediad/Info.plist", embedded), + ] { + let Some((tag, reason)) = value(plist, "NSCameraUsageDescription") else { + panic!("{file} does not say why the camera is opened") + }; + assert!(tag == "string" && !reason.is_empty(), "{file} holds NSCameraUsageDescription as <{tag}> `{reason}`"); + } + } + + #[test] + fn the_entitlements_allow_the_camera() { + // `packaging/bundle.sh` signs `packaging/entitlements.plist` into mediad and into the app. + // It is inert until the hardened runtime is turned on; from then on the camera needs it + // (#1019). + let Some((tag, _)) = value(include_str!("../../../packaging/entitlements.plist"), "com.apple.security.device.camera") else { + panic!("packaging/entitlements.plist has no camera entitlement") + }; + assert!(tag == "true", "packaging/entitlements.plist holds the camera entitlement as <{tag}/>"); + } +} From 63ef075cce47f23e66c7858c762a6c873385e541 Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 01:35:14 +0100 Subject: [PATCH 2/8] The Discord soundboard test waits for the gateway frame it checks, instead of reading it at once --- crates/chatd/tests/discord.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/chatd/tests/discord.rs b/crates/chatd/tests/discord.rs index 14cd30d1..3b863421 100644 --- a/crates/chatd/tests/discord.rs +++ b/crates/chatd/tests/discord.rs @@ -13588,7 +13588,9 @@ fn an_activity_a_stage_and_a_soundboard_are_part_of_a_discord_voice_channel() { }; assert!(sounds.iter().any(|sound| sound.name == "Boom" && sound.default), "{sounds:?}"); assert!(sounds.iter().any(|sound| sound.name == "Quack" && sound.guild_id.as_deref() == Some("4000")), "{sounds:?}"); - assert!(!world.discord.frames_of(31).is_empty(), "the guild soundboard was asked for"); + // The guild's sounds were pushed before chatd asked for them, so chatd answered at once. The + // fake's reader thread records the frame it wrote a moment later. + wait("the guild soundboard request", || (world.discord.frames_of(31).iter().any(|frame| frame["d"]["guild_ids"] == json!(["4000"]))).then_some(())); assert!(matches!( world.ask(Request::PlaySoundboard { conversation: world.key("4202"), sound_id: "b".into(), guild_id: None }), Response::Ok From 6b2a917b038c7ccbff91e049849c2d77cad1fadd Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 01:32:35 +0100 Subject: [PATCH 3/8] Test that the 2,000-per-conversation cap keeps a crowded Signal conversation whole and still trims a network that serves its messages again --- crates/chatd/src/store.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/chatd/src/store.rs b/crates/chatd/src/store.rs index 7faec748..8b268d04 100644 --- a/crates/chatd/src/store.rs +++ b/crates/chatd/src/store.rs @@ -5672,7 +5672,8 @@ impl Store { // Retention. /// Keeps the newest [`KEEP_MESSAGES`] of every conversation, and nothing older than `days` - /// (P4, [`KEEP_DAYS`] by default) unless the conversation was opened in that time. Runs + /// (P4, [`KEEP_DAYS`] by default) unless the conversation was opened in that time. Signal keeps + /// everything: no request brings one of its messages back. Runs /// shortly after the boot, never inside it (the sign-in has the store busy), then daily, /// and when P4 changes. Unsent messages are the user's and are never pruned. /// Returns how many rows went. @@ -7516,6 +7517,29 @@ mod tests { assert!(store.message(&key, "1").unwrap().is_some()); } + #[test] + fn pruning_trims_a_crowded_discord_conversation_and_leaves_a_crowded_signal_one_whole() { + // 2,100 each, all newer than the age rule: only the cap can delete them. + let (mut store, discord) = store(); + let account = AccountKey { network: Network::Signal, account: "me".into() }; + let signal = Key::new(&account, "mara"); + store.upsert_conversation(&account, &ConversationRow::new("mara", ConversationKind::Direct, "Mara")).unwrap(); + let stored = KEEP_MESSAGES + 100; + for n in 0..stored { + let sent = NOW - i64::from(stored - n); + store.ingest(&discord, &said(&n.to_string(), "line", sent), false).unwrap(); + store.ingest(&signal, &said(&n.to_string(), "line", sent), false).unwrap(); + } + + // Discord serves its messages again, so its oldest 100 went. Signal's all stay: no + // request brings one of them back. + assert_eq!(store.prune(NOW, KEEP_DAYS as u32).unwrap(), 100); + for n in 0..stored { + assert_eq!(store.message(&discord, &n.to_string()).unwrap().is_some(), n >= stored - KEEP_MESSAGES, "Discord message {n}"); + assert!(store.message(&signal, &n.to_string()).unwrap().is_some(), "Signal message {n} went"); + } + } + #[test] fn what_a_send_carried_is_kept_while_it_is_unsent() { let (mut store, key) = store(); From 5cf752075d72b32f20d56484009bbc569834194f Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 12:20:39 +0100 Subject: [PATCH 4/8] Say in the README and the docs that retention leaves Signal history whole --- README.md | 2 +- docs/architecture.md | 2 +- docs/design/09-settings.md | 2 +- docs/product/05-navigation.md | 2 +- docs/product/07-budgets-and-risk.md | 4 ++-- docs/product/09-settings.md | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4d527146..71373636 100644 --- a/README.md +++ b/README.md @@ -505,7 +505,7 @@ The data directory is `~/Library/Application Support/tinyclient` on macOS, `$XDG - **Calls** connect mediad to Discord's voice servers, Telegram's voice reflectors/SFU, or the Tiny server's own media port. Telegram 1:1 voice calls use MTProto 2.0 end-to-end encryption with 4 verification emoji; Telegram group voice chats join via WebRTC (DTLS-SRTP) and are not end-to-end encrypted. A Tiny server call is end-to-end encrypted only when that server offers `e2ee_calls` and every app in the call can do it. Otherwise the call says "Encrypted to the server". What that lock does and does not promise is in [SECURITY.md](SECURITY.md). When a Tiny call turns on screen share, camera, or watching a picture, and Cisco's OpenH264 library is not already on disk, mediad downloads it from Cisco. A voice-only call does not. - **Messages** texts go through the paired Android phone. The phone has to stay online. - **TLS** is the operating system's (Security.framework, SChannel, OpenSSL) for every network but Signal, whose libraries use rustls pinned to Signal's own certificate authority. -- **Retention.** By default, the newest 2,000 messages per conversation, and nothing older than 90 days unless you opened the conversation in that time. Settings can keep messages for 7, 30, or 90 days. Unsent messages stay. Signing out of an account asks the network to end the session where it can, takes that account out of the network's credential item, and deletes the item when it was the last account. It deletes that account's rows and its media files. The database is not vacuumed, so deleted text can remain in free pages of `chat.sqlite` until SQLite reuses them. +- **Retention.** By default, the newest 2,000 messages per conversation, and nothing older than 90 days unless you opened the conversation in that time. Settings can keep messages for 7, 30, or 90 days. Signal messages are the exception and are kept until you clear them, because Signal does not send them again. Unsent messages stay. Signing out of an account asks the network to end the session where it can, takes that account out of the network's credential item, and deletes the item when it was the last account. It deletes that account's rows and its media files. The database is not vacuumed, so deleted text can remain in free pages of `chat.sqlite` until SQLite reuses them. - **The local socket** is not authenticated. Any process running as your user can connect to it, as it can read your files. - **Signal** does not show safety numbers yet, and a contact's new identity key is trusted automatically, as presage's own stores do. diff --git a/docs/architecture.md b/docs/architecture.md index 846ea8fd..f0e050ca 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -260,7 +260,7 @@ changing again replaces its entry, so the list is bounded (256) by how many thin | Presence and activity, typing, voice occupants, what the shell watches, links and capabilities, the change list, the call, upload progress, previews asked, and five minutes of profiles, info panes and catalog pages (64 / 64 / 16 / 32 at most) | chatd memory, bounded, gone at restart. | | Files opened in another app under their own names | `open/` in the support directory: hard links into the cache, emptied when the shell starts. | | Panics, chatd's stderr | `crash.log` (cut at 256 KB), `chatd.log` (cut at 4 MB at start) in the support directory. | -| Retention | Newest 2,000 messages per conversation (`KEEP_MESSAGES`). Nothing older than the retention the user chose, 7, 30 or 90 days, default 90, unless the conversation was opened in that time. A thread row that names its parent goes when its parent goes, or when its root message has aged out and nobody opened the thread in that same window. `Store::prune`, at start and daily. | +| Retention | Newest 2,000 messages per conversation (`KEEP_MESSAGES`). Nothing older than the retention the user chose, 7, 30 or 90 days, default 90, unless the conversation was opened in that time. Neither rule touches Signal: no server serves its messages again. A thread row that names its parent goes when its parent goes, or when its root message has aged out and nobody opened the thread in that same window. `Store::prune`, at start and daily. | ## What an adapter must do diff --git a/docs/design/09-settings.md b/docs/design/09-settings.md index 62f90cdb..1a374de2 100644 --- a/docs/design/09-settings.md +++ b/docs/design/09-settings.md @@ -182,7 +182,7 @@ Caption: "Text size is also ⌘+, ⌘− and ⌘0. Reduce Motion and Increase Co | | "Keep messages on this Mac for" (P4) | Segmented: "7 days" / "30 days" / "90 days" | | | Calls | "Only join end-to-end encrypted calls" (PE) | Switch | Caption: "When a server turns a call's encryption off, the call stops until you choose to carry on unencrypted. With this on you can't: you leave instead, and a Tiny server that cannot encrypt calls is not joined. Always the case on Incognito servers and in rooms that require it. Takes effect the next time you join." | -Captions. Under the read group: "Discord and Slack have no read receipts." If no signed-in account has receipts, the group is just that caption under the label. Under P4: "Older messages are deleted here, never on the networks. Each conversation also keeps at most its newest 2,000." +Captions. Under the read group: "Discord and Slack have no read receipts." If no signed-in account has receipts, the group is just that caption under the label. Under P4: "Older messages are deleted here, never on the networks. Each conversation also keeps at most its newest 2,000. Signal messages are kept until you clear them: Signal does not send them again." **Shortening P4 asks first**, because it deletes. Modal (01, 440): "Delete messages older than 7 days?" / "41,210 messages, about 12 MB, are removed from this Mac. They stay on Slack, Discord and the others." / "Cancel" · danger "Delete". Unknown counts are dropped from the sentence, as in 08 §6. Lengthening applies without a question. diff --git a/docs/product/05-navigation.md b/docs/product/05-navigation.md index 0bb0a72f..b5b23c79 100644 --- a/docs/product/05-navigation.md +++ b/docs/product/05-navigation.md @@ -173,6 +173,6 @@ The Inbox is directs and group directs, starred channels, and channels that ment Discord subscribes to a large server when one of its channels is open, and drops that subscription on leaving. -Search retention is 2,000 messages and 90 days (`KEEP_MESSAGES`, `KEEP_DAYS`). Settings › Privacy can shorten the age. The cache is unencrypted. See `07-budgets-and-risk.md`. There is no FTS index. +Search retention is 2,000 messages and 90 days (`KEEP_MESSAGES`, `KEEP_DAYS`), except for Signal, which keeps everything. Settings › Privacy can shorten the age. The cache is unencrypted. See `07-budgets-and-risk.md`. There is no FTS index. N17 (preview and join an unjoined Slack channel) and N23 (join a public Telegram channel) were not confirmed. Keyboard shortcuts were not diffed one by one against `shortcuts.rs`. diff --git a/docs/product/07-budgets-and-risk.md b/docs/product/07-budgets-and-risk.md index 4f7d9bdd..0a2952e4 100644 --- a/docs/product/07-budgets-and-risk.md +++ b/docs/product/07-budgets-and-risk.md @@ -64,7 +64,7 @@ Per-item costs behind the heavy-account row (decoded pixels are 4 bytes each, at | Slack boot | Keep `client.counts` as the only listing call. Page channel lists on demand when the browser is opened. No `client.userBoot`, no `users.list`. | Boot payloads are MBs on large workspaces *(unverified size)*. | | Emoji | Unicode emoji come from the system font. Custom emoji are fetched when first drawn, at 48 px, into the avatar-style cache. The picker loads one server's set at a time. | A bundled emoji set is 10+ MB on disk and in memory. | | Search | Search on Enter asks the network (`SearchNetwork`). Local search is `SearchMessages` over the cache. There is no FTS index. | An FTS index would add roughly 30 to 50% to the message table. It is not in this commit. | -| SQLite growth | Keep the newest 2,000 messages per conversation and nothing older than 90 days unless the conversation was opened in that time (`KEEP_MESSAGES`, `KEEP_DAYS`). Settings › Privacy can shorten the age. Prune at start and daily. | At about 300 B a row, 1,000 conversations x 2,000 = 600 MB without the age rule; with it, under 200 MB. | +| SQLite growth | Keep the newest 2,000 messages per conversation and nothing older than 90 days unless the conversation was opened in that time (`KEEP_MESSAGES`, `KEEP_DAYS`). Signal keeps everything, because no request brings one of its messages back. Settings › Privacy can shorten the age. Prune at start and daily. | At about 300 B a row, 1,000 conversations x 2,000 = 600 MB without the age rule; with it, under 200 MB. A Signal account's store grows with the history its phone synced to it, outside this budget. | | grammers | Runs on the adapter's thread inside chatd, and only while a Telegram account exists or a sign-in has started. It does not keep a second database. If a later measurement blows the chatd budget, that is a new decision. It is not the current design. | The TDLib 30–50 MB row does not apply. The +0.2 MB / +1.2 MB figures are the comment in `telegram.rs`. | | Message window | The shell holds at most 300 messages; older ones page in 50 at a time from chatd and fall off the other end. | 5,000 shaped messages would otherwise cost tens of MB. | @@ -169,7 +169,7 @@ Rules: `TINYCLIENT_DIR` replaces it for tests. `chat.sqlite` and `media//` (avatars, thumbnails, custom emoji) live there, files named by content hash. Sessions stay in the keychain or the system keyring, one item per network. Slack workspaces and Tiny servers share that one item and are split by the adapter. Nothing goes to temp directories; logs hold no message bodies or tokens. -- Caps: media 500 MB (`CACHE_BYTES`), least recently used evicted; messages default to 2,000 per conversation and 90 days (`KEEP_MESSAGES`, `KEEP_DAYS`), unless the conversation was opened in that window. Settings › Privacy can shorten the age. Under 1 GB in total, checked with `du -sk`. +- Caps: media 500 MB (`CACHE_BYTES`), least recently used evicted; messages default to 2,000 per conversation and 90 days (`KEEP_MESSAGES`, `KEEP_DAYS`), unless the conversation was opened in that window. Signal's messages are not capped, since no server serves them again. Settings › Privacy can shorten the age. Under 1 GB in total without Signal history, checked with `du -sk`. - Full-size images and files are fetched when opened and saved only where the user chooses. - Sign-out deletes that network's rows, its `media/` directory and its session, then vacuums so the bytes leave the file. e2e check: no row and no file for that network remains. - The cache is unencrypted and relies on the disk's own encryption. The README already says so. diff --git a/docs/product/09-settings.md b/docs/product/09-settings.md index 06266e84..8be9a6c6 100644 --- a/docs/product/09-settings.md +++ b/docs/product/09-settings.md @@ -226,7 +226,7 @@ no control. | PL | Confirm before opening links | Switch | On | G | s | A click on a web link in a message shows the site it really goes to (registrable domain, with punycode decoded and the `xn--` form beside it for an internationalised name) and offers Open, Copy link and Cancel, plus "Don't ask again for ", kept on this device (`link_ok` lines in `shell.prefs`; "Forget all" is PF). Off: links open at once. A name that mixes alphabets or passes for Latin letters, or an address with a user name before the `@`, is always asked about, and never gets "Don't ask again". Only http and https are ever links | in | | PS | Strip tracking parameters when opening | Switch | Off | G | s | On: `utm_*`, `fbclid`, `gclid`, `mc_eid`, `igshid` and the like are taken out of the address as it opens; the rest of the address is untouched. The address is handed to the system's opener alone, so no page is the referrer | in | | PF | Sites that open without asking | Button "Forget all" | | G | s | Shown only when "Don't ask again" has been used. Clears the list | in | -| P4 | Keep messages on this computer for | Segmented: "7 days" / "30 days" / "90 days" | 90 days | G | d | The age half of the retention rule (`store.rs`); the 2,000 per conversation cap stays. Pruned within 1 min of the change and daily | in | +| P4 | Keep messages on this computer for | Segmented: "7 days" / "30 days" / "90 days" | 90 days | G | d | The age half of the retention rule (`store.rs`); the 2,000 per conversation cap stays. Neither touches Signal, which keeps its history whole. Pruned within 1 min of the change and daily | in | | PE | Only join end-to-end encrypted calls | Switch | Off | G | s | Off on purpose: a server or an app that cannot encrypt calls would stop working. Either way a Tiny call whose server turns encryption off stops sending and playing ("Encryption was turned off" on the call badge); off, the security panel offers "Carry on without encryption", on, it offers only leaving, and a server with no end-to-end calls is not joined. Incognito hosts (`incognito.tinyclient.io` and names under it) and `e2ee_required` rooms behave as on whatever the switch says. Read when a call is joined | in | | P5 | Hide tinyclient from screen sharing and recordings | Switch | | G | s | | Later (spike: macOS 15 capture may ignore `sharingType`) | | P6 | Lock tinyclient | Off, after 1 minute, after 5 minutes, after 1 hour, and when the screen locks | Off | G | s | Covers the window. A notification then says "New message" with no sender or text, and Reply is refused. A ring can still be answered. Unlock uses device approval; Linux keeps a passphrase hash in the window prefs. The cache is not encrypted. A phone hides the app switcher while the lock is on. | in | From 69b464156f57cf98e66d17d9d0936a4df55b0cc4 Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 02:06:06 +0100 Subject: [PATCH 5/8] Keep the settings a Signal phone shared over a chatd restart and ask for them again at every connect --- crates/chatd/src/adapters/signal.rs | 171 ++++++++-- crates/chatd/src/adapters/signal/fake.rs | 19 +- crates/chatd/src/adapters/signal/real.rs | 16 +- crates/chatd/tests/signal.rs | 53 +++ docs/product/09-settings.md | 4 + .../signal-settings-kept/drive.linux.sh | 9 + .../signal-settings-kept/drive.macos.sh | 9 + e2e/scenarios/signal-settings-kept/drive.py | 315 ++++++++++++++++++ .../signal-settings-kept/drive.windows.ps1 | 17 + .../signal-settings-kept/scenario.json | 12 + 10 files changed, 595 insertions(+), 30 deletions(-) create mode 100644 e2e/scenarios/signal-settings-kept/drive.linux.sh create mode 100644 e2e/scenarios/signal-settings-kept/drive.macos.sh create mode 100644 e2e/scenarios/signal-settings-kept/drive.py create mode 100644 e2e/scenarios/signal-settings-kept/drive.windows.ps1 create mode 100644 e2e/scenarios/signal-settings-kept/scenario.json diff --git a/crates/chatd/src/adapters/signal.rs b/crates/chatd/src/adapters/signal.rs index 02671b66..e512b152 100644 --- a/crates/chatd/src/adapters/signal.rs +++ b/crates/chatd/src/adapters/signal.rs @@ -32,8 +32,9 @@ //! # What the user did, and only that //! //! Read receipts go out when the shell says a message was read and the user's own Signal settings -//! send them; typing likewise. Both stay off until the phone has said what those settings are. -//! Nothing else is sent unasked: no reaction, edit, delete or profile change. +//! send them; typing likewise. Both stay off until the phone has said what those settings are, +//! and what it said is kept from one start to the next until it says otherwise. Nothing else is +//! sent unasked: no reaction, edit, delete or profile change. mod fake; mod files; @@ -92,6 +93,9 @@ const REACTIONS_KEPT: usize = 4_096; /// Largest reaction record file read on startup. `REACTIONS_KEPT` rows sit well below this; /// anything larger is skipped so an oversized or corrupt file is not parsed under the lock. const REACTIONS_FILE_LIMIT: u64 = 2 * 1024 * 1024; +/// Largest kept-settings file read at a start. The three switches sit far below this in JSON; +/// anything larger is not the file this adapter wrote, and is skipped. +const SETTINGS_FILE_LIMIT: u64 = 4 * 1024; /// Ballots remembered on one poll. Older ones drop off the list; the choice counts stay. const BALLOTS_KEPT: usize = 1_024; /// Signal's poll limits, from its desktop schema: a question and each choice are at most this @@ -772,9 +776,13 @@ struct Live { group_calls: HashMap, /// Pending incoming Signal group-call ring (`conversation_id`, `group_id`, `era_id`, `caller_aci`, `ring_id`). group_ring: Option, - /// The user's own Signal settings. Off until the phone says. + /// The user's own Signal settings, as the phone last shared them: off until it says, and + /// what it said is kept at `settings_path` for the next start. read_receipts: bool, typing: bool, + /// `{support}/signal/{aci}.settings`: what the phone last said of those settings. Empty when + /// nothing is kept on disk. + settings_path: PathBuf, /// File sends, by the time Signal gave them, so the phone's copy does not replace the file. echoed: VecDeque, /// Disappearing-messages timer per conversation id. @@ -946,6 +954,38 @@ struct ActiveGroupCall { } impl Live { + /// A new memory on what the adapter keeps for this account. The settings are the phone's + /// last word, so they hold from the first moment until the phone says otherwise. A start + /// with nothing kept, or a kept file that does not read, is off. + fn kept(aci: &str) -> Live { + let settings_path = settings_path(aci); + let said = read_settings(&settings_path).unwrap_or_default(); + Live { + reactions_path: reactions_path(aci), + pins_path: pins_path(aci), + stickers_path: stickers_path(aci), + attachments_path: transfer::attachments_path(aci), + settings_path, + read_receipts: said.read_receipts, + typing: said.typing, + link_previews: said.link_previews.unwrap_or(false), + ..Live::default() + } + } + + /// Takes what the phone said of the account's settings and keeps it for the next start. + /// The phone saying nothing of link previews leaves what is held, here and in the file. + fn note_settings(&mut self, said: &KeptSettings) { + self.read_receipts = said.read_receipts; + self.typing = said.typing; + if let Some(previews) = said.link_previews { + self.link_previews = previews; + } + // What is kept is what holds now, so a start from the file is as this moment is. + let held = KeptSettings { read_receipts: self.read_receipts, typing: self.typing, link_previews: Some(self.link_previews) }; + write_settings(&self.settings_path, &held); + } + fn name(&self, id: &str) -> String { if let Some(nick) = self.nicknames.get(id).filter(|s| !s.is_empty()) { return nick.clone(); @@ -1392,6 +1432,59 @@ fn write_reactions(path: &Path, order: &VecDeque<(String, String)>, book: &HashM } } +/// What the phone last said of the account's own settings, as `Event::Settings` carries them. +/// The file is this, in JSON, owned by this adapter and not by the message store. What it does +/// not say is off: unknown never sends a receipt. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +struct KeptSettings { + #[serde(default)] + read_receipts: bool, + #[serde(default)] + typing: bool, + /// None when the phone said nothing of it. + #[serde(default, skip_serializing_if = "Option::is_none")] + link_previews: Option, +} + +fn settings_path(aci: &str) -> PathBuf { + protocol::support_dir().join("signal").join(format!("{aci}.settings")) +} + +/// `None` when nothing is kept or what is there does not read. +fn read_settings(path: &Path) -> Option { + if path.as_os_str().is_empty() { + return None; + } + let Ok(meta) = std::fs::metadata(path) else { + return None; + }; + if meta.len() > SETTINGS_FILE_LIMIT { + return None; + } + let Ok(bytes) = std::fs::read(path) else { + return None; + }; + serde_json::from_slice::(&bytes).ok() +} + +fn write_settings(path: &Path, said: &KeptSettings) { + if path.as_os_str().is_empty() { + return; + } + if let Some(parent) = path.parent() { + if std::fs::create_dir_all(parent).is_err() { + return; + } + } + let Ok(bytes) = serde_json::to_vec(said) else { + return; + }; + let tmp = path.with_extension("settings.tmp"); + if std::fs::write(&tmp, &bytes).and_then(|()| std::fs::rename(&tmp, path)).is_err() { + let _ = std::fs::remove_file(&tmp); + } +} + /// The lab's signal-wave13 driver: proves mobile companion linking (#735) and linked-device /// message history transfer (#724) end-to-end against a scratch SQLite store. pub fn prove_signal_wave13() -> Result<(), String> { @@ -1527,15 +1620,10 @@ pub fn start(ctx: Context, session: &str, inbox: Receiver) -> Result<() if !supported() { return Err(unsupported_reason()); } - // What is learned (names, settings, unread) outlives one connection. Reactions outlive the - // process: the file is what a later reaction replaces, once this memory is gone. - let live = Arc::new(Mutex::new(Live { - reactions_path: reactions_path(&saved.aci), - pins_path: pins_path(&saved.aci), - stickers_path: stickers_path(&saved.aci), - attachments_path: transfer::attachments_path(&saved.aci), - ..Live::default() - })); + // What is learned (names, unread) outlives one connection. The kept files outlive the + // process: a later reaction replaces against the reaction record once this memory is gone, + // and the settings are the phone's last word until it says otherwise. + let live = Arc::new(Mutex::new(Live::kept(&saved.aci))); let current: Arc>>> = Arc::default(); let (socket_ctx, held, socket_saved, socket_live) = (ctx.clone(), current.clone(), saved.clone(), live.clone()); std::thread::Builder::new() @@ -2358,19 +2446,11 @@ fn apply(account: &Account, event: Event) { } } Event::Settings { read_receipts, typing, link_previews } => { - let updated_lp = { - let mut live = account.live(); - live.read_receipts = read_receipts; - live.typing = typing; - if let Some(lp) = link_previews { - live.link_previews = lp; - Some(lp) - } else { - None - } - }; - if let Some(lp) = updated_lp { - ctx.capabilities(capabilities(lp)); + // Kept as it is taken, so the next start has the phone's word before it answers again. + let said = KeptSettings { read_receipts, typing, link_previews }; + account.live().note_settings(&said); + if let Some(previews) = said.link_previews { + ctx.capabilities(capabilities(previews)); } } Event::TimerChanged { peer, seconds, version } => { @@ -7564,6 +7644,47 @@ mod tests { assert!(read_reactions(&path).is_empty()); } + #[test] + fn kept_settings_round_trip_and_nothing_unknown_reads_as_on() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("acct.settings"); + // Nothing kept, a file that is not the settings, one too large: none of them reads, so + // a start from them is off. + assert_eq!(read_settings(&path), None); + assert_eq!(read_settings(std::path::Path::new("")), None); + std::fs::write(&path, br#"{"read_receipts":"yes"}"#).unwrap(); + assert_eq!(read_settings(&path), None); + std::fs::write(&path, vec![b' '; (SETTINGS_FILE_LIMIT as usize) + 1]).unwrap(); + assert_eq!(read_settings(&path), None); + + // The phone's word is kept as it was said, and nothing else is in the file. + let said = KeptSettings { read_receipts: true, typing: false, link_previews: Some(false) }; + write_settings(&path, &said); + assert_eq!(std::fs::read_to_string(&path).unwrap(), r#"{"read_receipts":true,"typing":false,"link_previews":false}"#); + assert_eq!(read_settings(&path), Some(said)); + assert!(!path.with_extension("settings.tmp").exists(), "the temporary file was renamed away"); + + // A file that does not say every switch, or says one this build does not know, still + // reads; what it does not say is off. + std::fs::write(&path, br#"{"typing":true,"later":1}"#).unwrap(); + assert_eq!(read_settings(&path), Some(KeptSettings { read_receipts: false, typing: true, link_previews: None })); + + // Taking the phone's word keeps it. The phone saying nothing of link previews leaves + // what is held, here and in the file, so the next start holds it too. + let mut live = Live { settings_path: path.clone(), ..Live::default() }; + live.note_settings(&KeptSettings { read_receipts: true, typing: true, link_previews: Some(true) }); + assert!(live.read_receipts && live.typing && live.link_previews); + let off = KeptSettings { read_receipts: false, typing: true, link_previews: None }; + live.note_settings(&off); + assert!(!live.read_receipts && live.typing && live.link_previews); + assert_eq!(read_settings(&path), Some(KeptSettings { read_receipts: false, typing: true, link_previews: Some(true) })); + + // A memory with no file to keep to still takes the word, and writes nothing. + let mut nowhere = Live::default(); + nowhere.note_settings(&said); + assert!(nowhere.read_receipts && !nowhere.typing && !nowhere.link_previews); + } + #[test] fn a_username_shape_is_proven() { prove_signal_username().unwrap(); diff --git a/crates/chatd/src/adapters/signal/fake.rs b/crates/chatd/src/adapters/signal/fake.rs index 2723f502..5e2d66ae 100644 --- a/crates/chatd/src/adapters/signal/fake.rs +++ b/crates/chatd/src/adapters/signal/fake.rs @@ -43,6 +43,11 @@ //! WHO is `grace` or `alan`. Every request it is sent is appended to `signal.calls`, one line //! each, so a test can see what the network would have heard. //! +//! The phone answers a device that connects with its contacts, its groups and its settings. A +//! test keeps it from answering the settings with an empty `signal.phone-away` in the scratch +//! directory, as a phone that is off: they then come only from the lines above, and chatd has to +//! go by what it kept of the phone's last word (`adapters/signal.rs`). +//! //! The account: Ada Quill (us); Grace Ombra and Alan Ferro, both contacts; the group "Bridge //! club" with all three of us in it. @@ -94,6 +99,13 @@ fn record(line: &str) { } } +/// True when a test keeps the phone from answering at this connect (`signal.phone-away` in the +/// scratch directory). Only the settings wait for it: the contacts and the groups are read from +/// the device's own memory and from the storage service. +fn phone_away() -> bool { + protocol::support_dir().join("signal.phone-away").exists() +} + #[derive(Clone)] struct FakeGroup { info: GroupInfo, @@ -230,13 +242,16 @@ pub struct Fake { impl Fake { pub fn open(_saved: &Saved) -> Fake { let (events, heard) = channel(); - // What the phone says once a device connects: its contacts, its groups, its settings. + // What the phone says once a device connects: its contacts, its groups, its settings, + // unless the test has the phone away. let grace = Contact { id: GRACE.into(), name: "Grace Ombra".into(), phone: "+15550100002".into() }; let alan = Contact { id: ALAN.into(), name: "Alan Ferro".into(), phone: String::new() }; let _ = events.send(Event::Contacts(vec![grace, alan])); let club_state = FakeGroup::initial(); let _ = events.send(Event::Groups(vec![club_state.info.clone()])); - let _ = events.send(Event::Settings { read_receipts: true, typing: true, link_previews: Some(true) }); + if !phone_away() { + let _ = events.send(Event::Settings { read_receipts: true, typing: true, link_previews: Some(true) }); + } let manifest_path = protocol::support_dir().join("signal.storage.json"); if let Ok(raw) = std::fs::read_to_string(&manifest_path) { if let Ok(snapshot) = serde_json::from_str::(&raw) { diff --git a/crates/chatd/src/adapters/signal/real.rs b/crates/chatd/src/adapters/signal/real.rs index ee7375dc..15d435d7 100644 --- a/crates/chatd/src/adapters/signal/real.rs +++ b/crates/chatd/src/adapters/signal/real.rs @@ -1013,15 +1013,27 @@ impl Session { let _ = self.events.send(event); } - /// Once per link: ask the phone for the contacts and the settings it shares with devices. + /// At every connect: ask the phone for the settings it shares with devices. What was kept of + /// its last answer (`adapters/signal.rs`) holds until this one arrives, and a link whose + /// first answer never came is not left without. The contacts are asked for once per link: + /// the phone answers with the whole list. async fn first_run(&mut self) { self.emit_sticker_packs().await; if self.vault.flag("asked") { self.tell(Event::Contacts(self.contacts().await)); + self.ask_settings().await; self.sync_storage().await; return; } let _ = self.manager.request_contacts().await; + self.ask_settings().await; + self.vault.set_flag("asked"); + self.sync_storage().await; + } + + /// Asks the phone for the account's settings: read receipts, typing, link previews. Its + /// answer is a configuration sync, which becomes `Event::Settings`. + async fn ask_settings(&mut self) { let configuration = SyncMessage { request: Some(sync_message::Request { r#type: Some(sync_message::request::Type::Configuration.into()) }), ..SyncMessage::with_padding(&mut rand::rng()) @@ -1029,8 +1041,6 @@ impl Session { if let Ok(me) = Uuid::parse_str(&self.me) { let _ = self.manager.send_message(Aci::from(me), configuration, now_ms()).await; } - self.vault.set_flag("asked"); - self.sync_storage().await; } /// Derives the account's read-only Storage Service key from the stored master key or account entropy pool. diff --git a/crates/chatd/tests/signal.rs b/crates/chatd/tests/signal.rs index 00d0e765..a44263db 100644 --- a/crates/chatd/tests/signal.rs +++ b/crates/chatd/tests/signal.rs @@ -681,6 +681,59 @@ fn typing_and_receipts_have_a_local_switch_that_stops_the_frames_here() { world.heard(&format!("typing {ALAN} started")); } +#[test] +fn the_settings_the_phone_shared_are_kept_over_a_restart() { + let mut world = World::linked(); + world.connected(); + for (at, text) in [(1, "one"), (2, "two")] { + world.steer(&format!("incoming grace {} {text}", T0 + at * 1_000)); + } + // The settings were said before either message, so they are taken before the second is stored. + world.arrived(GRACE, &id(T0 + 2_000, GRACE)); + // The phone is away at the next start and says nothing of the settings. What it said before + // is all there is, and it said on. + std::fs::write(world.dir.join("signal.phone-away"), b"").unwrap(); + world.restart(); + world.connected(); + assert_eq!(world.ask(Request::MarkRead { conversation: key(GRACE), message_id: id(T0 + 1_000, GRACE) }), Response::Ok); + world.heard(&format!("read receipts=true {}", id(T0 + 1_000, GRACE))); + world.ask(Request::Typing { conversation: key(GRACE), activity: protocol::Compose::Typing }); + world.heard(&format!("typing {GRACE} started")); + world.send(GRACE, "7381", "Tuesday, then", None); + // Read back, as the shell does: the answer to the send does not carry the note. + let ours = world.until("our message", || world.messages(GRACE).into_iter().find(|message| message.client_id.as_deref() == Some("7381") && message.id != "7381")); + assert_eq!(ours.receipt_note, ""); + // The phone is back with another word. It wins, and it is what is kept from now on. + world.steer("receipts off"); + let kept = || std::fs::read_to_string(world.dir.join("signal").join(format!("{ME}.settings"))).unwrap_or_default(); + world.until("the phone's last word kept", || kept().contains(r#""read_receipts":false"#).then_some(())); + assert_eq!(world.ask(Request::MarkRead { conversation: key(GRACE), message_id: id(T0 + 2_000, GRACE) }), Response::Ok); + world.heard(&format!("read receipts=false {}", id(T0 + 2_000, GRACE))); +} + +#[test] +fn a_phone_that_turned_the_receipts_off_is_still_off_after_a_restart() { + let mut world = World::linked(); + world.connected(); + for (at, text) in [(1, "one"), (2, "two")] { + world.steer(&format!("incoming grace {} {text}", T0 + at * 1_000)); + } + world.arrived(GRACE, &id(T0 + 2_000, GRACE)); + world.steer("receipts off"); + let kept = || std::fs::read_to_string(world.dir.join("signal").join(format!("{ME}.settings"))).unwrap_or_default(); + world.until("the phone's word kept", || kept().contains(r#""read_receipts":false"#).then_some(())); + // The phone is away at the next start. What it last said was off, and off it stays: the + // failure to avoid is a receipt the account did not agree to. + std::fs::write(world.dir.join("signal.phone-away"), b"").unwrap(); + world.restart(); + world.connected(); + assert_eq!(world.ask(Request::MarkRead { conversation: key(GRACE), message_id: id(T0 + 2_000, GRACE) }), Response::Ok); + world.heard(&format!("read receipts=false {}", id(T0 + 2_000, GRACE))); + world.send(GRACE, "7382", "Quiet", None); + let ours = world.until("our message", || world.messages(GRACE).into_iter().find(|message| message.client_id.as_deref() == Some("7382") && message.id != "7382")); + assert_eq!(ours.receipt_note, "Read receipts are off"); +} + #[test] fn an_unlinked_device_expires_keeps_what_was_read_and_signing_out_unlinks() { let world = World::linked(); diff --git a/docs/product/09-settings.md b/docs/product/09-settings.md index 06266e84..7c98834f 100644 --- a/docs/product/09-settings.md +++ b/docs/product/09-settings.md @@ -409,6 +409,10 @@ the control is not shown on that platform. choices, a Teams admin's policy) is honoured live from the network's events and shown as a fixed row or caption, never stored as a tinyclient value. Signal's P1 and P2 switches are a local stop on top of that, stricter than the account, never the account's value itself. +- Signal's receipt and typing choices are honoured from the phone's last word, and the Signal + adapter keeps that word in its own file (`signal/.settings`) so a restart does not + turn them off until the phone answers again, which it is asked to at every connect (#738). It + stays the network's value, never a tinyclient one. - No setting is written to a network, except the mute that already exists (N12) and is the network's own. - No import from the official apps, browsers or other Macs. No export, no sync, no backup. diff --git a/e2e/scenarios/signal-settings-kept/drive.linux.sh b/e2e/scenarios/signal-settings-kept/drive.linux.sh new file mode 100644 index 00000000..e4696483 --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-settings-kept on Linux. The lab runs this with bash while ffmpeg films the display. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/signal-settings-kept/drive.macos.sh b/e2e/scenarios/signal-settings-kept/drive.macos.sh new file mode 100644 index 00000000..89d6d91d --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-settings-kept on macOS. The lab runs this with bash while the display is filmed. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/signal-settings-kept/drive.py b/e2e/scenarios/signal-settings-kept/drive.py new file mode 100644 index 00000000..d60b26ff --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +"""The read receipts and typing a Signal phone shared are kept over a chatd restart. + +Starts this build's chatd with the scripted Signal wire (TINYCLIENT_SIGNAL_FAKE), steers it +over its control file the way tests/signal.rs does, and speaks chatd's real socket. The phone +shares its settings at the first connect (read receipts on, typing on), then is away for one +restart (an empty signal.phone-away), so it says nothing at the next connect. A read now asks +the wire for "read receipts=true", a typing signal goes out, and a message sent here does not +say "Read receipts are off". The phone's word is kept under signal/.settings, and when +the phone answers later with receipts off, no receipt goes out. A build from before the fix +forgets the settings with its memory: the read goes out as "receipts=false", no typing signal +is sent, the message says the receipts are off and nothing is kept, so this driver fails there. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR. +""" + +import json +import os +import socket +import struct +import subprocess +import sys +import time + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") + +ME = "a1a1a1a1-0000-4000-8000-000000000001" +GRACE = "b2b2b2b2-0000-4000-8000-000000000002" +GROUP = "g.5a175a175a175a175a175a175a175a175a175a175a175a175a175a175a175a17" +SESSION = json.dumps({"aci": ME, "name": "Ada Quill", "vault": "00"}) +T0MS = 1_791_892_800_000 +FIRST = 1_000 +SECOND = 2_000 + +FAILED = False +STEPS = "" + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false") + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def app_bin(app_dir): + name = "chatd.exe" if sys.platform == "win32" else "chatd" + if sys.platform == "darwin" and app_dir.endswith(".app"): + return os.path.join(app_dir, "Contents", "MacOS", "chatd") + return os.path.join(app_dir, name) + + +def connect(sock_path): + """chatd's socket: a file on Unix, the matching named pipe on Windows.""" + if sys.platform == "win32": + return open("\\\\.\\pipe\\" + sock_path, "r+b", buffering=0) + stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stream.settimeout(5) + stream.connect(sock_path) + return stream + + +def write_all(stream, data): + view = memoryview(data) + while view: + written = stream.write(view) + if not written: + raise RuntimeError("chatd's socket took nothing") + view = view[written:] + + +class Chat: + def __init__(self, sock_path): + self.stream = connect(sock_path) + + def ask(self, request): + body = json.dumps(request, separators=(",", ":")).encode() + write_all(self.stream, struct.pack("!I", len(body)) + body) + head = b"" + while len(head) < 4: + got = self.stream.read(4 - len(head)) + if not got: + raise RuntimeError("chatd closed its socket") + head += got + length = struct.unpack("!I", head)[0] + if length > 1024 * 1024: + raise RuntimeError("answer exceeds the protocol size limit") + chunks = b"" + while len(chunks) < length: + got = self.stream.read(length - len(chunks)) + if not got: + raise RuntimeError("chatd closed its socket mid-frame") + chunks += got + return json.loads(chunks) + + def close(self): + try: + self.stream.close() + except OSError: + pass + + +def key(id): + return {"network": "signal", "account": ME, "id": id} + + +def wait(what, chat, look, seconds=20): + deadline = time.time() + seconds + while time.time() < deadline: + found = look() + if found is not None: + step(what, True) + return found + time.sleep(0.2) + step(what, False) + return None + + +def steer(control, line): + with open(control, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def ask(chat, request): + try: + return chat.ask(request) + except Exception: + return None + + +def conversation(chat, id): + answer = ask(chat, {"op": "conversation", "conversation": key(id)}) + return (answer or {}).get("conversation") + + +def stored(chat): + """What the conversation with Grace holds, as chatd pages it to the shell.""" + answer = ask(chat, {"op": "messages", "conversation": key(GRACE), "page": "newest", "limit": 100}) + return (answer or {}).get("messages", []) + + +def lines(path): + """A file the scripted wire appends to, as it stands. Empty until there is one.""" + try: + with open(path, encoding="utf-8") as handle: + return handle.read().splitlines() + except OSError: + return [] + + +def json_file(path): + """A JSON file's content, or None until it is there and reads.""" + try: + with open(path, encoding="utf-8") as handle: + return json.load(handle) + except (OSError, ValueError): + return None + + +def launch(binary, kwargs, stem, sock_path): + """chatd on the scratch directory, once its socket answers: (process, Chat, its logs).""" + out = open(os.path.join(OUT, stem + ".out.log"), "w", encoding="utf-8") + err = open(os.path.join(OUT, stem + ".err.log"), "w", encoding="utf-8") + proc = subprocess.Popen([binary], stdout=out, stderr=err, **kwargs) + chat = None + deadline = time.time() + 15 + while chat is None: + if proc.poll() is not None: + step("chatd stays up for the driver", False) + break + if time.time() > deadline: + step("chatd opens its socket", False) + break + try: + chat = Chat(sock_path) + except OSError: + time.sleep(0.1) + return proc, chat, (out, err) + + +def stop(proc, chat, logs, sock_path): + """chatd off, and gone before anything starts again on its directory.""" + if chat: + chat.close() + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + for log in logs: + log.close() + if sys.platform != "win32" and os.path.exists(sock_path): + os.remove(sock_path) + + +def connected(chat, words): + return wait(words, chat, lambda: link_is(chat, "connected") or None) is not None + + +def link_is(chat, state): + """True when a Signal account's link is `state` right now.""" + return any(account["link"] == state for account in (ask(chat, {"op": "status"}) or {}).get("accounts", [])) + + +def unread(chat, count): + """None until Grace's row counts `count` unread messages.""" + row = conversation(chat, GRACE) or {} + return row.get("unread") == count or None + + +def before_restart(chat, control, data): + wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"})) + if not connected(chat, "Signal is connected"): + return + wait("the fake's group is known", chat, lambda: conversation(chat, GROUP)) + + # Grace writes. The settings came with the connect, before her message did. + steer(control, "incoming grace %d Still on for Tuesday?" % (T0MS + FIRST)) + wait("Grace's message is stored, unread", chat, lambda: unread(chat, 1)) + + +def after_restart(chat, control, data): + calls = os.path.join(data, "signal.calls") + kept = os.path.join(data, "signal", ME + ".settings") + connected(chat, "Signal is connected again, with the phone away") + + # The phone said nothing at this connect, so the read goes out as it last said: with a receipt. + first = "%d-%s" % (T0MS + FIRST, GRACE) + step("marking Grace's message read is taken", ask(chat, {"op": "mark_read", "conversation": key(GRACE), "message_id": first}) == {"op": "ok"}) + heard = wait("chatd tells Signal the message is read", chat, lambda: next((c for c in lines(calls) if c.startswith("read receipts=") and c.endswith(" " + first)), None)) + step("the read carries a receipt, as the phone last said (%s)" % heard, heard == "read receipts=true " + first) + + ask(chat, {"op": "typing", "conversation": key(GRACE)}) + wait("a typing signal goes out", chat, lambda: next((c for c in lines(calls) if c == "typing %s started" % GRACE), None)) + + ask(chat, {"op": "send", "conversation": key(GRACE), "client_id": "kept-1", "text": "Tuesday, then"}) + # Read back, as the shell does: the answer to the send does not carry the note. + ours = wait("the message sent now is in the conversation", chat, lambda: next((m for m in stored(chat) if m.get("client_id") == "kept-1" and m.get("id") != "kept-1"), None)) + note = (ours or {}).get("receipt_note") + step("a message sent now does not say the receipts are off (it says: %r)" % note, ours is not None and not note) + + said = wait("the phone's last word is kept", chat, lambda: json_file(kept), seconds=5) + step("what is kept says receipts and typing are on (%s)" % said, bool(said) and said.get("read_receipts") is True and said.get("typing") is True) + + # The phone is back and turned the receipts off: its word wins, and none goes out. + steer(control, "incoming grace %d Bring the score sheet" % (T0MS + SECOND)) + wait("Grace's second message is stored, unread", chat, lambda: unread(chat, 1)) + steer(control, "receipts off") + wait("the phone's later word is kept", chat, lambda: (json_file(kept) or {}).get("read_receipts") is False or None, seconds=5) + second = "%d-%s" % (T0MS + SECOND, GRACE) + step("marking the second message read is taken", ask(chat, {"op": "mark_read", "conversation": key(GRACE), "message_id": second}) == {"op": "ok"}) + wait("the phone's later word is honoured: the read goes out with no receipt", chat, lambda: next((c for c in lines(calls) if c == "read receipts=false " + second), None)) + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + binary = app_bin(APP) + if not os.path.isfile(binary): + step("chatd is in E2E_APP_DIR", False) + return 1 + + data = os.path.join(OUT, "data") + os.makedirs(data, exist_ok=True) + sock_path = os.path.join(data, "chat.sock") + control = os.path.join(data, "signal.ctl") + open(control, "a", encoding="utf-8").close() + env = os.environ.copy() + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_SIGNAL_FAKE"] = "1" + env["TINYCLIENT_SESSION_SIGNAL"] = SESSION + env.pop("TINYCLIENT_SESSION_DISCORD", None) + env.pop("TINYCLIENT_SESSION_SLACK", None) + env.pop("TINYCLIENT_SESSION_TELEGRAM", None) + env.pop("TINYCLIENT_SESSION_TEAMS", None) + kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + + def run(stem, part): + """chatd on the scratch directory for one part of the drive. False when a step failed.""" + proc, chat, logs = launch(binary, kwargs, stem, sock_path) + try: + if chat is not None: + part(chat, control, data) + return not FAILED + finally: + stop(proc, chat, logs, sock_path) + + if not run("chatd", before_restart): + return 1 + # The phone is off for the next connect: it says nothing of the settings, and what chatd + # kept of its last word is all there is. + open(os.path.join(data, "signal.phone-away"), "a", encoding="utf-8").close() + run("chatd-again", after_restart) + return 1 if FAILED else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/signal-settings-kept/drive.windows.ps1 b/e2e/scenarios/signal-settings-kept/drive.windows.ps1 new file mode 100644 index 00000000..f7c40b3b --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.windows.ps1 @@ -0,0 +1,17 @@ +# signal-settings-kept on Windows. The lab runs this in the console session it is already filming. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/signal-settings-kept/scenario.json b/e2e/scenarios/signal-settings-kept/scenario.json new file mode 100644 index 00000000..3b761cf7 --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "signal-settings-kept", + "title": "The read receipts and typing a Signal phone shared are kept over a chatd restart, until the phone says otherwise", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The phone proof build does not run desktop chatd. The kept settings are desktop chatd's Signal adapter and its file.", + "ios": "The phone proof build does not run desktop chatd. The kept settings are desktop chatd's Signal adapter and its file." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +} From a1a3a96c722e9e10bf6017a3aaa1d93a4e65c575 Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 14:35:28 +0100 Subject: [PATCH 6/8] Stopping a Telegram download ends it at the piece on its way and leaves no part file behind --- crates/chatd/src/adapters/mod.rs | 5 + crates/chatd/src/adapters/telegram.rs | 7 + crates/chatd/src/adapters/telegram/fake.rs | 14 +- crates/chatd/src/adapters/telegram/files.rs | 116 +++++++- crates/chatd/src/demo/adapter.rs | 1 + crates/chatd/src/server.rs | 9 + crates/chatd/tests/telegram.rs | 68 +++++ crates/protocol/src/lib.rs | 9 + crates/tinyclient/src/client.rs | 2 + docs/architecture.md | 1 + .../telegram-cancel-download/drive.linux.sh | 9 + .../telegram-cancel-download/drive.macos.sh | 9 + .../telegram-cancel-download/drive.py | 281 ++++++++++++++++++ .../drive.windows.ps1 | 17 ++ .../telegram-cancel-download/scenario.json | 12 + 15 files changed, 548 insertions(+), 12 deletions(-) create mode 100644 e2e/scenarios/telegram-cancel-download/drive.linux.sh create mode 100644 e2e/scenarios/telegram-cancel-download/drive.macos.sh create mode 100644 e2e/scenarios/telegram-cancel-download/drive.py create mode 100644 e2e/scenarios/telegram-cancel-download/drive.windows.ps1 create mode 100644 e2e/scenarios/telegram-cancel-download/scenario.json diff --git a/crates/chatd/src/adapters/mod.rs b/crates/chatd/src/adapters/mod.rs index 0d1a01bc..7481229c 100644 --- a/crates/chatd/src/adapters/mod.rs +++ b/crates/chatd/src/adapters/mod.rs @@ -1914,6 +1914,11 @@ pub enum Command { ids: Vec, span: (u64, u64), }, + /// The user stopped the download of this file (`Request::CancelDownload`). An adapter that + /// fetches files over its own session stops at the piece on its way and keeps nothing of + /// the file on disk; a file already on disk stays, and nothing is announced. The player's + /// byte windows are not downloads. Others ignore it. + CancelDownload { id: String }, /// The link that opens this conversation's call in the official app. Handoff { conversation_id: String, reply: Reply }, /// A stage hand, an accepted invite, or a moderator moving someone. diff --git a/crates/chatd/src/adapters/telegram.rs b/crates/chatd/src/adapters/telegram.rs index 49bac929..525ca980 100644 --- a/crates/chatd/src/adapters/telegram.rs +++ b/crates/chatd/src/adapters/telegram.rs @@ -804,6 +804,13 @@ pub fn start(ctx: Context, session: &str, inbox: Receiver) -> Result<() .spawn(move || deliver_cancel(&account, &conversation_id)); } } + // Off `telegram-commands`, like a send's cancel: a history fetch held there + // must not hold the stop too. + Command::CancelDownload { id } => { + if let Some(account) = account() { + account.files.cancel(&id); + } + } Command::Previews(ids) => { let _ = preview_tx.send(ids); } diff --git a/crates/chatd/src/adapters/telegram/fake.rs b/crates/chatd/src/adapters/telegram/fake.rs index 543e6545..f07e6905 100644 --- a/crates/chatd/src/adapters/telegram/fake.rs +++ b/crates/chatd/src/adapters/telegram/fake.rs @@ -2256,8 +2256,9 @@ pub struct Fake { /// `TINYCLIENT_TELEGRAM_PEER_HOLD`), until a line steers it through. hold_pages: bool, hold_peer_dialogs: bool, - /// And the row's size of `photo-preview`'s photo (`TINYCLIENT_TELEGRAM_FILE_HOLD`), until - /// `file-go`: what a slow download looks like while the stripped preview is on screen. + /// And some files (`TINYCLIENT_TELEGRAM_FILE_HOLD`, [`held_file`]) until `file-go`: the + /// row's size of `photo-preview`'s photo, which is what a slow download looks like while + /// the stripped preview is on screen, and the document `big-file` posts, which is one to stop. hold_files: bool, /// Wakes an answer held at the wire when the test steers. wake: Arc, @@ -2329,10 +2330,17 @@ impl Fake { // asked again until the `peer-go`. (self.hold_pages && asked::(body).is_some_and(|request| !matches!(request.offset_peer, tl::enums::InputPeer::Empty)) && !world.dialogs_go) || (self.hold_peer_dialogs && asked::(body).is_some() && !world.peer_go) - || (self.hold_files && asked::(body).is_some_and(|request| is_ridge_thumb(&request.location)) && !world.file_go) + || (self.hold_files && asked::(body).is_some_and(|request| held_file(&request.location)) && !world.file_go) } } +/// The files `TINYCLIENT_TELEGRAM_FILE_HOLD` holds at the wire until `file-go`: the row's size +/// of `photo-preview`'s photo, and the document `big-file` posts. +fn held_file(location: &tl::enums::InputFileLocation) -> bool { + is_ridge_thumb(location) + || matches!(location, tl::enums::InputFileLocation::InputDocumentFileLocation(document) if document.id == 9_400) +} + /// The row's size of `photo-preview`'s photo. fn is_ridge_thumb(location: &tl::enums::InputFileLocation) -> bool { matches!(location, tl::enums::InputFileLocation::InputPhotoFileLocation(photo) if photo.id == RIDGE && photo.thumb_size == "m") diff --git a/crates/chatd/src/adapters/telegram/files.rs b/crates/chatd/src/adapters/telegram/files.rs index 997be20b..c3723a7e 100644 --- a/crates/chatd/src/adapters/telegram/files.rs +++ b/crates/chatd/src/adapters/telegram/files.rs @@ -12,8 +12,10 @@ //! at its front. So a channel opened after another does not wait behind the first one's //! pictures, nor behind its own that are not on screen yet. A picture the shell asks for before //! a page has named it here goes ahead once a page does. A picker's tiles keep their turn: a -//! picker asks for a whole tab at once. The file being fetched is never cut short, and the -//! line never holds more than [`WAITING`]: past it, the last a page named is let go first. +//! picker asks for a whole tab at once. The file being fetched is never cut short for another, +//! and the line never holds more than [`WAITING`]: past it, the last a page named is let go +//! first. What the user stopped ([`Files::cancel`]) is the one exception: the piece of it on +//! its way is the last. //! // CONTRACT: an adapter has no way to hand the media cache a file. This does what the cache does // when one lands (`Store::register_media`, `Store::media_landed`, `Change::Media`) and nothing @@ -93,6 +95,8 @@ enum Job { Seen(Box, Instant), /// What is on screen changed: rows that came back put their pictures back in line. Look, + /// The user stopped the download of this file ([`Files::cancel`]). + Cancel(String), } pub struct Files { @@ -100,6 +104,9 @@ pub struct Files { jobs: Sender, waiting: Arc, held: Mutex, + /// The files whose download the user stopped, until the fetching thread looked at it: the + /// file being fetched ends at its next piece, and one waiting its turn is let go. + stops: Arc>>, } /// What the shell may ask for by id, and what it asked for before it was known here. @@ -312,6 +319,16 @@ impl Line { } gone } + + /// The user stopped the download: out of the line, wherever it waited its turn. The + /// player's byte windows are not downloads and stay. Answers how many places it had. + fn forget(&mut self, id: &str) -> usize { + let before = self.len(); + self.first.retain(|held| held.file.id != id); + self.seen.retain(|(_, held)| held.file.id != id); + self.rest.retain(|held| held.file.id != id); + before - self.len() + } } impl Files { @@ -319,8 +336,9 @@ impl Files { pub fn start(ctx: &Context) -> Files { let (jobs, inbox) = channel::(); let waiting = Arc::new(AtomicUsize::new(0)); + let stops = Arc::new(Mutex::new(HashSet::new())); let keeper = ctx.clone(); - let (ctx, counted) = (ctx.clone(), waiting.clone()); + let (ctx, counted, halts) = (ctx.clone(), waiting.clone(), stops.clone()); let spawned = std::thread::Builder::new().name("telegram-files".into()).spawn(move || { let mut account = Weak::new(); // Datacenters this connection's sign-in has been carried to. @@ -383,6 +401,16 @@ impl Files { } } Job::Look => rows_back(&account, &mut parked, &mut line.rest, &counted), + Job::Cancel(id) => { + // Nothing is fetched while a job is handled, so this stop was for + // what waits its turn: that lets go of its place, and the stop is + // spent. + let in_line = line.forget(&id); + let before = parked.len(); + parked.retain(|(_, held)| held.file.id != id); + counted.fetch_sub(in_line + before - parked.len(), Ordering::Relaxed); + crate::hub::lock(&halts).remove(&id); + } } // What the shell asks for is never refused at the door, so the line keeps // its own limit, parked pictures counted. @@ -425,7 +453,15 @@ impl Files { continue; } counted.fetch_sub(1, Ordering::Relaxed); - if let Err(fault) = fetch(&account, &want, &mut carried) { + let outcome = fetch(&account, &want, &mut carried); + // A stop that came as the last piece landed stopped nothing: it is not + // kept for the next ask. + crate::hub::lock(&halts).remove(&want.file.id); + if let Err(fault) = outcome { + // The user stopped it: nothing went wrong, and nothing is kept. + if fault == cancelled() { + continue; + } // A reference that ran out is renewed by the next page that names the file. if !fault.is("FILE_REFERENCE_EXPIRED") { tracing::warn!("chatd: Telegram: file {}: {fault}", want.file.id); @@ -445,7 +481,7 @@ impl Files { if let Err(err) = spawned { tracing::warn!("chatd: Telegram: files: {err}"); } - Files { ctx: keeper, jobs, waiting, held: Mutex::default() } + Files { ctx: keeper, jobs, waiting, held: Mutex::default(), stops } } pub fn attach(&self, account: &Arc) { @@ -478,7 +514,7 @@ impl Files { let (inline, wants): (Vec, Vec) = wants.into_iter().partition(|want| want.inline.is_some() && !want.original); for want in inline { let bytes = want.inline.as_deref().unwrap_or_default(); - if let Err(fault) = keep(&self.ctx, &want, |out, _| write_inline(out, bytes)) { + if let Err(fault) = keep(&self.ctx, &want, &|| false, |out, _| write_inline(out, bytes)) { tracing::warn!("chatd: Telegram: file {}: {fault}", want.file.id); } } @@ -513,6 +549,22 @@ impl Files { count } + /// The user stopped the download of this file. One waiting its turn lets go of its place at + /// once, and so does an ask no page has answered yet; the piece being fetched now is the + /// last, and nothing is kept of the file on disk. A file already on disk stays, and asking + /// for the file again fetches it from the start. + pub fn cancel(&self, id: &str) { + crate::hub::lock(&self.held).early.remove(id); + crate::hub::lock(&self.stops).insert(id.to_owned()); + let _ = self.jobs.send(Job::Cancel(id.to_owned())); + } + + /// Whether the user stopped the download of this file and the fetching thread did not look + /// at it yet. + fn stopped(&self, id: &str) -> bool { + crate::hub::lock(&self.stops).contains(id) + } + /// Sends what the shell asked for: never refused here, however many wait. The fetching /// thread keeps the line to [`WAITING`] by letting go of what matters least (`Line::trim`). fn ahead(&self, jobs: Vec) { @@ -856,7 +908,8 @@ fn fetch_span( /// One file, from Telegram to the cache's directory. fn fetch(account: &Account, want: &Want, carried: &mut HashSet) -> Result<(), Fault> { - let written = keep(&account.ctx, want, |out, start| match &want.inline { + let stopped = || account.files.stopped(&want.file.id); + let written = keep(&account.ctx, want, &stopped, |out, start| match &want.inline { Some(bytes) => write_inline(out, bytes), None => download(account, want, carried, start, out), })?; @@ -876,8 +929,9 @@ fn write_inline(out: &mut std::fs::File, bytes: &[u8]) -> Result { } /// One file into the cache's directory, written by `write`, and recorded as the cache records -/// a file that landed. `false` when it was on disk already and nothing was written. -fn keep(ctx: &Context, want: &Want, write: impl FnOnce(&mut std::fs::File, u64) -> Result) -> Result { +/// a file that landed. `false` when it was on disk already and nothing was written. While +/// `stopped` says so the user stopped the download: nothing is kept of it then. +fn keep(ctx: &Context, want: &Want, stopped: &dyn Fn() -> bool, write: impl FnOnce(&mut std::fs::File, u64) -> Result) -> Result { let id = std::slice::from_ref(&want.file.id); let on_disk = |ctx: &Context| { let known = ctx.hub.store().media(&ctx.account, id).unwrap_or_default(); @@ -915,6 +969,11 @@ fn keep(ctx: &Context, want: &Want, write: impl FnOnce(&mut std::fs::File, u64) }; let written = write(&mut out, start); drop(out); + // The user stopped the download, however its last piece ended: nothing is kept of it. + if want.inline.is_none() && stopped() { + let _ = std::fs::remove_file(&part); + return Err(cancelled()); + } let bytes = match written { Ok(bytes) => bytes, Err(fault) => { @@ -1006,6 +1065,11 @@ fn mismatched() -> Fault { Fault::Net("Telegram's copy of this file did not match.".to_owned()) } +/// The user stopped this download (`Command::CancelDownload`): nothing went wrong with it. +fn cancelled() -> Fault { + Fault::Net("stopped by the user".to_owned()) +} + type AesCtr = Ctr128BE; /// The counter Telegram's CDN uses: the redirect's IV plus `offset / 16`, big-endian. @@ -1070,6 +1134,10 @@ fn download(account: &Account, want: &Want, carried: &mut HashSet, start: u if account.ctx.pause(PACE) { return Err(Fault::Net("stopped".to_owned())); } + // The user stopped it meanwhile: no piece is asked for after that. + if account.files.stopped(&want.file.id) { + return Err(cancelled()); + } let request = tl::functions::upload::GetFile { precise: false, // A CDN redirect names a data centre the library cannot reach or key, so the file @@ -1084,6 +1152,10 @@ fn download(account: &Account, want: &Want, carried: &mut HashSet, start: u // A flood wait is honored in full here as everywhere. Err(fault) => match fault.flood() { Some(seconds) if seconds <= wire::PATIENCE && !pause(std::time::Duration::from_secs(seconds)) => { + // The wait may have been long, and the user may have stopped it meanwhile. + if account.files.stopped(&want.file.id) { + return Err(cancelled()); + } wire::call_in(wire, dc, &request)? } _ => return Err(fault), @@ -1163,6 +1235,10 @@ fn download_cdn( if account.ctx.pause(PACE) { return Err(Fault::Net("stopped".to_owned())); } + // The user stopped it meanwhile: no piece is asked for after that. + if account.files.stopped(&want.file.id) { + return Err(cancelled()); + } let request = tl::functions::upload::GetCdnFile { file_token: redirect.file_token.clone(), offset: offset as i64, @@ -1390,6 +1466,27 @@ mod tests { assert_eq!(order(line), ["original"]); } + #[test] + fn a_stopped_download_leaves_the_line_wherever_it_waits_but_not_the_players_windows() { + let mut line = Line::default(); + let at = Instant::now(); + assert!(!line.first(file("original", MediaKind::File, true, 1))); + assert!(!line.seen(thumb("a1"), at)); + assert!(!line.fetch(thumb("a2"))); + // The player's window of a file that also waits whole is not a download. + assert!(!line.span(file("video", MediaKind::Video, false, 1), (0, 1))); + assert!(!line.first(file("video", MediaKind::Video, true, 1))); + assert_eq!(line.forget("original"), 1, "the viewer's original"); + assert_eq!(line.forget("a1"), 1, "a picture on screen"); + assert_eq!(line.forget("a2"), 1, "a picture a page named"); + assert_eq!(line.forget("original"), 0, "it is gone already"); + assert_eq!(line.forget("nowhere"), 0, "nothing waits under that name"); + assert_eq!(line.forget("video"), 1, "the whole file goes, its window does not"); + assert_eq!(line.len(), 1); + assert!(line.pop_work().is_some_and(|work| matches!(work, NextWork::Span(_, (0, 1))))); + assert!(line.is_empty()); + } + #[test] fn what_is_remembered_keeps_the_latest_half_and_a_name_read_again_stays() { let mut recent = Recent::new(2); @@ -1422,6 +1519,7 @@ mod tests { Job::Seen(want, _) => ("seen", want.file.id), Job::Attach(_) => ("attach", String::new()), Job::Look => ("look", String::new()), + Job::Cancel(id) => ("cancel", id), }).collect() } diff --git a/crates/chatd/src/demo/adapter.rs b/crates/chatd/src/demo/adapter.rs index e9fd7828..4cf8f32e 100644 --- a/crates/chatd/src/demo/adapter.rs +++ b/crates/chatd/src/demo/adapter.rs @@ -1515,6 +1515,7 @@ impl Demo { | Command::Watch(_) | Command::Wanted(_) | Command::WantedSpan { .. } + | Command::CancelDownload { .. } | Command::TelegramCallSignal { .. } | Command::TelegramAcceptLoginToken { .. } | Command::TelegramCallSpeaking { .. } diff --git a/crates/chatd/src/server.rs b/crates/chatd/src/server.rs index ff692b2c..28e2c572 100644 --- a/crates/chatd/src/server.rs +++ b/crates/chatd/src/server.rs @@ -6674,6 +6674,15 @@ impl Chat { Err(err) => internal(err), } } + Request::CancelDownload { account, id } => { + // Only an adapter that fetches files over its own session (Telegram) has a + // download of its own to stop; the others let the command pass. + let adapter = lock(&self.adapters).get(&account).map(Adapter::sender); + if let Some(adapter) = adapter { + let _ = adapter.send(Command::CancelDownload { id }); + } + Response::Ok + } Request::FetchPreview { account, ids, max_bytes } => { let adapter = lock(&self.adapters).get(&account).map(Adapter::sender); let ids = &ids[..ids.len().min(PAGE_LIMIT as usize)]; diff --git a/crates/chatd/tests/telegram.rs b/crates/chatd/tests/telegram.rs index cd41dddc..f44f9cb3 100644 --- a/crates/chatd/tests/telegram.rs +++ b/crates/chatd/tests/telegram.rs @@ -3394,6 +3394,74 @@ fn a_dropped_large_file_resumes_from_the_part() { assert!(world.called("GetFile document 9400 at 1048576") >= 1, "{:#?}", world.calls()); } +/// Where the download of a Telegram file is kept while it is on its way. +fn part_path(world: &World, id: &str) -> PathBuf { + chatd::blobs::path_of(&world.dir.join("media"), &account(), id).with_extension("part") +} + +/// Asks chatd to stop a download, in the wire's own words: a chatd from before the request +/// answers `Unsupported`, and the download runs on. +fn stop_download(world: &World, id: &str) -> Response { + let mut stream = ChatStream::connect(&world.dir.join("chat.sock")).unwrap(); + write_frame(&mut stream, &serde_json::json!({"op": "cancel_download", "account": account(), "id": id})).unwrap(); + read_frame(&mut stream).unwrap() +} + +#[test] +fn a_stopped_download_ends_at_its_next_piece_and_leaves_no_part() { + let world = World::with(Some(SESSION), "30", &[("TINYCLIENT_TELEGRAM_FILE_HOLD", "1")]); + world.connected(); + world.watch(Watching { conversation: Some(key("u7002")), ..Watching::default() }); + world.until("history", || world.message("u7002", "12")); + world.steer("big-file"); + assert_eq!(world.arrived("u7002", "31").attachments[0].file.id, "d9400"); + // The user opened it: Telegram is asked for the first piece, which the wire holds. + assert_eq!(fetch_path(&world, "d9400"), None); + world.until("the first piece asked for", || (world.called("GetFile document 9400 at 0") > 0).then_some(())); + world.until("the part file", || part_path(&world, "d9400").exists().then_some(())); + assert_eq!(stop_download(&world, "d9400"), Response::Ok); + world.steer("file-go"); + // The piece on its way was the last: nothing more is asked for, and nothing is kept. + world.until("the part file gone", || (!part_path(&world, "d9400").exists()).then_some(())); + assert_eq!(world.called("GetFile document 9400 at 1048576"), 0, "{:#?}", world.calls()); + // Nothing landed. (The store lists a Telegram file only once it lands, so there is no row + // of it to ask for.) + assert!(!part_path(&world, "d9400").exists(), "the part file is gone"); + assert!(!chatd::blobs::path_of(&world.dir.join("media"), &account(), "d9400").exists(), "nothing landed"); + // Asked for again, it is fetched from the start and lands whole. + let landed = world.until("the file on disk", || fetch_path(&world, "d9400")); + let expected: Vec = (0..(1024 * 1024 + 64)).map(|at| (at % 251) as u8).collect(); + assert_eq!(std::fs::read(&landed).unwrap(), expected); + assert_eq!(world.called("GetFile document 9400 at 0"), 2, "{:#?}", world.calls()); +} + +#[test] +fn a_download_stopped_while_it_waits_its_turn_is_never_asked_for() { + let world = World::with(Some(SESSION), "30", &[("TINYCLIENT_TELEGRAM_FILE_HOLD", "1")]); + world.connected(); + world.watch(Watching { conversation: Some(key("u7002")), ..Watching::default() }); + world.until("history", || world.message("u7002", "12")); + // The big file is opened first, and the wire holds its first piece. + world.steer("big-file"); + world.arrived("u7002", "31"); + assert_eq!(fetch_path(&world, "d9400"), None); + world.until("the first piece asked for", || (world.called("GetFile document 9400 at 0") > 0).then_some(())); + // A photo comes while the chat is open, so its thumbnail waits behind the big file. The + // line after it is on screen: that proves the thumbnail was queued before the stop. + world.steer("photo"); + world.steer("incoming"); + world.arrived("u7002", "13"); + assert_eq!(stop_download(&world, "p6014m"), Response::Ok); + world.steer("file-go"); + world.until("the big file asked to its end", || (world.called("GetFile document 9400 at 1048576") > 0).then_some(())); + sleep(Duration::from_millis(1_500)); + assert_eq!(world.called("GetFile photo 6014 m"), 0, "{:#?}", world.calls()); + // Asked for again, it is fetched as any picture is. + let thumb = world.until("the thumbnail on disk", || fetch_path(&world, "p6014m")); + assert_eq!(std::fs::read(&thumb).unwrap(), (0..FILE_BYTES).map(|at| (at % 251) as u8).collect::>()); + assert_eq!(world.called("GetFile photo 6014 m at 0"), 1, "{:#?}", world.calls()); +} + #[test] fn a_link_preview_telegram_finishes_later_reaches_the_message() { let world = World::signed_in(); diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 9db39429..2f2d3f13 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -3270,6 +3270,15 @@ pub enum Request { span: Option<(u64, u64)>, }, + /// Stops fetching this file. The piece on its way is the last, nothing is kept of it on + /// disk, and a file already on disk stays. Nothing is announced: asking for the file again + /// (`Fetch`) fetches it from the start. Answers `Ok` at once. Only a network that fetches + /// files over its own session (Telegram) has a download to stop; the others do nothing. + CancelDownload { + account: AccountKey, + id: String, + }, + /// Fetches at most `max_bytes` (clamped to [`TEXT_PREVIEW_MAX_BYTES`]) from the head of /// registered file attachments via a ranged HTTP request through chatd's media cache, for /// inline text/code previews. Returned [`MediaFile`] ids carry a `"head:"` prefix so full diff --git a/crates/tinyclient/src/client.rs b/crates/tinyclient/src/client.rs index c3283683..f64710a9 100644 --- a/crates/tinyclient/src/client.rs +++ b/crates/tinyclient/src/client.rs @@ -370,6 +370,8 @@ mod tests { "UserGroupUpdate", "UserGroupMembers", "SectionCreate", "SectionRename", "SectionDelete", "SectionReorder", // chatd sends this one to itself when a voice message starts playing. "MarkPlayed", + // The window's own way to stop a download is not built yet; the request is. + "CancelDownload", ]; fn sources(dir: &std::path::Path, into: &mut String) { diff --git a/docs/architecture.md b/docs/architecture.md index 846ea8fd..20fa95d0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -65,6 +65,7 @@ Seven adapters ship, one per `Network::ALL`, started from `adapters::start`: Dis | `Reactions {conversation}` | `Reactions {conversation, rules}` (kept 5 min) | `Command::ReactionRules` | | `Edit {.., text}`, `Delete {..}` | `Ok` once the network accepted | `Command::Edit` / `Delete`. Discord, Telegram and Tiny do this. An adapter that does not answers `Unsupported`. | | `Fetch {account, ids, size, retry}` | `Media {files}` | store (size, retry); `blobs` | +| `CancelDownload {account, id}` | `Ok` | `Command::CancelDownload`. Telegram stops the download at the piece on its way and keeps no part file of it; the others do nothing. | | `SignIn {network, at}`, `SignOut {account}` | `Status` | server | | `CallStart`, `CallAccept`, `CallDecline`, `CallEnd`, `CallSet`, `Media(..)` | `Status` | `media::Calls`; `Command::Call*` | | `Play(Start {account, file, path, conversation, message, title, at, rate, output} \| Pause \| Seek {at} \| Rate {rate} \| Stop)` | `Ok`; then `Change::Playback` | `playback::Player`; `mediad --play` | diff --git a/e2e/scenarios/telegram-cancel-download/drive.linux.sh b/e2e/scenarios/telegram-cancel-download/drive.linux.sh new file mode 100644 index 00000000..a6a1c335 --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# telegram-cancel-download on Linux. The lab runs this with bash while ffmpeg films the display. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/telegram-cancel-download/drive.macos.sh b/e2e/scenarios/telegram-cancel-download/drive.macos.sh new file mode 100644 index 00000000..5309da5c --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# telegram-cancel-download on macOS. The lab runs this with bash while the display is filmed. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/telegram-cancel-download/drive.py b/e2e/scenarios/telegram-cancel-download/drive.py new file mode 100644 index 00000000..3e30f7fc --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Stopping a Telegram download ends it at the piece on its way and leaves no part file behind. + +Starts this build's chatd with the scripted Telegram wire (TINYCLIENT_TELEGRAM_FAKE) on an +isolated profile, steers it over its control file the way tests/telegram.rs does, and speaks +chatd's real socket. A file the user opened is asked of Telegram piece by piece; the wire holds +the first piece; the shell stops the download; the wire lets go. Then Telegram is not asked for +the rest, the part file is gone and nothing landed. Asking for the file again fetches it from +the start and it lands whole. A build from before the fix does not know the request (it answers +an error), asks Telegram for the rest of the file and keeps the part file, so this driver fails +there. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR. +""" + +import json +import os +import socket +import struct +import subprocess +import sys +import time + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") + +ME = "7001" +CHAT = "u7002" +SESSION = json.dumps({"user": 7001, "name": "Mira Kessler", "home": 2, "dcs": []}) +# What `big-file` posts into the chat: a document Telegram serves as one piece of a megabyte +# and 64 bytes more. +FILE = "d9400" +FILE_BYTES = 1024 * 1024 + 64 +# What another run of the fake, or a lab machine, may have left in the environment. +KNOBS = ("TINYCLIENT_TELEGRAM_HOLD", "TINYCLIENT_TELEGRAM_PEER_HOLD", "TINYCLIENT_TELEGRAM_MANY", "TINYCLIENT_TELEGRAM_PREMIUM") +ACCOUNT = {"network": "telegram", "account": ME} + +FAILED = False +STEPS = "" + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false") + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def app_bin(app_dir): + name = "chatd.exe" if sys.platform == "win32" else "chatd" + if sys.platform == "darwin" and app_dir.endswith(".app"): + return os.path.join(app_dir, "Contents", "MacOS", "chatd") + return os.path.join(app_dir, name) + + +def connect(sock_path): + """chatd's socket: a file on Unix, the matching named pipe on Windows.""" + if sys.platform == "win32": + return open("\\\\.\\pipe\\" + sock_path, "r+b", buffering=0) + stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stream.settimeout(5) + stream.connect(sock_path) + return stream + + +def write_all(stream, data): + view = memoryview(data) + while view: + written = stream.write(view) + if not written: + raise RuntimeError("chatd's socket took nothing") + view = view[written:] + + +class Chat: + def __init__(self, sock_path): + self.stream = connect(sock_path) + + def ask(self, request): + body = json.dumps(request, separators=(",", ":")).encode() + write_all(self.stream, struct.pack("!I", len(body)) + body) + head = b"" + while len(head) < 4: + got = self.stream.read(4 - len(head)) + if not got: + raise RuntimeError("chatd closed its socket") + head += got + length = struct.unpack("!I", head)[0] + if length > 1024 * 1024: + raise RuntimeError("answer exceeds the protocol size limit") + chunks = b"" + while len(chunks) < length: + got = self.stream.read(length - len(chunks)) + if not got: + raise RuntimeError("chatd closed its socket mid-frame") + chunks += got + return json.loads(chunks) + + def close(self): + try: + self.stream.close() + except OSError: + pass + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + binary = app_bin(APP) + if not os.path.isfile(binary): + step("chatd is in E2E_APP_DIR", False) + return 1 + + data = os.path.join(OUT, "data") + os.makedirs(data, exist_ok=True) + sock_path = os.path.join(data, "chat.sock") + control = os.path.join(data, "telegram.ctl") + open(control, "a", encoding="utf-8").close() + env = os.environ.copy() + for name in list(env): + if name.startswith("TINYCLIENT_SESSION_") or name in KNOBS: + del env[name] + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_TELEGRAM_FAKE"] = "30" + # Yesterday's midnight UTC, as tests/telegram.rs: the Inbox leaves out a chat nobody + # touched for thirty days. + env["TINYCLIENT_TELEGRAM_T0"] = str(int(time.time()) // 86_400 * 86_400 - 86_400) + # The wire holds this file's pieces until the driver says `file-go`. + env["TINYCLIENT_TELEGRAM_FILE_HOLD"] = "1" + env["TINYCLIENT_SESSION_TELEGRAM"] = SESSION + kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + with open(os.path.join(OUT, "chatd.out.log"), "w", encoding="utf-8") as out, open(os.path.join(OUT, "chatd.err.log"), "w", encoding="utf-8") as err: + kwargs["stdout"] = out + kwargs["stderr"] = err + proc = subprocess.Popen([binary], **kwargs) + chat = None + try: + deadline = time.time() + 15 + while chat is None: + if proc.poll() is not None: + step("chatd stays up for the driver", False) + return 1 + if time.time() > deadline: + step("chatd opens its socket", False) + return 1 + try: + chat = Chat(sock_path) + except OSError: + time.sleep(0.1) + drive(chat, control, data) + finally: + if chat: + chat.close() + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + return 1 if FAILED else 0 + + +def key(id): + return {"network": "telegram", "account": ME, "id": id} + + +def name_of(file_id): + """The name chatd keeps a media file under: FNV-1a of its id (blobs::name_of).""" + value = 0xCBF29CE484222325 + for byte in file_id.encode("utf-8"): + value = ((value ^ byte) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + return "%016x" % value + + +def wait(what, chat, look, seconds=20): + deadline = time.time() + seconds + while time.time() < deadline: + found = look() + if found is not None: + step(what, True) + return found + time.sleep(0.2) + step(what, False) + return None + + +def steer(control, line): + with open(control, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def ask(chat, request): + try: + return chat.ask(request) + except Exception: + return None + + +def messages(chat, id): + answer = ask(chat, {"op": "messages", "conversation": key(id), "page": "newest", "limit": 100}) + return (answer or {}).get("messages", []) + + +def drive(chat, control, data): + # The scripted wire writes what it is asked there, one line per request. + calls = os.path.join(data, "telegram.calls") + # Where chatd keeps the file while it downloads (blobs::path_of, with the part's extension). + part = os.path.join(data, "media", "telegram", ME, name_of(FILE) + ".part") + + def asked(start): + try: + with open(calls, encoding="utf-8") as handle: + lines = [line.strip() for line in handle] + except OSError: + return 0 + return sum(1 for line in lines if line.startswith(start)) + + def fetch(): + answer = ask(chat, {"op": "fetch", "account": ACCOUNT, "ids": [FILE]}) + files = (answer or {}).get("files") or [] + return files[0] if files else {} + + def accounts(): + return (ask(chat, {"op": "status"}) or {}).get("accounts") or [] + + status = wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"})) + if status is None: + return + wait("Telegram is connected", chat, lambda: (any(a["link"] == "connected" for a in accounts()) or None)) + wait("the fake's chat is known", chat, lambda: (ask(chat, {"op": "conversation", "conversation": key("u7003")}) or {}).get("conversation")) + + # The chat is open, as the shell opens it. + ask(chat, {"op": "watch", "watching": {"conversation": key(CHAT)}}) + wait("the chat's history is read", chat, lambda: next((m for m in messages(chat, CHAT) if m["id"] == "12"), None)) + + # The file arrives, and the user opens it: Telegram is asked for its first piece, which the + # wire holds, so this is a download in progress. + steer(control, "big-file") + wait("the chat holds the file", chat, lambda: next((m for m in messages(chat, CHAT) if m["id"] == "31" and m.get("attachments") and m["attachments"][0]["file"]["id"] == FILE), None)) + step("the file is not on disk when it is asked for", "path" not in fetch()) + wait("Telegram is asked for the file's first piece, which the wire holds", chat, lambda: asked("GetFile document 9400 at 0") or None) + wait("the download keeps a part file", chat, lambda: os.path.exists(part) or None) + pieces = asked("GetFile document 9400 at") + + # The shell stops it, as its cancel does, and the wire lets its piece go. + answer = ask(chat, {"op": "cancel_download", "account": ACCOUNT, "id": FILE}) + step("chatd takes the request to stop the download", bool(answer) and answer.get("op") == "ok") + steer(control, "file-go") + wait("the part file is gone", chat, lambda: (not os.path.exists(part)) or None) + step("Telegram is not asked for the rest of the file", asked("GetFile document 9400 at") == pieces) + file = fetch() + step("nothing landed and nothing failed", "path" not in file and "failed" not in file) + + # Asking for it again is a new download: it starts over and ends on disk, whole. + def on_disk(): + return fetch().get("path") or None + + path = wait("asking for the file again lands it", chat, on_disk) + if path is not None: + with open(path, "rb") as handle: + step("the file holds the bytes Telegram served", handle.read() == bytes(at % 251 for at in range(FILE_BYTES))) + step("it was fetched from the start, as a second download", asked("GetFile document 9400 at 0") == 2) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/telegram-cancel-download/drive.windows.ps1 b/e2e/scenarios/telegram-cancel-download/drive.windows.ps1 new file mode 100644 index 00000000..6178be08 --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/drive.windows.ps1 @@ -0,0 +1,17 @@ +# telegram-cancel-download on Windows. The lab runs this in the console session it is already filming. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/telegram-cancel-download/scenario.json b/e2e/scenarios/telegram-cancel-download/scenario.json new file mode 100644 index 00000000..b82d430e --- /dev/null +++ b/e2e/scenarios/telegram-cancel-download/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "telegram-cancel-download", + "title": "Stopping a Telegram download ends it at the piece on its way and leaves no part file behind", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The lab's phone demo build bypasses chatd and cannot run the scripted Telegram wire.", + "ios": "The lab's phone demo build bypasses chatd and cannot run the scripted Telegram wire." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +} From 9dbeea8c1be200a8608b89f63e048c100d24c53b Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 14:33:39 +0100 Subject: [PATCH 7/8] Mark unread from a Tiny message goes by time and the post's number, and a chat forgotten with no read marker comes back --- crates/chatd/src/store.rs | 164 ++++++- .../tiny-mark-unread-order/drive.linux.sh | 9 + .../tiny-mark-unread-order/drive.macos.sh | 9 + e2e/scenarios/tiny-mark-unread-order/drive.py | 379 +++++++++++++++ .../tiny-mark-unread-order/drive.windows.ps1 | 18 + .../tiny-mark-unread-order/fixture.py | 449 ++++++++++++++++++ .../tiny-mark-unread-order/scenario.json | 12 + 7 files changed, 1023 insertions(+), 17 deletions(-) create mode 100644 e2e/scenarios/tiny-mark-unread-order/drive.linux.sh create mode 100644 e2e/scenarios/tiny-mark-unread-order/drive.macos.sh create mode 100644 e2e/scenarios/tiny-mark-unread-order/drive.py create mode 100644 e2e/scenarios/tiny-mark-unread-order/drive.windows.ps1 create mode 100644 e2e/scenarios/tiny-mark-unread-order/fixture.py create mode 100644 e2e/scenarios/tiny-mark-unread-order/scenario.json diff --git a/crates/chatd/src/store.rs b/crates/chatd/src/store.rs index 7faec748..4f12761c 100644 --- a/crates/chatd/src/store.rs +++ b/crates/chatd/src/store.rs @@ -3616,9 +3616,11 @@ impl Store { } /// `message_id` is the first message that counts as unread. Empty means the newest message - /// stored. The marker becomes the newest stored id strictly before that, which may be older - /// than the marker already held, and the badge is counted from what is stored. When no - /// messages are stored yet, the badge still becomes at least one and the ack target is empty + /// stored. The marker becomes the newest stored id strictly before that, in the order the + /// messages are read: the one the window shows above it. That is time, then the server's + /// sequence, since a Tiny id is a UUID whose text says nothing about time. The marker may + /// be older than the one already held, and the badge is counted from what is stored. When + /// no messages are stored yet, the badge still becomes at least one and the ack target is empty /// (for networks with a dialog-level unread mark). `None` when the conversation is missing. /// The pair is the ack target (empty when the first stored message is the one marked or no /// messages are stored) and how many of the unread messages mention me. @@ -3709,15 +3711,19 @@ impl Store { Ok(found.is_some()) } - /// The newest stored id strictly before `target`. Empty when nothing is. + /// The newest stored id strictly before `target`, in the order the messages are read. + /// Empty when nothing is. fn message_before(&self, conversation: &Key, target: &str) -> rusqlite::Result { + let before = self.beside_target(conversation, target, "<")?; Ok(self .db .query_row( - "SELECT id FROM message - WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND pending = 0 - AND (length(id), id) < (length(?4), ?4) - ORDER BY length(id) DESC, id DESC LIMIT 1", + &format!( + "SELECT id FROM message + WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND pending = 0 + AND {before} + {NEWEST_FIRST} LIMIT 1" + ), params![word(&conversation.network), conversation.account, conversation.id, target], |row| row.get(0), ) @@ -3725,9 +3731,25 @@ impl Store { .unwrap_or_default()) } - /// How many stored messages are unread from `anchor`, and how many of those mention me. - /// `inclusive` counts `anchor` itself (it is the first unread). Otherwise `anchor` is the - /// last message still read, and an empty anchor counts every stored message. + /// SQL that is true for a stored message of `conversation` on the `side` of `target` + /// (`<`, `>` or `>=`), in the order the messages are read ([`PLACE`]): time, then the + /// server's sequence, and the id only where both tie. A stored UUID is placed by that + /// order, since its text is no clock. A target the store does not hold has no place: its + /// id is then compared as text, which is the order of an id that carries its own. + fn beside_target(&self, conversation: &Key, target: &str, side: &str) -> rusqlite::Result { + if self.message_place(conversation, target).is_some() { + return Ok(format!( + "{PLACE} {side} (SELECT {PLACE_TERMS} FROM message + WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND id = ?4)" + )); + } + Ok(format!("(length(id), id) {side} (length(?4), ?4)")) + } + + /// How many stored messages are unread from `anchor`, and how many of those mention me, + /// counted in the order the messages are read. `inclusive` counts `anchor` itself (it is + /// the first unread). Otherwise `anchor` is the last message still read, and an empty + /// anchor counts every stored message. fn unread_from(&self, conversation: &Key, anchor: &str, inclusive: bool) -> rusqlite::Result<(u32, u32)> { let (count, mentions): (i64, i64) = if anchor.is_empty() { self.db.query_row( @@ -3739,14 +3761,14 @@ impl Store { |row| Ok((row.get(0)?, row.get(1)?)), )? } else { - let side = if inclusive { ">=" } else { ">" }; + let from = self.beside_target(conversation, anchor, if inclusive { ">=" } else { ">" })?; self.db.query_row( &format!( "SELECT COUNT(*), COALESCE(SUM(CASE WHEN json_extract(body, '$.mentions_me') IN (1, 'true') THEN 1 ELSE 0 END), 0) FROM message WHERE network = ?1 AND account = ?2 AND conversation = ?3 AND pending = 0 - AND (length(id), id) {side} (length(?4), ?4)" + AND {from}" ), params![word(&conversation.network), conversation.account, conversation.id, anchor], |row| Ok((row.get(0)?, row.get(1)?)), @@ -4203,8 +4225,8 @@ impl Store { preview = CASE WHEN ?15 THEN ?4 ELSE preview END, preview_expires = CASE WHEN ?15 THEN ?14 ELSE preview_expires END, updated = max(updated, ?5), - hidden = CASE WHEN ?12 AND (?16 OR (last_read != '' - AND (length(last_read), last_read) < (length(?6), ?6))) THEN 0 ELSE hidden END + hidden = CASE WHEN ?12 AND (?16 OR last_read = '' + OR (length(last_read), last_read) < (length(?6), ?6)) THEN 0 ELSE hidden END WHERE network = ?1 AND account = ?2 AND id = ?3", params![ network, @@ -4223,6 +4245,9 @@ impl Store { incoming.expires_at, replace_preview, // A UUID says nothing about time: any live message brings the row back. + // So does a row with no marker, whatever the network: a chat forgotten + // before anything marked where it was read has nothing to be newer than, + // and its empty marker compared as text kept it hidden for good. is_uuid(&incoming.id), ], )?; @@ -5865,6 +5890,14 @@ mod tests { Message::plain(id, "mara", text, sent, false) } + /// Whether chatd would announce a just-arrived `message`, by the conversation's row as the + /// store keeps it: a hidden row announces nothing. + fn announced(store: &Store, key: &Key, message: &Message) -> bool { + let row = store.conversation(key).unwrap().expect("the conversation is there"); + let moment = crate::notify::Moment { now: message.sent, ..Default::default() }; + crate::notify::decide(&protocol::settings::Values::default(), &row, message, &moment).is_some() + } + fn ids(page: &MessagePage) -> Vec<&str> { page.messages.iter().map(|message| message.id.as_str()).collect() } @@ -6262,6 +6295,9 @@ mod tests { let never = Message { state: SendState::Pending, ..said("3", "world in waiting", 30) }; store.ingest(&key, &never, false).unwrap(); store.ingest(&hidden, &said("4", "world of secrets", 40), true).unwrap(); + // A hidden row with no read marker comes back on the next live message, so this one is + // hidden after its message arrived: what it hides behind keeps it hidden now. + store.forget_conversation(&hidden).unwrap(); let request = Key::new(&account, "stranger"); store .upsert_conversation(&account, &ConversationRow { @@ -6656,15 +6692,106 @@ mod tests { assert!(store.forget_conversation(&dm).unwrap()); assert!(store.conversation(&dm).unwrap().unwrap().hidden); // The later message has the smaller id. - store.ingest(&dm, &said(low, "are you there?", 20), true).unwrap(); + let later = said(low, "are you there?", 20); + store.ingest(&dm, &later, true).unwrap(); assert!(!store.conversation(&dm).unwrap().unwrap().hidden); - + assert!(announced(&store, &dm, &later), "back in the Inbox, the message that brought it notifies"); assert!(store.set_seen(&dm, high).unwrap()); assert!(store.set_seen(&dm, low).unwrap(), "the newer receipt names the smaller id"); assert!(!store.set_seen(&dm, low).unwrap()); } + /// A chat forgotten before anything marked where it was read keeps no marker, so the next + /// live message has nothing to be newer than. On a network whose ids carry their order the + /// empty marker, compared as text, kept the chat hidden for good: no Inbox row, and the + /// message was never announced. + #[test] + fn a_forgotten_direct_without_a_marker_comes_back_on_the_next_live_message() { + let (mut store, key) = store(); + let account = key.account(); + let dm = Key::new(&account, "dm"); + store.upsert_conversation(&account, &ConversationRow::new("dm", ConversationKind::Direct, "Mara")).unwrap(); + // The network listed the chat with nothing previewed and nothing read. + store.set_counts(&dm, 0, 0, None, NOW).unwrap(); + assert!(store.forget_conversation(&dm).unwrap()); + let row = store.conversation(&dm).unwrap().unwrap(); + assert!(row.hidden && row.last_read.is_none(), "forgotten with no marker"); + + let live = said("20", "are you there?", NOW + 10); + store.ingest(&dm, &live, true).unwrap(); + let row = store.conversation(&dm).unwrap().unwrap(); + assert!(!row.hidden, "the next live message brings the chat back"); + assert_eq!(row.unread, 1); + assert!(announced(&store, &dm, &live), "back in the Inbox, the message notifies like any other direct message"); + } + + /// Tiny message ids are UUIDs, so their text is no clock. "Mark unread from here" on the + /// middle of three messages counts it and the newer one, and puts the marker on the oldest: + /// the order the window lists them in. By text the middle one has the smallest id, which + /// left nothing before it and put all three after it. + #[test] + fn marking_unread_from_a_uuid_message_goes_by_time_not_by_the_ids_text() { + let (mut store, key) = store(); + let first = "ffffffff-ffff-4fff-8fff-ffffffffffff"; + let middle = "00000000-0000-4000-8000-000000000000"; + let last = "55555555-5555-4555-8555-555555555555"; + store.ingest(&key, &said(first, "one", 10), true).unwrap(); + store.ingest(&key, &said(middle, "two", 20), true).unwrap(); + store.ingest(&key, &said(last, "three", 30), true).unwrap(); + assert!(store.mark_read(&key, "").unwrap(), "read up to the newest message"); + + let (marker, mentions) = store.mark_unread(&key, middle).unwrap().expect("the conversation is there"); + assert_eq!((marker.as_str(), mentions), (first, 0), "the marker is the message shown above the one marked"); + let row = store.conversation(&key).unwrap().unwrap(); + assert_eq!((row.unread, row.last_read.as_deref()), (2, Some(first)), "the marked message and the newer one are unread"); + + // From the newest message, as the sidebar's "Mark unread" asks: one unread, and the + // marker on the message shown above it. + let (marker, _) = store.mark_unread(&key, "").unwrap().unwrap(); + assert_eq!(marker, middle); + let row = store.conversation(&key).unwrap().unwrap(); + assert_eq!((row.unread, row.last_read.as_deref()), (1, Some(middle))); + } + + /// Tiny stamps a plaintext message to the second and an encrypted one to the minute, and + /// numbers each post. Inside one stamp that sequence is the order the window shows. + #[test] + fn marking_unread_inside_one_stamp_goes_by_the_post_sequence() { + let (mut store, key) = store(); + let post = |id: &str, text: &str, seq: i64| Message { seq, ..said(id, text, NOW) }; + let first = "ffffffff-ffff-4fff-8fff-ffffffffffff"; + let middle = "00000000-0000-4000-8000-000000000000"; + let last = "55555555-5555-4555-8555-555555555555"; + store.ingest(&key, &post(first, "one", 1), true).unwrap(); + store.ingest(&key, &post(middle, "two", 2), true).unwrap(); + store.ingest(&key, &post(last, "three", 3), true).unwrap(); + assert!(store.mark_read(&key, "").unwrap(), "read up to the newest message"); + + let (marker, mentions) = store.mark_unread(&key, middle).unwrap().expect("the conversation is there"); + assert_eq!((marker.as_str(), mentions), (first, 0), "the marker is the first post of the stamp"); + let row = store.conversation(&key).unwrap().unwrap(); + assert_eq!((row.unread, row.last_read.as_deref()), (2, Some(first)), "the marked post and the one after it are unread"); + } + + /// A marker that names a message the store has not got has no place among the stored ones. + /// Its id is still compared as text, which is the order of an id that carries its own. + #[test] + fn a_marker_for_a_message_the_store_has_not_got_still_compares_ids_as_text() { + let (mut store, key) = store(); + store.ingest(&key, &said("8", "one", 10), true).unwrap(); + store.ingest(&key, &said("9", "two", 20), true).unwrap(); + assert!(store.mark_read(&key, "").unwrap()); + + let (marker, mentions) = store.mark_unread(&key, "10").unwrap().unwrap(); + let unread = store.conversation(&key).unwrap().unwrap().unread; + assert_eq!((marker.as_str(), mentions, unread), ("9", 0, 1), "the newest stored message is before it, and the badge turns on for the one not stored"); + + assert!(store.apply_manual_ack(&key, "5", None).unwrap(), "another device read up to a message that is not stored"); + let row = store.conversation(&key).unwrap().unwrap(); + assert_eq!((row.unread, row.mentions, row.last_read.as_deref()), (2, 0, Some("5")), "both stored messages are after it"); + } + #[test] fn unread_marks_of_one_space_do_not_name_another_spaces_rows() { let (mut store, key) = store(); @@ -7128,6 +7255,9 @@ mod tests { for (id, days) in [("old", 40), ("starred-old", 40), ("app", 1), ("archived", 1), ("stranger", 1), ("hidden", 1), ("recent", 2)] { store.ingest(&at(id), &said(&format!("{id}-1"), "hello", now - days * day), true).unwrap(); } + // A hidden row with no read marker comes back on the next live message, so this one is + // hidden again after the one above; the marker that leaves keeps it hidden. + store.forget_conversation(&at("hidden")).unwrap(); store.set_starred(&at("starred-old"), true).unwrap(); store.mark_read(&at("old"), "old-1").unwrap(); let titles = |store: &Store, filter| -> Vec { diff --git a/e2e/scenarios/tiny-mark-unread-order/drive.linux.sh b/e2e/scenarios/tiny-mark-unread-order/drive.linux.sh new file mode 100644 index 00000000..2afd23c5 --- /dev/null +++ b/e2e/scenarios/tiny-mark-unread-order/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# tiny-mark-unread-order on Linux. The lab runs this with bash while ffmpeg films the display. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/tiny-mark-unread-order/drive.macos.sh b/e2e/scenarios/tiny-mark-unread-order/drive.macos.sh new file mode 100644 index 00000000..52050eab --- /dev/null +++ b/e2e/scenarios/tiny-mark-unread-order/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# tiny-mark-unread-order on macOS. The lab runs this with bash while the helper films the app window. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/tiny-mark-unread-order/drive.py b/e2e/scenarios/tiny-mark-unread-order/drive.py new file mode 100644 index 00000000..68b9091a --- /dev/null +++ b/e2e/scenarios/tiny-mark-unread-order/drive.py @@ -0,0 +1,379 @@ +#!/usr/bin/env python3 +"""Drive chatd against fixture.py and read the badge back from the app. + +Tiny message ids are UUIDs, so their text is no clock. Bea writes three messages in one direct +over the live socket: the oldest has the id that sorts last, the one in the middle the id that +sorts first. The person reads the chat, then picks "Mark unread from here" on the middle message, +which the window asks chatd for over the chat pipe; this driver sends the same two requests. The +Inbox must then count that message and the newer one, and the read marker must sit on the +message above it, the oldest one. Compared as text, nothing sorted before the middle message +and all three sorted after it. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR, E2E_SABOTAGE=1 (no session, so the badge step +fails). E2E_NO_WINDOW=1 skips opening the window, for a run with no display. +""" + +import json +import os +import re +import socket +import sqlite3 +import struct +import subprocess +import sys +import tempfile +import time + +import fixture + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") +SABOTAGE = os.environ.get("E2E_SABOTAGE") == "1" +NO_WINDOW = os.environ.get("E2E_NO_WINDOW") == "1" +ME = fixture.ME +TOKEN = fixture.TOKEN +BEA = {"network": "tiny", "account": ME, "id": fixture.DIRECT} +UNREAD_AFTER_MARK = "2" +CHECK = "Bea shows 2 unread and the marker is on the message above the one marked" + +FAILED = False +STEPS = "" + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = json.dumps({"t": round(now(), 1), "step": words, "ok": bool(ok)}, ensure_ascii=True) + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def binaries(app_dir): + if sys.platform == "win32": + return os.path.join(app_dir, "chatd.exe"), os.path.join(app_dir, "tinyclient.exe") + if sys.platform == "darwin" and app_dir.endswith(".app"): + mac = os.path.join(app_dir, "Contents", "MacOS") + return os.path.join(mac, "chatd"), os.path.join(mac, "tinyclient") + return os.path.join(app_dir, "chatd"), os.path.join(app_dir, "tinyclient") + + +def scratch_dir(): + if sys.platform == "win32": + path = os.path.join(OUT, "data") + os.makedirs(path, exist_ok=True) + return path + return tempfile.mkdtemp(prefix="tmuo-") + + +def session(port): + return json.dumps({ + "base_url": "http://127.0.0.1:%d" % port, + "token": TOKEN, + "user_id": ME, + "email": "ada@example.com", + "display_name": "Ada", + "role": "member", + }) + + +def child_env(data, port): + env = os.environ.copy() + for key in list(env): + if key.startswith("TINYCLIENT_SESSION_"): + del env[key] + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_LOG_LEVEL"] = "info" + if not SABOTAGE: + # The label is "Tiny server", so the scratch session name keeps the space. + env["TINYCLIENT_SESSION_TINY SERVER"] = session(port) + return env + + +def popen(args, **kwargs): + if sys.platform == "win32": + kwargs["creationflags"] = kwargs.get("creationflags", 0x08000000) + return subprocess.Popen(args, **kwargs) + + +def stop(proc): + if proc is None or proc.poll() is not None: + return + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + + +def wait_until(limit, predicate): + deadline = time.time() + limit + while time.time() < deadline: + if predicate(): + return True + time.sleep(0.1) + return False + + +def inbox(tinyclient, env, data): + kwargs = {"cwd": data, "env": env, "capture_output": True, "text": True, "timeout": 30} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + done = subprocess.run([tinyclient, "--text"], **kwargs) + return done.returncode, done.stdout or "" + + +def badge_of(text, title): + """The unread column of one inbox row, "" when nothing is unread. None when that title is + not listed. + + `--text` prints `"{:<8} {:<24} {:>3} {:>4} {}"`. The network label is wider than 8, so the + title starts after that whole label and the following space. One more space separates the + title from the 3-column unread. + """ + prefix = "Tiny server " + for line in text.splitlines(): + if not line.startswith(prefix): + continue + rest = line[len(prefix):] + if len(rest) < 28 or rest[:24].rstrip() != title: + continue + return rest[25:28].strip() + return None + + +def beas_direct(data): + """What the store keeps for Bea's direct: its unread count, its read marker and how many + messages are stored in it. None when there is no such row. + + chatd keeps this file open under WAL. A second connection can read the committed rows; one + that is busy is asked again. + """ + path = os.path.join(data, "chat.sqlite") + if not os.path.exists(path): + return None + for _ in range(10): + try: + con = sqlite3.connect(path, timeout=2) + row = con.execute( + "SELECT c.unread, c.last_read, (SELECT COUNT(*) FROM message m" + " WHERE m.network = c.network AND m.account = c.account AND m.conversation = c.id)" + " FROM conversation c WHERE c.network = 'tiny' AND c.account = ? AND c.id = ?", + (ME, fixture.DIRECT), + ).fetchone() + con.close() + if row is None: + return None + return int(row[0]), row[1], int(row[2]) + except sqlite3.Error: + time.sleep(0.1) + return None + + +def write_all(stream, data): + view = memoryview(data) + while view: + written = stream.write(view) + if not written: + raise OSError("chatd's pipe took nothing") + view = view[written:] + + +def read_exact(stream, count): + chunks = b"" + while len(chunks) < count: + got = stream.read(count - len(chunks)) + if not got: + raise OSError("chatd closed its pipe before the answer was whole") + chunks += got + return chunks + + +def ask(stream, request): + """One request the way the window sends it: four bytes of length, then JSON. The answer.""" + body = json.dumps(request, separators=(",", ":")).encode() + write_all(stream, struct.pack("!I", len(body)) + body) + length = struct.unpack("!I", read_exact(stream, 4))[0] + if length > 1024 * 1024: + raise OSError("chatd's answer is larger than a frame") + return json.loads(read_exact(stream, length)) + + +def chat_pipe(data, pid): + """chatd's chat pipe, opened the way the window opens it to ask something: `chat.sock` under + the scratch directory on Unix. On Windows it is a named pipe chatd names after that path. + Rather than repeat chatd's naming, the driver asks each chat pipe which process serves it + and keeps the one served by the chatd it started, so it never writes to another tinyclient. + None when it did not come up in time. + """ + deadline = time.time() + 10 + if sys.platform != "win32": + path = os.path.join(data, "chat.sock") + while time.time() < deadline: + stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stream.settimeout(30) + try: + stream.connect(path) + return stream + except OSError: + stream.close() + time.sleep(0.1) + return None + + import ctypes + import msvcrt + from ctypes import wintypes + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetNamedPipeServerProcessId.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)] + kernel32.GetNamedPipeServerProcessId.restype = wintypes.BOOL + + def served_by(stream): + server = wintypes.ULONG() + if not kernel32.GetNamedPipeServerProcessId(msvcrt.get_osfhandle(stream.fileno()), ctypes.byref(server)): + return None + return server.value + + # A chat pipe is `tinyclient-` and sixteen hex digits. The invite pipe has a word between, + # and is another program's. + chat_pipes = re.compile(r"tinyclient-[0-9a-f]{16}$") + # Each pipe is opened once to ask who serves it, never twice. + asked = set() + while True: + for name in os.listdir("\\\\.\\pipe\\"): + if not chat_pipes.match(name) or name in asked: + continue + try: + stream = open("\\\\.\\pipe\\" + name, "r+b", buffering=0) + except OSError: + # Busy this instant. It is looked at again on the next pass. + continue + asked.add(name) + if served_by(stream) == pid: + return stream + stream.close() + if time.time() >= deadline: + return None + time.sleep(0.1) + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + chatd_bin, tiny_bin = binaries(APP) + if not os.path.isfile(chatd_bin) or not os.path.isfile(tiny_bin): + step("chatd and tinyclient are in E2E_APP_DIR", False) + return 1 + + data = scratch_dir() + httpd, state = fixture.serve() + port = httpd.server_address[1] + env = child_env(data, port) + chatd = None + chat = None + window = None + try: + chatd = popen( + [chatd_bin], + cwd=data, + env=env, + stdin=subprocess.DEVNULL, + stdout=open(os.path.join(OUT, "chatd.out.log"), "w", encoding="utf-8"), + stderr=open(os.path.join(OUT, "chatd.err.log"), "w", encoding="utf-8"), + ) + answered = wait_until(45, lambda: inbox(tiny_bin, env, data)[0] == 0) + step("chatd answers on the scratch directory", answered and chatd.poll() is None) + if not answered: + return 1 + + if SABOTAGE: + step("sabotage has no Tiny direct to mark unread", beas_direct(data) is None) + # A sabotage run is supposed to fail the real check. The line above records what + # the empty directory showed; the scenario itself did not see the direct. + step(CHECK, False) + return 1 + + # The handshake was held until the first list was stored, so Bea's direct exists; and + # ready went down the socket before anything the driver queues. + ready = state.ready_sent.wait(30) + step("the live socket is up and said ready", ready) + if not ready: + return 1 + + chat = chat_pipe(data, chatd.pid) + step("the driver reaches chatd's pipe, as the window does", chat is not None) + if chat is None: + return 1 + + for frame in fixture.live_direct(state): + state.say(frame) + arrived = wait_until(20, lambda: (beas_direct(data) or (0, "", 0))[2] == len(fixture.POSTS)) + step("three live messages from Bea are stored, the oldest with the id that sorts last", arrived) + if not arrived: + return 1 + + # The person read the chat: what the window asks for once the newest message is on screen. + read = ask(chat, {"op": "mark_read", "conversation": BEA, "message_id": ""}) + cleared = wait_until(10, lambda: badge_of(inbox(tiny_bin, env, data)[1], "Bea") == "") + step("reading the chat clears its badge", read == {"op": "ok"} and cleared) + if read != {"op": "ok"} or not cleared: + return 1 + + # "Mark unread from here" on the middle message, the first that counts as unread again. + marked = ask(chat, {"op": "mark_unread", "conversation": BEA, "message_id": fixture.MIDDLE}) + text = inbox(tiny_bin, env, data)[1] + shown = badge_of(text, "Bea") + marker = (beas_direct(data) or (None, None, 0))[1] + right = marked == {"op": "ok"} and shown == UNREAD_AFTER_MARK and marker == fixture.FIRST + detail = CHECK + if not right: + said = marked.get("op") if isinstance(marked, dict) else marked + detail += " (Bea shows %s, the marker is %r, chatd said %s)" % (shown, marker, said) + step(detail, right) + if not right: + with open(os.path.join(OUT, "inbox.txt"), "w", encoding="utf-8") as handle: + handle.write(text) + return 1 + + if not NO_WINDOW: + window = popen([tiny_bin], cwd=data, env=env, stdin=subprocess.DEVNULL, creationflags=0) + opened = wait_until(20, lambda: window.poll() is None) + step("window stays open", opened) + if opened: + time.sleep(2.0) + shown = badge_of(inbox(tiny_bin, env, data)[1], "Bea") + marker = (beas_direct(data) or (None, None, 0))[1] + step( + "the badge and the marker are still there after the window's own refresh", + shown == UNREAD_AFTER_MARK and marker == fixture.FIRST, + ) + finally: + if chat is not None: + chat.close() + stop(window) + stop(chatd) + fixture.stop(httpd, state) + with open(os.path.join(OUT, "fixture.log"), "w", encoding="utf-8") as handle: + handle.write("\n".join(state.log) + "\n") + return 1 if FAILED else 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except Exception as error: + step("driver: %s" % error, False) + print("driver: %s" % error, file=sys.stderr) + sys.exit(1) diff --git a/e2e/scenarios/tiny-mark-unread-order/drive.windows.ps1 b/e2e/scenarios/tiny-mark-unread-order/drive.windows.ps1 new file mode 100644 index 00000000..bc2537b8 --- /dev/null +++ b/e2e/scenarios/tiny-mark-unread-order/drive.windows.ps1 @@ -0,0 +1,18 @@ +# tiny-mark-unread-order on Windows. The lab runs this in the console session it is already filming. +# Python is the standard-library fixture and the driver; chatd and tinyclient come from E2E_APP_DIR. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/tiny-mark-unread-order/fixture.py b/e2e/scenarios/tiny-mark-unread-order/fixture.py new file mode 100644 index 00000000..55cefb19 --- /dev/null +++ b/e2e/scenarios/tiny-mark-unread-order/fixture.py @@ -0,0 +1,449 @@ +#!/usr/bin/env python3 +"""A Tiny server small enough to show where "Mark unread from here" lands. + +Tiny message ids are UUIDs, so their text is no clock. Once the account's lists are published and +the live socket said ready, the driver has this server send three messages down that socket, the +way Bea's posts arrive: oldest first, a second apart, with ids whose text sorts the other way +round (the first message sorts last, the one in the middle sorts first). The person reads the +chat and marks the middle message unread. chatd must count that message and the newer one, and +put the read marker on the first. + +The lists are the shape the server really sends: a channel and a direct, each with a last +message and no read cursor. The handshake is held until the first list has been applied, so +the live messages only ever come after ready. + +Standard library only. `python fixture.py --self-test` checks the lists and the three frames +without chatd. +""" + +import base64 +import hashlib +import json +import socket +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlsplit + +TOKEN = "fixture-token" +ME = "11111111-1111-4111-8111-111111111111" +BEA = "22222222-2222-4222-8222-222222222222" +GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" +DIRECT = "direct-1" +# The three messages Bea sends, oldest first. Time runs one way and their text the other. +FIRST = "ffffffff-ffff-4fff-8fff-ffffffffffff" +MIDDLE = "00000000-0000-4000-8000-000000000000" +LAST = "55555555-5555-4555-8555-555555555555" +POSTS = ((FIRST, "morning Ada"), (MIDDLE, "lunch at one?"), (LAST, "ping")) +# How long the handshake waits for the first list, inside the client's 10s connect limit. +HANDSHAKE_WAIT = 8.0 +# After the first list's last HTTP response, before ready: long enough for that publish to apply. +APPLY_PAUSE = 1.0 + +STATE = None + + +def stamp(unix): + """A server time: `2026-01-02T03:04:05Z`, whole seconds.""" + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(unix)) + + +class State: + def __init__(self): + self.lock = threading.Lock() + self.channels = 0 + self.directs = 0 + self.rooms = 0 + self.created_at = int(time.time()) + self.created = stamp(self.created_at) + self.stop = threading.Event() + # Set once ready is on the wire. Everything the driver queues goes after it. + self.ready_sent = threading.Event() + self.log = [] + # Frames the driver asked for, waiting for the live socket's next look. + self.outbox = [] + + def bump(self, kind): + with self.lock: + setattr(self, kind, getattr(self, kind) + 1) + return getattr(self, kind) + + def counts(self): + with self.lock: + return self.channels, self.directs, self.rooms + + def note(self, line): + with self.lock: + self.log.append(line) + + def say(self, frame): + """Queues one frame for the live socket, as a server event.""" + with self.lock: + self.outbox.append(frame) + + def unsaid(self): + """Everything queued, taken off the queue.""" + with self.lock: + frames, self.outbox = self.outbox, [] + return frames + + +def message(message_id): + """A direct's last message as the list names it: one from before this run.""" + return { + "id": message_id, + "author_id": BEA, + "body": "did the build finish?", + "created_at": STATE.created, + } + + +def lists(): + """The channel has no cursor, which is what the server sends. So does the direct: nothing + is unread until the live messages arrive.""" + channels = { + "channels": [{ + "id": "night-watch", + "name": "Night Watch", + "topic": "The late shift", + "position": 1, + "unread": 0, + "last_message": message("00000000-0000-4000-8000-000000000001"), + }] + } + directs = { + "directs": [{ + "id": DIRECT, + "peer": {"user_id": BEA, "display_name": "Bea"}, + "unread": 0, + "last_message": message("00000000-0000-4000-8000-000000000002"), + }] + } + return channels, directs + + +def live_direct(state): + """The three `message.created` frames, oldest first, the way a current server says them: a + durable `seq` each, the post's own `seq`, and a stamp a second apart. Every stamp is later + than the lists'.""" + base = max(int(time.time()) - (len(POSTS) - 1), state.created_at + 1) + return [ + { + "type": "message.created", + "seq": 2 + at, + "conversation_id": DIRECT, + "message": { + "id": post, + "author_id": BEA, + "body": body, + "seq": 1 + at, + "created_at": stamp(base + at), + }, + } + for at, (post, body) in enumerate(POSTS) + ] + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): + STATE.note("%s %s" % (self.command, self.path)) + + def _json(self, status, body): + raw = json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(raw) + + def _authorized(self): + if self.headers.get("Authorization") == "Bearer " + TOKEN: + return True + self._json(401, {"error": "unauthorized"}) + return False + + def do_GET(self): + path = urlsplit(self.path).path + # A fresh ready asks /health with no bearer, only to see if call audio is up. + if path == "/health": + self._json(200, {"ok": True, "media": "off"}) + return + if not self._authorized(): + return + if path == "/v1/live": + self._live() + return + if path == "/v1/capabilities": + self._json(200, {"features": []}) + return + if path == "/v1/members": + self._json(200, [ + {"user_id": ME, "display_name": "Ada", "email": "ada@example.com", "role": "member"}, + {"user_id": BEA, "display_name": "Bea", "email": "bea@example.com", "role": "member"}, + ]) + return + if path == "/v1/channels": + STATE.bump("channels") + self._json(200, lists()[0]) + return + if path == "/v1/directs": + STATE.bump("directs") + self._json(200, lists()[1]) + return + if path == "/v1/rooms": + STATE.bump("rooms") + # An empty list, not a wrapped object: chatd reads this body as the array itself. + # 404 would also do; an empty 200 keeps the publish on the path that stores unreads. + self._json(200, []) + return + self._json(404, {"error": "not_found"}) + + def do_POST(self): + if not self._authorized(): + return + if urlsplit(self.path).path == "/v1/conversations/%s/read" % DIRECT: + # The read receipt chatd posts. The server notes it and has nothing to say back. + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + self.send_response(204) + self.send_header("Connection", "close") + self.end_headers() + return + self._json(404, {"error": "not_found"}) + + do_PUT = do_DELETE = do_PATCH = do_POST + + def _live(self): + # Stay in the handshake until the account's first publish can have been stored, so the + # direct exists when the live messages come. ready goes out first; whatever the driver + # queues follows it. + deadline = time.time() + HANDSHAKE_WAIT + while time.time() < deadline and not STATE.stop.is_set(): + channels, directs, rooms = STATE.counts() + if channels >= 1 and directs >= 1 and rooms >= 1: + break + time.sleep(0.02) + else: + self._json(503, {"error": "the first list never arrived"}) + return + time.sleep(APPLY_PAUSE) + if STATE.stop.is_set(): + return + key = self.headers.get("Sec-WebSocket-Key", "") + if not key: + self._json(400, {"error": "not a websocket"}) + return + accept = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode() + self.send_response(101, "Switching Protocols") + self.send_header("Upgrade", "websocket") + self.send_header("Connection", "Upgrade") + self.send_header("Sec-WebSocket-Accept", accept) + self.end_headers() + ready = json.dumps({ + "type": "ready", + "seq": 1, + "me": {"role": "member"}, + "online": [], + "calls": [], + }).encode() + self.wfile.write(_frame(ready)) + self.wfile.flush() + STATE.ready_sent.set() + self._frames(self.connection) + self.close_connection = True + + def _frames(self, sock): + sock.settimeout(0.5) + try: + while not STATE.stop.is_set(): + # What the driver asked the server to say goes out first. + for frame in STATE.unsaid(): + sock.sendall(_frame(json.dumps(frame).encode())) + try: + header = _exact(sock, 2) + except socket.timeout: + continue + if not header: + return + opcode = header[0] & 0x0F + length = header[1] & 0x7F + if length == 126: + length = int.from_bytes(_exact(sock, 2), "big") + elif length == 127: + length = int.from_bytes(_exact(sock, 8), "big") + mask = _exact(sock, 4) if header[1] & 0x80 else b"" + payload = _exact(sock, length) if length else b"" + if payload is None: + return + if mask: + payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) + if opcode == 0x8: + sock.sendall(_frame(payload, 0x8)) + return + if opcode == 0x9: + sock.sendall(_frame(payload, 0xA)) + continue + if opcode != 0x1: + continue + try: + kind = json.loads(payload.decode()).get("type") + except (UnicodeDecodeError, json.JSONDecodeError, AttributeError): + continue + if kind == "ping": + sock.sendall(_frame(json.dumps({"type": "pong"}).encode())) + except OSError: + return + + +def _frame(payload, opcode=0x1): + n = len(payload) + if n < 126: + head = bytes([0x80 | opcode, n]) + elif n < 65536: + head = bytes([0x80 | opcode, 126]) + n.to_bytes(2, "big") + else: + head = bytes([0x80 | opcode, 127]) + n.to_bytes(8, "big") + return head + payload + + +def _exact(sock, n): + buf = b"" + while len(buf) < n: + chunk = sock.recv(n - len(buf)) + if not chunk: + return None + buf += chunk + return buf + + +def serve(): + """Listen on 127.0.0.1 and a free port. Returns (httpd, state).""" + global STATE + STATE = State() + httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + httpd.daemon_threads = True + threading.Thread(target=httpd.serve_forever, name="tiny-fixture", daemon=True).start() + return httpd, STATE + + +def stop(httpd, state): + state.stop.set() + httpd.shutdown() + httpd.server_close() + + +def _unframe(held): + """The first frame the server wrote, as (payload, what was read past it), or None while it + is not all there yet.""" + if len(held) < 2: + return None + length, at = held[1] & 0x7F, 2 + if length == 126: + if len(held) < 4: + return None + length, at = int.from_bytes(held[2:4], "big"), 4 + elif length == 127: + if len(held) < 10: + return None + length, at = int.from_bytes(held[2:10], "big"), 10 + if len(held) < at + length: + return None + return held[at:at + length], held[at + length:] + + +def _self_test(): + import urllib.request + + httpd, state = serve() + port = httpd.server_address[1] + base = "http://127.0.0.1:%d" % port + + def get(path): + req = urllib.request.Request(base + path, headers={"Authorization": "Bearer " + TOKEN}) + with urllib.request.urlopen(req) as res: + return res.status, json.loads(res.read().decode()) + + try: + status, body = get("/v1/channels") + assert status == 200 and body["channels"][0]["unread"] == 0, body + assert "last_read" not in body["channels"][0] + _, directs = get("/v1/directs") + assert (directs["directs"][0]["id"], directs["directs"][0]["unread"]) == (DIRECT, 0), directs + assert "last_read" not in directs["directs"][0] + status, rooms = get("/v1/rooms") + assert status == 200 and rooms == [] + # The read receipt chatd posts is taken, and nothing is said back. + receipt = urllib.request.Request( + base + "/v1/conversations/%s/read" % DIRECT, + data=b'{"message_id": "x"}', + headers={"Authorization": "Bearer " + TOKEN}, + method="POST", + ) + with urllib.request.urlopen(receipt) as res: + assert res.status == 204 and res.read() == b"", res.status + # ready is withheld until the first list is done. + sock = socket.create_connection(("127.0.0.1", port), 5) + key = base64.b64encode(b"fixture-self-test!").decode() + sock.sendall(( + "GET /v1/live HTTP/1.1\r\n" + "Host: 127.0.0.1:%d\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: %s\r\n" + "Sec-WebSocket-Version: 13\r\n" + "Authorization: Bearer %s\r\n" + "\r\n" % (port, key, TOKEN) + ).encode()) + sock.settimeout(5) + buffered = b"" + while b"\r\n\r\n" not in buffered: + buffered += sock.recv(1) + + def take(held): + """The next frame the server wrote: its payload, and what was read past it.""" + while True: + found = _unframe(held) + if found: + return found + held += sock.recv(4096) + + head, held = buffered.split(b"\r\n\r\n", 1) + assert head.startswith(b"HTTP/1.1 101 "), head + payload, held = take(held) + assert json.loads(payload.decode())["type"] == "ready", payload + assert state.ready_sent.wait(5), "the driver is told once ready is on the wire" + + # The live messages come down the socket oldest first, each after the ready's own + # sequence, and their ids sort the other way round from their time. + frames = live_direct(state) + assert [frame["message"]["id"] for frame in frames] == [FIRST, MIDDLE, LAST], frames + assert [frame["seq"] for frame in frames] == [2, 3, 4], frames + stamps = [frame["message"]["created_at"] for frame in frames] + assert stamps == sorted(stamps) and min(stamps) > state.created, stamps + assert MIDDLE < LAST < FIRST, "the ids sort the other way from their time" + for frame in frames: + state.say(frame) + heard = [] + for _ in frames: + payload, held = take(held) + heard.append(json.loads(payload.decode())["message"]["id"]) + assert heard == [FIRST, MIDDLE, LAST], heard + _, body = get("/v1/channels") + assert body["channels"][0]["last_message"]["created_at"] == state.created + _, directs = get("/v1/directs") + assert directs["directs"][0]["unread"] == 0 + sock.close() + finally: + stop(httpd, state) + print("fixture self-test passed") + + +if __name__ == "__main__": + if "--self-test" in sys.argv: + _self_test() + else: + print("run drive.py; this file is the server it starts", file=sys.stderr) + sys.exit(2) diff --git a/e2e/scenarios/tiny-mark-unread-order/scenario.json b/e2e/scenarios/tiny-mark-unread-order/scenario.json new file mode 100644 index 00000000..1c704102 --- /dev/null +++ b/e2e/scenarios/tiny-mark-unread-order/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "tiny-mark-unread-order", + "title": "Mark unread from a Tiny message counts by time and puts the marker on the message above it", + "platforms": ["windows", "linux", "macos"], + "not_applicable": { + "android": "The phone proof build uses demo chatd and never opens a Tiny server session, so no Tiny direct can arrive there to be marked unread.", + "ios": "The phone proof build uses demo chatd and never opens a Tiny server session, so no Tiny direct can arrive there to be marked unread." + }, + "needs": [], + "release": false, + "max_still_seconds": 45 +} From 68938ee9b2d5abde8f4bf743629cedb3bf431e78 Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 15:46:42 +0100 Subject: [PATCH 8/8] Installed Signal sticker packs are read again from the storage service --- crates/chatd/src/adapters/signal.rs | 116 +++++--- crates/chatd/src/adapters/signal/real.rs | 265 +++++++++++++++++- crates/chatd/src/adapters/signal/wire.rs | 17 ++ crates/chatd/tests/signal.rs | 59 ++++ .../drive.linux.sh | 9 + .../drive.macos.sh | 9 + .../drive.py | 222 +++++++++++++++ .../drive.windows.ps1 | 17 ++ .../scenario.json | 12 + 9 files changed, 673 insertions(+), 53 deletions(-) create mode 100644 e2e/scenarios/signal-sticker-packs-from-storage/drive.linux.sh create mode 100644 e2e/scenarios/signal-sticker-packs-from-storage/drive.macos.sh create mode 100644 e2e/scenarios/signal-sticker-packs-from-storage/drive.py create mode 100644 e2e/scenarios/signal-sticker-packs-from-storage/drive.windows.ps1 create mode 100644 e2e/scenarios/signal-sticker-packs-from-storage/scenario.json diff --git a/crates/chatd/src/adapters/signal.rs b/crates/chatd/src/adapters/signal.rs index 02671b66..ab02617c 100644 --- a/crates/chatd/src/adapters/signal.rs +++ b/crates/chatd/src/adapters/signal.rs @@ -1517,6 +1517,16 @@ impl Account { fn live(&self) -> MutexGuard<'_, Live> { self.live.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } + + /// The picker's sticker packs, read from this account's file the first time they are asked for. + fn sticker_packs(&self) -> Vec { + let mut live = self.live(); + if !live.stickers_loaded { + live.sticker_packs = read_sticker_packs(&live.stickers_path); + live.stickers_loaded = true; + } + live.sticker_packs.clone() + } } pub fn start(ctx: Context, session: &str, inbox: Receiver) -> Result<(), String> { @@ -2671,43 +2681,7 @@ fn apply(account: &Account, event: Event) { write_sticker_packs(&live.stickers_path, &live.sticker_packs); account.ctx.hub.catalogs.forget_matching(|(acct, kind, ..)| *acct == account.ctx.account && *kind == CatalogKind::Stickers); } - Event::StickerPackOp { pack_id, pack_key, install } => { - if install { - let mut pack = account - .wire - .preview_sticker_pack(&pack_id, &pack_key) - .unwrap_or_else(|_| wire::StickerPackInfo { - id: pack_id.clone(), - key: pack_key.clone(), - title: "Sticker pack".to_owned(), - author: String::new(), - cover_id: Some(0), - stickers: Vec::new(), - installed: true, - }); - pack.installed = true; - let mut live = account.live(); - if !live.stickers_loaded { - live.sticker_packs = read_sticker_packs(&live.stickers_path); - live.stickers_loaded = true; - } - if let Some(existing) = live.sticker_packs.iter_mut().find(|p| p.id == pack.id) { - *existing = pack; - } else if live.sticker_packs.len() < 128 { - live.sticker_packs.push(pack); - } - write_sticker_packs(&live.stickers_path, &live.sticker_packs); - } else { - let mut live = account.live(); - if !live.stickers_loaded { - live.sticker_packs = read_sticker_packs(&live.stickers_path); - live.stickers_loaded = true; - } - live.sticker_packs.retain(|p| p.id != pack_id); - write_sticker_packs(&live.stickers_path, &live.sticker_packs); - } - account.ctx.hub.catalogs.forget_matching(|(acct, kind, ..)| *acct == account.ctx.account && *kind == CatalogKind::Stickers); - } + Event::StickerPackOp { pack_id, pack_key, install } => apply_sticker_pack_op(account, &pack_id, &pack_key, install), Event::Story(story) => apply_story(account, story), Event::StoryReaction { by, story_author, story_sent, emoji, removed, .. } => { if account.live().stories_disabled { @@ -2980,6 +2954,65 @@ fn apply_storage_sync(account: &Account, snapshot: wire::StorageSnapshot) { if disabled_stories { let _ = ctx.forget_conversation(STORIES_CONVERSATION); } + apply_storage_sticker_packs(account, snapshot.sticker_packs); +} + +/// Puts a pack another device installed into the picker's list, or takes a removed one out. The +/// pack's manifest is fetched as for any install, so the list holds its title and stickers. +fn apply_sticker_pack_op(account: &Account, pack_id: &str, pack_key: &str, install: bool) { + if install { + // Asked of the wire before the list is touched, so no lock is held on the way to Signal. + let mut pack = account + .wire + .preview_sticker_pack(pack_id, pack_key) + .unwrap_or_else(|_| wire::StickerPackInfo { + id: pack_id.to_owned(), + key: pack_key.to_owned(), + title: "Sticker pack".to_owned(), + author: String::new(), + cover_id: Some(0), + stickers: Vec::new(), + installed: true, + }); + pack.installed = true; + let mut live = account.live(); + if !live.stickers_loaded { + live.sticker_packs = read_sticker_packs(&live.stickers_path); + live.stickers_loaded = true; + } + if let Some(existing) = live.sticker_packs.iter_mut().find(|p| p.id == pack.id) { + *existing = pack; + } else if live.sticker_packs.len() < 128 { + live.sticker_packs.push(pack); + } + write_sticker_packs(&live.stickers_path, &live.sticker_packs); + } else { + let mut live = account.live(); + if !live.stickers_loaded { + live.sticker_packs = read_sticker_packs(&live.stickers_path); + live.stickers_loaded = true; + } + live.sticker_packs.retain(|p| p.id != pack_id); + write_sticker_packs(&live.stickers_path, &live.sticker_packs); + } + account.ctx.hub.catalogs.forget_matching(|(acct, kind, ..)| *acct == account.ctx.account && *kind == CatalogKind::Stickers); +} + +/// Applies the sticker pack records of a Storage Service snapshot, which is read on every storage +/// change: a pack this device already holds, stickers and all, is not fetched from Signal again, +/// and a removal is always carried out. +fn apply_storage_sticker_packs(account: &Account, packs: Vec) { + let held: Vec = account + .sticker_packs() + .into_iter() + .filter(|pack| pack.installed && !pack.stickers.is_empty()) + .map(|pack| pack.id) + .collect(); + for pack in packs { + if pack.removed || !held.contains(&pack.id) { + apply_sticker_pack_op(account, &pack.id, &pack.key, !pack.removed); + } + } } fn ensure_stories_row(account: &Account) { @@ -5830,14 +5863,7 @@ fn pin_message(account: &Account, conversation_id: &str, message_id: &str, pinne fn catalog(account: &Account, kind: CatalogKind, query: &str, cursor: Option<&str>) -> Result { if kind == CatalogKind::Stickers { let q = query.trim().to_ascii_lowercase(); - let packs = { - let mut live = account.live(); - if !live.stickers_loaded { - live.sticker_packs = read_sticker_packs(&live.stickers_path); - live.stickers_loaded = true; - } - live.sticker_packs.clone() - }; + let packs = account.sticker_packs(); let mut items = Vec::new(); let mut media = Vec::new(); { diff --git a/crates/chatd/src/adapters/signal/real.rs b/crates/chatd/src/adapters/signal/real.rs index ee7375dc..3040f9ce 100644 --- a/crates/chatd/src/adapters/signal/real.rs +++ b/crates/chatd/src/adapters/signal/real.rs @@ -14,7 +14,8 @@ use super::wire::{ GifEntry, GroupAccess, GroupCallCredentials, GroupCallInfo, GroupCallSignal, GroupEdit, GroupInfo, GroupMember, GroupMembers, HangupKind, HistoryTransfer, IdentityState, InviteLinkMode, LinkPreview, Linked, Linker, MessageRequestAction, OwnCard, Peer, PersonProfile, Pointer, Quote, QuotedAttachment, SafetyNumber, Sticker, - StickerEntry, StickerPackInfo, StorageAccount, StorageContact, StorageGroup, StorageSnapshot, StoryContext, + StickerEntry, StickerPackInfo, StorageAccount, StorageContact, StorageGroup, StorageSnapshot, StorageStickerPack, + StoryContext, StoryDistributionList, StoryMessageData, StoryText, Text, TransferOutcome, TransferProgress, TurnServer, Wire, }; use super::{group_delta, GroupRevisions, GroupSnap, MemberSnap, Saved}; @@ -39,8 +40,8 @@ use presage::proto::{ body_range::{AssociatedValue, Style as RangeStyle}, call_message, chat_folder_record, contact_record, conversation_identifier, data_message, receipt_message, recipient, storage_record, sync_message, typing_message, verified, AddressableMessage, BodyRange, CallMessage, - ConversationIdentifier, DataMessage, EditMessage, GroupContextV2, ReceiptMessage, SyncMessage, TypingMessage, - Verified, + ConversationIdentifier, DataMessage, EditMessage, GroupContextV2, ReadOperation, ReceiptMessage, StorageItem, + StorageItems, SyncMessage, TypingMessage, Verified, }; use presage::store::{ContentsStore, StateStore}; use presage::Manager; @@ -1047,23 +1048,30 @@ impl Session { None } - /// Reads Signal's encrypted Storage Service manifest and items (contact, group, account, folder records) - /// in read-only mode to seed contacts, groups, pins, archive, mutes, nicknames, notes, and settings. + /// Reads Signal's encrypted Storage Service manifest and items (contact, group, account, folder and + /// sticker pack records) in read-only mode to seed contacts, groups, pins, archive, mutes, nicknames, + /// notes, settings, and the sticker packs the other devices installed. async fn sync_storage(&mut self) { let Some(storage_key) = self.storage_key().await else { return; }; + let storage_key_bytes = storage_key.inner; let Ok(credentials) = self.credentials() else { return; }; - let push = PushService::new(SignalServers::Production, Some(credentials), "tinyclient"); + let push = PushService::new(SignalServers::Production, Some(credentials.clone()), "tinyclient"); let Ok(storage) = StorageService::new(push, storage_key).await else { return; }; let Ok(manifest) = storage.manifest().await else { return; }; - let keys: Vec> = manifest.identifiers.into_iter().map(|id| id.raw).collect(); + // A sticker pack record is not one of the library's record types, so its identifiers are + // read apart from the rest. + let (packs, others): (Vec<_>, Vec<_>) = + manifest.identifiers.into_iter().partition(|id| id.r#type == STICKER_PACK_RECORD_TYPE); + let pack_ids: Vec> = packs.into_iter().map(|id| id.raw).collect(); + let keys: Vec> = others.into_iter().map(|id| id.raw).collect(); if keys.is_empty() { return; } @@ -1071,6 +1079,14 @@ impl Session { let Ok(records) = storage.read_items(keys, ikm).await else { return; }; + let mut sticker_packs = Vec::new(); + if !pack_ids.is_empty() { + // Read sealed, as the server sends them, and opened here (`sticker_packs_in_items`). + let reader = PushService::new(SignalServers::Production, Some(credentials), "tinyclient"); + if let Ok(items) = sealed_storage_items(&reader, pack_ids).await { + sticker_packs = sticker_packs_in_items(&storage_key_bytes, &items, ikm); + } + } self.blocked_known = true; let join_name = |given: &str, family: &str| -> String { [given.trim(), family.trim()] @@ -1272,12 +1288,18 @@ impl Session { _ => {} } } - if !contacts.is_empty() || !groups.is_empty() || account_record.is_some() || !distribution_lists.is_empty() { + if !contacts.is_empty() + || !groups.is_empty() + || account_record.is_some() + || !distribution_lists.is_empty() + || !sticker_packs.is_empty() + { self.tell(Event::StorageSync(StorageSnapshot { contacts, groups, account: account_record, distribution_lists, + sticker_packs, })); } if !folders.is_empty() { @@ -4104,6 +4126,144 @@ async fn fetch_picture( } } +/// `ManifestRecord.Identifier.Type.STICKER_PACK`: an installed sticker pack in the Storage Service. +const STICKER_PACK_RECORD_TYPE: i32 = 6; + +/// The most this adapter reads of the sealed items behind the sticker pack records in one answer. +/// A record is under 200 bytes, so this holds every pack an account could install and stops +/// anything larger. +const MAX_STICKER_RECORD_BYTES: usize = 256 * 1024; + +/// An `InstalledStickerPackRecord` of the Storage Service (`StorageService.proto`). The pinned +/// libsignal-service predates it: its `StorageRecord` has no sticker pack field, so its reader +/// decodes each item into the record types it knows and drops this one. +#[derive(prost::Message)] +struct StickerPackRecord { + /// 16 bytes. + #[prost(bytes = "vec", tag = "1")] + pack_id: Vec, + /// 32 bytes; unset on a record that only says the pack was removed. + #[prost(bytes = "vec", tag = "2")] + pack_key: Vec, + /// Where the other devices show the pack in their picker. + #[prost(uint32, tag = "3")] + position: u32, + /// Non-zero when another device removed the pack. + #[prost(uint64, tag = "4")] + deleted_at_timestamp: u64, +} + +/// The key of one Storage Service item, named by its identifier in the manifest: from the +/// manifest's key (`record_ikm`) on accounts since 2024-08, and before that from the account's +/// storage key. libsignal-service keeps its own a private function. `None` when it cannot be made. +fn storage_item_key(storage_key: &[u8; 32], raw_id: &[u8], record_ikm: Option<&[u8]>) -> Option<[u8; 32]> { + use hmac::{Hmac, Mac}; + + const ITEM_KEY_INFO_PREFIX: &[u8] = b"20240801_SIGNAL_STORAGE_SERVICE_ITEM_"; + let mut key = [0u8; 32]; + match record_ikm { + Some(ikm) if !ikm.is_empty() => { + hkdf::Hkdf::::new(None, ikm).expand(&[ITEM_KEY_INFO_PREFIX, raw_id].concat(), &mut key).ok()?; + } + _ => { + let mut mac = as Mac>::new_from_slice(storage_key).ok()?; + mac.update(b"Item_"); + mac.update(base64::Engine::encode(&base64::engine::general_purpose::STANDARD, raw_id).as_bytes()); + key = mac.finalize().into_bytes().into(); + } + } + Some(key) +} + +/// Opens one sealed Storage Service item to the bytes before decoding, which is where the +/// library's reader loses a sticker pack. `None` when the item does not open. +fn open_storage_item(storage_key: &[u8; 32], item: &StorageItem, record_ikm: Option<&[u8]>) -> Option> { + use aes_gcm::aead::Aead; + use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; + + let key = storage_item_key(storage_key, &item.key, record_ikm)?; + // The item is `iv (12 bytes) || ciphertext || tag` under AES-256-GCM. + let (iv, sealed) = item.value.split_at_checked(12)?; + Aes256Gcm::new(Key::::from_slice(&key[..])).decrypt(Nonce::from_slice(iv), sealed).ok() +} + +/// Reads the sealed Storage Service items behind `ids` as the server sends them, without decoding +/// them: the library's own reader answers only the records it has decoded. An answer larger than +/// [`MAX_STICKER_RECORD_BYTES`] is refused. +async fn sealed_storage_items(push: &PushService, ids: Vec>) -> Result, Fault> { + use presage::libsignal_service::configuration::Endpoint; + use presage::libsignal_service::push_service::{HttpAuth, HttpAuthOverride}; + + // The Storage Service takes a login of its own, fetched with the account's. + #[derive(serde::Deserialize)] + struct StorageAuth { + #[serde(default)] + username: String, + #[serde(default)] + password: String, + } + let refused = |err: reqwest::Error| Fault::Net(err.to_string()); + let resp = push + .request(reqwest::Method::GET, Endpoint::service("/v1/storage/auth"), HttpAuthOverride::NoOverride) + .map_err(|err| Fault::Net(err.to_string()))? + .send() + .await + .map_err(refused)?; + if !resp.status().is_success() { + return Err(Fault::Net(format!("storage auth: {}", resp.status()))); + } + let auth: StorageAuth = resp.json().await.map_err(refused)?; + let resp = push + .request( + reqwest::Method::PUT, + Endpoint::storage("/v1/storage/read"), + HttpAuthOverride::Identified(HttpAuth { username: auth.username, password: auth.password }), + ) + .map_err(|err| Fault::Net(err.to_string()))? + .header("Content-Type", "application/x-protobuf") + .body(prost::Message::encode_to_vec(&ReadOperation { read_key: ids })) + .send() + .await + .map_err(refused)?; + if !resp.status().is_success() { + return Err(Fault::Net(format!("storage read: {}", resp.status()))); + } + let mut bytes = Vec::new(); + let mut stream = resp.bytes_stream(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(refused)?; + if bytes.len() + chunk.len() > MAX_STICKER_RECORD_BYTES { + return Err(Fault::Refused("Signal's sticker pack records are larger than expected.".to_owned())); + } + bytes.extend_from_slice(&chunk); + } + let items: StorageItems = prost::Message::decode(bytes.as_slice()).map_err(|err| Fault::Net(err.to_string()))?; + Ok(items.items) +} + +/// The sticker pack records among `items`, in the order the other devices show them: by +/// `position`, then by pack id. A record that does not open, or that names no pack this client +/// can fetch, is left out. That is the rule Signal's own apps keep: an id of 16 bytes, and a key +/// of 32 unless the pack was removed. +fn sticker_packs_in_items(storage_key: &[u8; 32], items: &[StorageItem], record_ikm: Option<&[u8]>) -> Vec { + let mut packs: Vec<(u32, StorageStickerPack)> = items + .iter() + .filter_map(|item| { + let opened = open_storage_item(storage_key, item, record_ikm)?; + let record: StickerPackRecord = prost::Message::decode(opened.as_slice()).ok()?; + let removed = record.deleted_at_timestamp != 0; + if record.pack_id.len() != 16 || (!removed && record.pack_key.len() != 32) { + return None; + } + // A removal keeps no key, whatever it was sealed with. + let key = if removed { String::new() } else { hex(&record.pack_key) }; + Some((record.position, StorageStickerPack { id: hex(&record.pack_id), key, removed })) + }) + .collect(); + packs.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.id.cmp(&b.1.id))); + packs.into_iter().map(|(_, pack)| pack).collect() +} + async fn preview_sticker_pack_with( vault: &Vault, pack_id: &str, @@ -4963,4 +5123,93 @@ mod tests { drop(rx); assert!(reply.is_closed()); } + + /// Seals `plain` the way the Storage Service keeps an item: `iv (12 bytes) || ciphertext || tag`. + fn sealed(key: &[u8; 32], plain: &[u8]) -> Vec { + use aes_gcm::aead::{Aead, KeyInit}; + use aes_gcm::{Aes256Gcm, Key, Nonce}; + + let iv = [7u8; 12]; + let ciphertext = Aes256Gcm::new(Key::::from_slice(&key[..])) + .encrypt(Nonce::from_slice(&iv[..]), plain) + .expect("AES-256-GCM seals"); + let mut value = iv.to_vec(); + value.extend_from_slice(&ciphertext); + value + } + + #[test] + fn a_storage_item_opens_as_the_library_sealed_it() { + use presage::proto::{storage_record, GroupV2Record, StorageRecord}; + + // The library derives an item's key itself and keeps that private. An item it seals has to + // open here to the same record, on an account with a manifest key and on an older one. + let storage_key = StorageServiceKey { inner: [9u8; 32] }; + let ikm = [4u8; 32]; + let record = StorageRecord { + record: Some(storage_record::Record::GroupV2(GroupV2Record { master_key: vec![5; 32], ..Default::default() })), + }; + for ikm in [None, Some(ikm.as_slice())] { + let item = StorageService::encrypt_item(&storage_key, vec![0xab; 16], &record, ikm); + let opened = open_storage_item(&storage_key.inner, &item, ikm).expect("the sealed item opens"); + let decoded: StorageRecord = ::decode(opened.as_slice()).unwrap(); + assert!(decoded == record, "another record came out"); + + // Another item's identifier does not open it. On an account with no manifest key the + // item is keyed by the account's storage key, so another account's does not open it. + let mut renamed = item.clone(); + renamed.key = vec![0xac; 16]; + assert!(open_storage_item(&storage_key.inner, &renamed, ikm).is_none()); + if ikm.is_none() { + let stranger = StorageServiceKey { inner: [8u8; 32] }; + assert!(open_storage_item(&stranger.inner, &item, ikm).is_none()); + } + } + // An item shorter than its iv is not opened. + let item = StorageService::encrypt_item(&storage_key, vec![0xab; 16], &record, None); + for cut in 0..12 { + let mut short = item.clone(); + short.value.truncate(cut); + assert!(open_storage_item(&storage_key.inner, &short, None).is_none()); + } + } + + #[test] + fn sticker_pack_records_are_read_in_the_pickers_order_and_bad_ones_are_left_out() { + let record = |pack_id: Vec, pack_key: Vec, position: u32, deleted_at_timestamp: u64| StickerPackRecord { + pack_id, + pack_key, + position, + deleted_at_timestamp, + }; + let cats = record(vec![1; 16], vec![2; 32], 1, 0); + let dogs = record(vec![3; 16], vec![4; 32], 0, 0); + let removed = record(vec![5; 16], vec![6; 32], 0, 1_700_000_000_000); + let short_id = record(vec![6; 8], vec![4; 32], 0, 0); + let keyless = record(vec![7; 16], Vec::new(), 0, 0); + + // An older account names each item in an HMAC of the storage key. + let storage_key = [9u8; 32]; + let mut items: Vec = [cats, dogs, removed, short_id, keyless] + .iter() + .enumerate() + .map(|(at, record)| { + let raw_id = [6u8, at as u8]; + let key = storage_item_key(&storage_key, &raw_id, None).expect("an item key"); + StorageItem { key: raw_id.to_vec(), value: sealed(&key, &prost::Message::encode_to_vec(record)) } + }) + .collect(); + items.push(StorageItem { key: vec![6, 9], value: vec![1, 2, 3] }); + + // By position, then by id. A removed pack keeps its id and no key. An id of the wrong + // length, a pack with no key and bytes that do not open are left out. + assert_eq!( + sticker_packs_in_items(&storage_key, &items, None), + vec![ + StorageStickerPack { id: hex(&[3; 16]), key: hex(&[4; 32]), removed: false }, + StorageStickerPack { id: hex(&[5; 16]), key: String::new(), removed: true }, + StorageStickerPack { id: hex(&[1; 16]), key: hex(&[2; 32]), removed: false }, + ] + ); + } } diff --git a/crates/chatd/src/adapters/signal/wire.rs b/crates/chatd/src/adapters/signal/wire.rs index ee58267b..e1ff97b9 100644 --- a/crates/chatd/src/adapters/signal/wire.rs +++ b/crates/chatd/src/adapters/signal/wire.rs @@ -500,6 +500,20 @@ pub fn resolve_story_recipients( out } +/// One sticker pack record decrypted from Signal's Storage Service (`InstalledStickerPackRecord`). +/// The record names a pack; its stickers are fetched from Signal's CDN as for any install. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct StorageStickerPack { + /// 16-byte pack id, lowercase hex (32 chars). + pub id: String, + /// 32-byte pack key, lowercase hex (64 chars). Empty on a removal. + #[serde(default)] + pub key: String, + /// Another device removed the pack; the record only says so. + #[serde(default)] + pub removed: bool, +} + /// Full read-only snapshot decrypted from Signal's Storage Service manifest. #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct StorageSnapshot { @@ -511,6 +525,9 @@ pub struct StorageSnapshot { pub account: Option, #[serde(default)] pub distribution_lists: Vec, + /// The installed sticker packs, in the order the other devices show them. + #[serde(default)] + pub sticker_packs: Vec, } /// One Signal chat folder from the storage service (`ChatFolderRecord`). diff --git a/crates/chatd/tests/signal.rs b/crates/chatd/tests/signal.rs index 00d0e765..91a34610 100644 --- a/crates/chatd/tests/signal.rs +++ b/crates/chatd/tests/signal.rs @@ -2283,6 +2283,65 @@ fn storage_service_manifest_seeds_contacts_groups_pins_archive_and_mutes_on_firs }); } +#[test] +fn sticker_packs_the_storage_service_holds_fill_the_picker_and_a_removal_takes_one_out() { + // Both packs were installed on the phone before this device was linked: it never hears the + // sync message that announced them, only what the Storage Service keeps, an id and a key. + let pack_id = "0123456789abcdef0123456789abcdef"; + let pack_key = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let other_id = "fedcba9876543210fedcba9876543210"; + let other_key = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + let installed = |id: &str, key: &str| format!(r#"{{"id":"{id}","key":"{key}"}}"#); + let previews = |world: &World, id: &str| world.calls().iter().filter(|call| **call == format!("sticker-pack-preview {id}")).count(); + let mut world = World::start_with_setup(Some(SESSION), |dir| { + let manifest = format!(r#"{{"sticker_packs":[{},{}]}}"#, installed(pack_id, pack_key), installed(other_id, other_key)); + std::fs::write(dir.join("signal.storage.json"), &manifest).unwrap(); + }); + world.connected(); + + let stickers = |world: &World| -> Vec { + match world.ask(Request::Catalog { + account: account(), + space: None, + kind: protocol::CatalogKind::Stickers, + query: String::new(), + cursor: None, + }) { + Response::Catalog { items, .. } => items, + other => panic!("{other:?}"), + } + }; + // Each pack's manifest is fetched as for any install, so the picker holds the pack's stickers. + let items = world.until("both packs from the storage are in the picker", || { + let items = stickers(&world); + (items.len() == 4).then_some(items) + }); + let mut ids: Vec = items.iter().map(|item| item.id.clone()).collect(); + ids.sort(); + assert_eq!(ids, [format!("{pack_id}:0"), format!("{pack_id}:1"), format!("{other_id}:0"), format!("{other_id}:1")]); + assert!(items.iter().all(|item| item.pack == "Signal Cats"), "{items:?}"); + assert_eq!(previews(&world, pack_id), 1); + assert_eq!(previews(&world, other_id), 1); + + // A pack removed on the phone leaves the picker. The storage is read on every change, so a + // pack this device already holds is not fetched from Signal again. + let updated = format!(r#"{{"sticker_packs":[{{"id":"{pack_id}","removed":true}},{}]}}"#, installed(other_id, other_key)); + world.steer(&format!("storage-manifest {updated}")); + world.until("the removed pack is out of the picker and the other stays", || { + let items = stickers(&world); + (items.len() == 2 && items.iter().all(|item| item.id.starts_with(other_id))).then_some(()) + }); + assert_eq!(previews(&world, other_id), 1, "a held pack was fetched again"); + + // The same after a restart: the held pack is read from this device's list, not fetched anew. + std::fs::write(world.dir.join("signal.storage.json"), &updated).unwrap(); + world.restart(); + world.connected(); + world.until("the held pack is in the picker after the restart", || (!stickers(&world).is_empty()).then_some(())); + assert!(stickers(&world).iter().all(|item| item.id.starts_with(other_id))); + assert_eq!(previews(&world, other_id), 1, "the held pack was fetched again after the restart"); +} + #[test] fn safety_number_change_writes_system_rows_and_blocks_verified_send_until_approved() { let world = World::linked(); diff --git a/e2e/scenarios/signal-sticker-packs-from-storage/drive.linux.sh b/e2e/scenarios/signal-sticker-packs-from-storage/drive.linux.sh new file mode 100644 index 00000000..07137b52 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-sticker-packs-from-storage on Linux. The lab runs this with bash while ffmpeg films the display. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/signal-sticker-packs-from-storage/drive.macos.sh b/e2e/scenarios/signal-sticker-packs-from-storage/drive.macos.sh new file mode 100644 index 00000000..5fb841f5 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-sticker-packs-from-storage on macOS. The lab runs this with bash while the display is filmed. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/signal-sticker-packs-from-storage/drive.py b/e2e/scenarios/signal-sticker-packs-from-storage/drive.py new file mode 100644 index 00000000..028941a2 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""A sticker pack the phone keeps in Signal's storage service is in the picker of a freshly linked +device, and a removal there takes it out. + +Starts this build's chatd with the scripted Signal wire (TINYCLIENT_SIGNAL_FAKE) on an isolated +TINYCLIENT_DIR, steers it over its control file the way tests/signal.rs does, and speaks chatd's +real socket. The storage file the scripted wire reads as the account's storage service names one +pack this device never heard a sync message about; the picker's Stickers catalog must list that +pack's two stickers, fetched as for any install. A later storage read that marks the pack removed +must empty the catalog. A build from before the fix lists no sticker at all, because it does not +read sticker pack records from the storage service, so this driver fails there. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR. +""" + +import json +import os +import socket +import struct +import subprocess +import sys +import time + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") + +ME = "a1a1a1a1-0000-4000-8000-000000000001" +SESSION = json.dumps({"aci": ME, "name": "Ada Quill", "vault": "00"}) +# A 16-byte pack id and a 32-byte pack key, as the storage service keeps them. +PACK = "0123456789abcdef0123456789abcdef" +PACK_KEY = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + +FAILED = False +STEPS = "" + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false") + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def app_bin(app_dir): + name = "chatd.exe" if sys.platform == "win32" else "chatd" + if sys.platform == "darwin" and app_dir.endswith(".app"): + return os.path.join(app_dir, "Contents", "MacOS", "chatd") + return os.path.join(app_dir, name) + + +def connect(sock_path): + """chatd's socket: a file on Unix, the matching named pipe on Windows.""" + if sys.platform == "win32": + return open("\\\\.\\pipe\\" + sock_path, "r+b", buffering=0) + stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stream.settimeout(5) + stream.connect(sock_path) + return stream + + +def write_all(stream, data): + view = memoryview(data) + while view: + written = stream.write(view) + if not written: + raise RuntimeError("chatd's socket took nothing") + view = view[written:] + + +class Chat: + def __init__(self, sock_path): + self.stream = connect(sock_path) + + def ask(self, request): + body = json.dumps(request, separators=(",", ":")).encode() + write_all(self.stream, struct.pack("!I", len(body)) + body) + head = b"" + while len(head) < 4: + got = self.stream.read(4 - len(head)) + if not got: + raise RuntimeError("chatd closed its socket") + head += got + length = struct.unpack("!I", head)[0] + if length > 1024 * 1024: + raise RuntimeError("answer exceeds the protocol size limit") + chunks = b"" + while len(chunks) < length: + got = self.stream.read(length - len(chunks)) + if not got: + raise RuntimeError("chatd closed its socket mid-frame") + chunks += got + return json.loads(chunks) + + def close(self): + try: + self.stream.close() + except OSError: + pass + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + binary = app_bin(APP) + if not os.path.isfile(binary): + step("chatd is in E2E_APP_DIR", False) + return 1 + + data = os.path.join(OUT, "data") + os.makedirs(data, exist_ok=True) + sock_path = os.path.join(data, "chat.sock") + control = os.path.join(data, "signal.ctl") + open(control, "a", encoding="utf-8").close() + # What the storage service holds: one pack installed on the phone before this device was linked. + with open(os.path.join(data, "signal.storage.json"), "w", encoding="utf-8") as handle: + handle.write(json.dumps({"sticker_packs": [{"id": PACK, "key": PACK_KEY}]})) + env = os.environ.copy() + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_SIGNAL_FAKE"] = "1" + env["TINYCLIENT_SESSION_SIGNAL"] = SESSION + env.pop("TINYCLIENT_SESSION_DISCORD", None) + env.pop("TINYCLIENT_SESSION_SLACK", None) + env.pop("TINYCLIENT_SESSION_TELEGRAM", None) + env.pop("TINYCLIENT_SESSION_TEAMS", None) + kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + with open(os.path.join(OUT, "chatd.out.log"), "w", encoding="utf-8") as out, open(os.path.join(OUT, "chatd.err.log"), "w", encoding="utf-8") as err: + kwargs["stdout"] = out + kwargs["stderr"] = err + proc = subprocess.Popen([binary], **kwargs) + chat = None + try: + deadline = time.time() + 15 + while chat is None: + if proc.poll() is not None: + step("chatd stays up for the driver", False) + return 1 + if time.time() > deadline: + step("chatd opens its socket", False) + return 1 + try: + chat = Chat(sock_path) + except OSError: + time.sleep(0.1) + drive(chat, control) + finally: + if chat: + chat.close() + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + return 1 if FAILED else 0 + + +def account(): + return {"network": "signal", "account": ME} + + +def wait(what, chat, look, seconds=20): + deadline = time.time() + seconds + while time.time() < deadline: + found = look() + if found is not None: + step(what, True) + return found + time.sleep(0.2) + step(what, False) + return None + + +def steer(control, line): + with open(control, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def ask(chat, request): + try: + return chat.ask(request) + except Exception: + return None + + +def stickers(chat): + answer = ask(chat, {"op": "catalog", "account": account(), "kind": "stickers"}) + return (answer or {}).get("items") or [] + + +def drive(chat, control): + status = wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"})) + if status is None: + return + wait("Signal is connected", chat, lambda: (any(a["link"] == "connected" for a in ask(chat, {"op": "status"})["accounts"]) or None)) + + # The pack's manifest is fetched as for any install, so the picker holds the pack's stickers. + items = wait("the picker lists the stickers of the pack the storage service holds", chat, lambda: stickers(chat) or None) + if items is not None: + step("they are the pack's two stickers, named after it", sorted(item.get("id") for item in items) == [PACK + ":0", PACK + ":1"] and all(item.get("pack") == "Signal Cats" for item in items)) + + # Removed on the phone: the next read of the storage service takes the pack out of the picker. + steer(control, 'storage-manifest {"sticker_packs":[{"id":"%s","removed":true}]}' % PACK) + wait("a pack removed on the phone leaves the picker", chat, lambda: (not stickers(chat)) or None) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/signal-sticker-packs-from-storage/drive.windows.ps1 b/e2e/scenarios/signal-sticker-packs-from-storage/drive.windows.ps1 new file mode 100644 index 00000000..68b2c38b --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.windows.ps1 @@ -0,0 +1,17 @@ +# signal-sticker-packs-from-storage on Windows. The lab runs this in the console session it is already filming. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/signal-sticker-packs-from-storage/scenario.json b/e2e/scenarios/signal-sticker-packs-from-storage/scenario.json new file mode 100644 index 00000000..4fdd0d06 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "signal-sticker-packs-from-storage", + "title": "A sticker pack the phone keeps in the storage service is in the picker on a freshly linked device, and a removal takes it out", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The phone proof build does not run desktop chatd. The sticker pack list is read and kept by the desktop's chatd.", + "ios": "The phone proof build does not run desktop chatd. The sticker pack list is read and kept by the desktop's chatd." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +}