//! `packages/core/__tests__/messages/applyMessageWrite.test.ts`, case for case, //! plus the Node vectors for the refusal sentences and the preview a write //! denormalises. use std::cell::RefCell; use serde_json::json; use super::*; use crate::messages::MessageMedia; const NOW: &str = "2026-08-26T10:00:00.000Z"; fn thread<'a>(last_message_at: Option<&'a str>) -> MessageWriteThread<'a> { MessageWriteThread { id: "t1", workspace_id: "w1", last_message_at, } } fn base<'a>() -> MessageWriteInput<'a> { MessageWriteInput { body: Some("hello"), ..MessageWriteInput::new(thread(None), "m1", MessageDirection::Out, NOW, NOW) } } fn tables(plan: &MessageWritePlan) -> Vec<&str> { plan.changes .iter() .map(|change| change.table.as_str()) .collect() } fn message_patch(plan: &MessageWritePlan) -> &Map { plan.changes .iter() .find(|change| change.table == "cotton_msg_messages") .and_then(|change| change.patch.as_ref()) .expect("no message change") } fn thread_patch(plan: &MessageWritePlan) -> &Map { plan.changes .iter() .find(|change| change.table == "cotton_msg_threads") .and_then(|change| change.patch.as_ref()) .expect("no thread change") } // ── planMessageWrite ───────────────────────────────────────────────────────── #[test] fn writes_the_message_row_and_advances_the_thread_in_one_batch() { let plan = plan_message_write(&base()).expect("plans"); assert_eq!(plan.message_id, "m1"); assert_eq!(plan.preview, "hello"); assert!(plan.advanced_thread); assert_eq!(tables(&plan), ["cotton_msg_messages", "cotton_msg_threads"]); assert_eq!( Value::Object(message_patch(&plan).clone()), json!({ "id": "m1", "thread_id": "t1", "workspace_id": "w1", "direction": "out", "channel": "cotton", "origin": "live", "body": "hello", "media": [], "mentions": [], "external_id": null, "sent_at": NOW, "created_at": NOW, "reply_to_id": null, "reply_to_external_id": null, "forward_of_id": null, "sender_participant_id": null, "seq": null, "reactions": [], "meta": {}, }) ); assert_eq!( Value::Object(thread_patch(&plan).clone()), json!({ "last_message_at": NOW, "last_message_preview": "hello", "updated_at": NOW, }) ); } /// RULE: A message row takes the database it belongs to from its conversation, never from whoever asked to write it. /// The BEFORE trigger's job. A caller cannot file a message into somebody else's /// workspace by asking. #[test] fn takes_the_workspace_from_the_thread_never_from_the_caller() { let plan = plan_message_write(&MessageWriteInput { thread: MessageWriteThread { id: "t1", workspace_id: "the-real-one", last_message_at: None, }, ..base() }) .expect("plans"); assert_eq!( message_patch(&plan).get("workspace_id"), Some(&Value::from("the-real-one")) ); } /// RULE: Writing an older message never drags a conversation's preview and timestamp backwards. #[test] fn does_not_drag_a_live_threads_preview_backwards() { let plan = plan_message_write(&MessageWriteInput { thread: thread(Some("2026-08-26T12:00:00.000Z")), sent_at: "2021-03-04T09:00:00.000Z", origin: Some(MessageOrigin::Imported), ..base() }) .expect("plans"); assert!(!plan.advanced_thread); assert_eq!(tables(&plan), ["cotton_msg_messages"]); } #[test] fn carries_a_reply_a_forward_mentions_media_and_a_seq_when_it_has_them() { let media = [MessageMedia { kind: Some(crate::constants::MessageMediaKind::Image), ..MessageMedia::new("ws/messages/t1/a.jpg", "image/jpeg") }]; let mentions = ["919999000011".to_string()]; let meta = MessageMeta { forwarded: Some(true), ..MessageMeta::default() }; let plan = plan_message_write(&MessageWriteInput { body: Some("look"), media: &media, mentions: &mentions, reply_to_id: Some("m0"), forward_of_id: Some("src-9"), seq: Some(12), meta: Some(&meta), ..base() }) .expect("plans"); let patch = message_patch(&plan); assert_eq!(patch.get("mentions"), Some(&json!(["919999000011"]))); assert_eq!(patch.get("reply_to_id"), Some(&Value::from("m0"))); assert_eq!(patch.get("forward_of_id"), Some(&Value::from("src-9"))); assert_eq!(patch.get("seq"), Some(&Value::from(12))); assert_eq!(patch.get("meta"), Some(&json!({ "forwarded": true }))); assert_eq!(plan.preview, "Photo · look"); } #[test] fn trims_the_body_and_stores_null_rather_than_an_empty_string() { let plan = plan_message_write(&MessageWriteInput { body: Some(" spaced "), ..base() }) .expect("plans"); assert_eq!( message_patch(&plan).get("body"), Some(&Value::from("spaced")) ); let media = [MessageMedia::new("k", "image/jpeg")]; let media_only = plan_message_write(&MessageWriteInput { body: Some(" "), media: &media, ..base() }) .expect("plans"); assert_eq!(message_patch(&media_only).get("body"), Some(&Value::Null)); } #[test] fn clears_the_draft_in_the_same_batch_when_asked() { let plan = plan_message_write(&MessageWriteInput { clear_draft: true, ..base() }) .expect("plans"); assert_eq!( Value::Object(thread_patch(&plan).clone()), json!({ "last_message_at": NOW, "last_message_preview": "hello", "updated_at": NOW, "draft": null, "draft_reply_to_id": null, }) ); } #[test] fn clears_the_draft_even_when_the_denorm_may_not_advance() { let plan = plan_message_write(&MessageWriteInput { thread: thread(Some("2026-08-26T12:00:00.000Z")), clear_draft: true, ..base() }) .expect("plans"); assert!(!plan.advanced_thread); assert_eq!(tables(&plan), ["cotton_msg_messages", "cotton_msg_threads"]); assert_eq!( Value::Object(thread_patch(&plan).clone()), json!({ "draft": null, "draft_reply_to_id": null }) ); } #[test] fn refuses_a_message_with_neither_body_nor_media() { let refusal = plan_message_write(&MessageWriteInput { body: Some(" "), media: &[], ..base() }) .unwrap_err(); assert_eq!(refusal.to_string(), "Write something first"); assert_eq!(refusal.code(), "EMPTY_MESSAGE"); assert_eq!( plan_message_write(&MessageWriteInput { body: None, ..base() }) .unwrap_err() .code(), "EMPTY_MESSAGE" ); } #[test] fn refuses_a_body_past_the_one_ceiling() { let too_long = "x".repeat(MESSAGE_BODY_MAX + 1); let refusal = plan_message_write(&MessageWriteInput { body: Some(&too_long), ..base() }) .unwrap_err(); assert!(refusal.to_string().contains("4,000"), "{refusal}"); assert_eq!(refusal.code(), "MESSAGE_TOO_LONG"); let at_the_line = "x".repeat(MESSAGE_BODY_MAX); assert!(plan_message_write(&MessageWriteInput { body: Some(&at_the_line), ..base() }) .is_ok()); } #[test] fn refuses_a_mention_that_is_not_a_phone() { let mentions = ["+919999000011".to_string()]; let refusal = plan_message_write(&MessageWriteInput { mentions: &mentions, ..base() }) .unwrap_err(); assert!(refusal.to_string().contains("mention"), "{refusal}"); assert_eq!(refusal.code(), "VALIDATION"); } /// RULE: Writing a message never touches the columns that belong to the owner alone. #[test] fn never_writes_a_private_column_the_relay_would_fight_the_owner_for_it() { let plan = plan_message_write(&base()).expect("plans"); for column in [ "read_at", "starred_at", "hidden_at", "edited_at", "deleted_at", ] { assert!(!message_patch(&plan).contains_key(column), "{column}"); } for column in ["read_seq", "delivered_seq", "muted_until", "pinned_at"] { assert!(!thread_patch(&plan).contains_key(column), "{column}"); } } // ── applyMessageWrite ──────────────────────────────────────────────────────── #[test] fn hands_the_whole_batch_to_the_sink_once() { let seen: RefCell>> = RefCell::new(Vec::new()); let plan = apply_message_write::( |changes| { seen.borrow_mut().push(changes.to_vec()); Ok(()) }, &base(), ) .expect("applies"); let seen = seen.borrow(); assert_eq!(seen.len(), 1); assert_eq!(seen[0], plan.changes); } #[test] fn does_not_call_the_sink_at_all_when_the_input_is_refused() { let called = RefCell::new(false); let error = apply_message_write::( |_| { *called.borrow_mut() = true; Ok(()) }, &MessageWriteInput { body: Some(""), ..base() }, ) .unwrap_err(); assert!(matches!( error, ApplyMessageWriteError::Refused(MessageWriteRefused::Empty) )); assert!(!*called.borrow()); } /// The TypeScript's "awaits an async sink before returning" case. Rust's async is /// the caller's, so what is asserted here is the guarantee that survives the /// translation: a sink that fails is reported as the SINK's failure and the plan /// does not come back as a success. #[test] fn a_sink_that_fails_is_reported_as_the_sinks_failure() { let error = apply_message_write(|_| Err("offline".to_string()), &base()).expect_err("the sink failed"); assert!(matches!(error, ApplyMessageWriteError::Sink(ref why) if why == "offline")); assert_eq!(error.to_string(), "offline"); } // ── the relay's two columns ────────────────────────────────────────────────── /// The double option, which is the one place `undefined` and `null` are different /// values rather than two spellings of absence. #[test] fn an_absent_edited_at_omits_the_column_and_an_explicit_null_writes_one() { let plan = plan_message_write(&base()).expect("plans"); assert!(!message_patch(&plan).contains_key("edited_at")); let explicit = plan_message_write(&MessageWriteInput { edited_at: Some(None), deleted_at: Some(Some("2026-08-26T11:00:00.000Z")), ..base() }) .expect("plans"); let patch = message_patch(&explicit); assert_eq!(patch.get("edited_at"), Some(&Value::Null)); assert_eq!( patch.get("deleted_at"), Some(&Value::from("2026-08-26T11:00:00.000Z")) ); // And they land LAST, after `meta`, exactly where the spread puts them. let keys: Vec<&str> = patch.keys().map(String::as_str).collect(); assert_eq!(&keys[keys.len() - 3..], ["meta", "edited_at", "deleted_at"]); } // ── Node vectors ───────────────────────────────────────────────────────────── /// Printed by running the TypeScript (`vec_applymessagewrite.ts`), pasted /// verbatim. /// /// The refusal sentences first: they are what a person reads in a toast, and the /// long one carries `toLocaleString("en-GB")` of the ceiling — a comma, not a /// space and not a lakh grouping. #[test] fn node_vectors_for_the_refusal_sentences() { let too_long = "x".repeat(MESSAGE_BODY_MAX + 1); assert_eq!( plan_message_write(&MessageWriteInput { body: Some(&too_long), ..base() }) .unwrap_err() .to_string(), "That message is too long \u{2014} 4,000 characters maximum." ); let mentions = ["+919999000011".to_string()]; assert_eq!( plan_message_write(&MessageWriteInput { mentions: &mentions, ..base() }) .unwrap_err() .to_string(), "A mention is a phone as digits, got \"+919999000011\"" ); assert_eq!( plan_message_write(&MessageWriteInput { body: None, ..base() }) .unwrap_err() .to_string(), "Write something first" ); } /// The ceiling is counted in UTF-16 code units, so 2 000 astral emoji are exactly /// at the line and 2 001 are over it — a `chars()` count would have admitted /// twice the message the composer allows. #[test] fn node_vectors_for_the_utf16_ceiling() { let at_the_line = "\u{1f600}".repeat(2000); assert!(plan_message_write(&MessageWriteInput { body: Some(&at_the_line), ..base() }) .is_ok()); let over = "\u{1f600}".repeat(2001); assert_eq!( plan_message_write(&MessageWriteInput { body: Some(&over), ..base() }) .unwrap_err() .code(), "MESSAGE_TOO_LONG" ); } /// The denormalised preview, which is the string every other member's file will /// hold for this thread. It is computed from the TRIMMED body and the media, and /// it is NOT the deleted line even when the relay is mirroring an already-deleted /// row — `deletedAt` is deliberately not passed to the preview. #[test] fn node_vectors_for_the_denormalised_preview() { let voice = [MessageMedia { kind: Some(crate::constants::MessageMediaKind::Voice), duration_ms: Some(65_000.0), ..MessageMedia::new("k", "audio/mp4") }]; let plan = plan_message_write(&MessageWriteInput { body: Some(" listen to this "), media: &voice, ..base() }) .expect("plans"); assert_eq!(plan.preview, "Voice message · 1:05 · listen to this"); assert_eq!( thread_patch(&plan).get("last_message_preview"), Some(&Value::from("Voice message · 1:05 · listen to this")) ); let deleted = plan_message_write(&MessageWriteInput { body: Some("said and unsaid"), deleted_at: Some(Some("2026-08-26T10:30:00.000Z")), ..base() }) .expect("plans"); assert_eq!(deleted.preview, "said and unsaid"); let long = "y".repeat(300); let capped = plan_message_write(&MessageWriteInput { body: Some(&long), ..base() }) .expect("plans"); assert_eq!(capped.preview.len(), 140); assert_eq!(capped.preview, "y".repeat(140)); }