From 9dbeea8c1be200a8608b89f63e048c100d24c53b Mon Sep 17 00:00:00 2001 From: unRekable Date: Fri, 4 Dec 2026 14:33:39 +0100 Subject: [PATCH] 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 +}