//! A conversation's first page comes off the phone's own file (lane//! threadload, 16 Oct 2026). On phone 286 the owner saw Messages and other//! inside pages show their data late after the tap, with the Mac reachable;//! the app is local-first, so the page a thread opens on must never wait on//! the serving Mac.//!//! Every row is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).use std::io::Read;use std::net::TcpListener;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};use rusqlite::types::ValueasSqlValue;use serde_json::json;usecrate::fixture;const THREAD: &str = "11111111-1111-4111-8111-00000000a001";const MESSAGES: usize = 2_000;/// A server that takes every connection and never answers: a client that/// waited on it would wait until its own timeout. It counts what reached it.fn a_server_that_never_answers() -> (String, Arc<AtomicUsize>) {let listener = TcpListener::bind("127.0.0.1:0").expect("a loopback port");let address = format!("http://{}", listener.local_addr().expect("its address"));let reached = Arc::new(AtomicUsize::new(0));let counted = reached.clone(); std::thread::spawn(move || {for stream in listener.incoming().flatten() { counted.fetch_add(1, Ordering::SeqCst);// Hold it open, read what is said, answer nothing. std::thread::spawn(move || {letmut stream = stream;letmut sink = [0u8; 4096];while matches!(stream.read(&mut sink), Ok(n) if n > 0) {} }); } }); (address, reached)}/// A phone joined to `server`, its own file holding one chat of 2,000 messages.fn a_phone_with_a_long_chat(server: &str) -> (tempfile::TempDir, crate::handle::CottonHandle) {let dir = tempfile::tempdir().expect("a temp container");let layout = cotton_client::layout::Layout::new(dir.path()); std::fs::create_dir_all(layout.client_dir()).expect("the client folder"); std::fs::write( layout.connection_json(), serde_json::to_vec(&json!({"mode": "remote","baseUrl": server,"workspaceId": fixture::WORKSPACE,"ownerId": fixture::OWNER,"connectedAt": "2026-10-16T00:00:00.000Z", })) .expect("connection json"), ) .expect("the connection record");let replica = layout.replica(fixture::WORKSPACE); std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");let db = fixture::seeded(&replica); fixture::device_row(&db, &fixture::paired_key());let ws = || SqlValue::from(fixture::WORKSPACE.to_string()); db.run("BEGIN", &[]).expect("begin"); db.run("INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \ VALUES (?, ?, 'dm', 'Example friend', '2026-01-01', '2026-10-16')", &[SqlValue::from(THREAD.to_string()), ws()], ) .expect("the chat");for n in0..MESSAGES {let sent = format!("2026-{:02}-{:02}T{:02}:{:02}:00Z", 1 + n / 200, 1 + (n / 8) % 25, (n / 60) % 24, n % 60); db.run("INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at) \ VALUES (?, ?, ?, ?, 'cotton', 'live', ?, ?, ?)", &[SqlValue::from(format!("11111111-1111-4111-8111-{n:012}")),SqlValue::from(THREAD.to_string()), ws(),SqlValue::from(if n % 3 == 0 { "out" } else { "in" }.to_string()),SqlValue::from(format!("Example message {n}")),SqlValue::from(sent.clone()),SqlValue::from(sent), ], ) .expect("a message"); } db.run("COMMIT", &[]).expect("commit"); drop(db);let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None, }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: None, }) .expect("an open core"); (dir, handle)}/// RULE: a thread of 2,000 messages draws its first slip from the phone's own file, with the client cut from its server: the chat's row and its newest page answer while the only server takes the connection and never replies, because a page that waited on the Mac drew late (phone 286) and the app is local-first — records before bytes.#[test]fn a_long_chat_s_first_page_answers_from_the_file_while_the_server_never_does() {let (server, _reached) = a_server_that_never_answers();let (_dir, handle) = a_phone_with_a_long_chat(&server);let run = |method: &str, args: serde_json::Value| crate::methods::dispatch(&handle, method, &args);let started = Instant::now();let chat = run("records.get", json!({ "table": "thread", "id": THREAD })).expect("the chat, from the file"); assert_eq!(chat["id"], THREAD);let page = run("records.list", json!({ "table": "message", "page": 0, "limit": 50, "where": { "thread_id": THREAD } }), ) .expect("the newest page, from the file");// A hang guard, not a timing: a read that waited on the server would sit// on its request until the client's own timeout, tens of seconds. assert!(started.elapsed() < Duration::from_secs(10), "the reads waited on the server: {:?}", started.elapsed());let rows = page["records"].as_array().expect("records"); assert_eq!(rows.len(), 50, "{page}"); assert!( rows.iter().any(|row| row["data"]["body"] == "Example message 1999"),"the newest page holds the newest message: {page}" );// The phone's own exchange is still waiting on the cut server; the reads// never did, and the test does not sit out that exchange's timeout. std::mem::forget(handle);}