From 7708cdfb00a3ae54249a5a76489ee4cbad9600d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 14:35:16 -0300 Subject: [PATCH 01/11] feat(chat): schedule text messages --- .../down.sql | 1 + .../up.sql | 9 + crates/chat-store/src/store/mod.rs | 1 + .../src/store/scheduled_messages.rs | 145 +++++++++++ crates/chat-store/tests/scheduled_messages.rs | 97 ++++++++ crates/core/src/lib.rs | 8 + crates/daemon/src/server/requests.rs | 41 +++ crates/daemon/src/server/tests.rs | 22 ++ crates/daemon/src/session_bridge/act.rs | 48 +++- crates/daemon/src/session_bridge/action.rs | 17 ++ crates/daemon/src/session_bridge/mod.rs | 57 +++++ crates/gui/src/app/mod.rs | 5 + crates/gui/src/app/scheduled_messages.rs | 235 ++++++++++++++++++ crates/gui/src/components/input_area_view.rs | 56 +++++ crates/gui/src/i18n/catalog.rs | 8 + crates/gui/src/session/frames.rs | 12 + crates/gui/src/session/mod.rs | 50 ++++ crates/ipc/src/protocol.rs | 17 ++ crates/ipc/src/transport.rs | 4 +- crates/session/src/whatsapp/mod.rs | 1 + .../src/whatsapp/scheduled_messages.rs | 83 +++++++ docs/gotchas.md | 9 + 22 files changed, 923 insertions(+), 3 deletions(-) create mode 100644 crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql create mode 100644 crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql create mode 100644 crates/chat-store/src/store/scheduled_messages.rs create mode 100644 crates/chat-store/tests/scheduled_messages.rs create mode 100644 crates/gui/src/app/scheduled_messages.rs create mode 100644 crates/session/src/whatsapp/scheduled_messages.rs diff --git a/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql b/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql new file mode 100644 index 00000000..bfe988c3 --- /dev/null +++ b/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql @@ -0,0 +1 @@ +DROP TABLE scheduled_messages; diff --git a/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql b/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql new file mode 100644 index 00000000..1d75af10 --- /dev/null +++ b/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql @@ -0,0 +1,9 @@ +CREATE TABLE scheduled_messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + device_id INTEGER NOT NULL REFERENCES device(id) ON DELETE CASCADE, + jid TEXT NOT NULL, + text TEXT NOT NULL, + send_at_ms BIGINT NOT NULL +); + +CREATE INDEX scheduled_messages_due ON scheduled_messages(device_id, send_at_ms, id); diff --git a/crates/chat-store/src/store/mod.rs b/crates/chat-store/src/store/mod.rs index 49232fa0..2de1fd21 100644 --- a/crates/chat-store/src/store/mod.rs +++ b/crates/chat-store/src/store/mod.rs @@ -28,6 +28,7 @@ mod receipt; mod recovery; pub(crate) mod retirement; mod revoke; +mod scheduled_messages; pub(crate) mod shared_history; mod writer; diff --git a/crates/chat-store/src/store/scheduled_messages.rs b/crates/chat-store/src/store/scheduled_messages.rs new file mode 100644 index 00000000..e3725f0e --- /dev/null +++ b/crates/chat-store/src/store/scheduled_messages.rs @@ -0,0 +1,145 @@ +use diesel::prelude::*; +use diesel::sql_types::{BigInt, Integer, Text}; + +use super::ChatStore; +use crate::error::{Result, db_err}; + +impl ChatStore { + pub async fn schedule_message( + &self, + jid: String, + text: String, + send_at_ms: i64, + ) -> Result { + let account = self.device_id(); + let inserted = self + .db() + .run(move |conn| { + diesel::sql_query( + "INSERT INTO scheduled_messages (device_id, jid, text, send_at_ms) + SELECT ?1, ?2, ?3, ?4 WHERE ( + SELECT COUNT(*) FROM scheduled_messages WHERE device_id = ?1 + ) < 256", + ) + .bind::(account) + .bind::(jid) + .bind::(text) + .bind::(send_at_ms) + .execute(conn) + .map_err(db_err) + }) + .await?; + Ok(inserted == 1) + } + + pub async fn take_scheduled_message(&self, now_ms: i64) -> Result> { + #[derive(QueryableByName)] + struct ScheduledMessage { + #[diesel(sql_type = Text)] + jid: String, + #[diesel(sql_type = Text)] + text: String, + } + + let account = self.device_id(); + let due = self + .db() + .run(move |conn| { + diesel::sql_query( + "DELETE FROM scheduled_messages WHERE id = ( + SELECT id FROM scheduled_messages WHERE device_id = ?1 AND send_at_ms <= ?2 + ORDER BY send_at_ms, id LIMIT 1 + ) RETURNING jid, text", + ) + .bind::(account) + .bind::(now_ms) + .get_result::(conn) + .optional() + .map_err(db_err) + }) + .await?; + Ok(due.map(|message| (message.jid, message.text))) + } + + pub async fn next_scheduled_message(&self) -> Result> { + use diesel::sql_types::Nullable; + + #[derive(QueryableByName)] + struct Deadline { + #[diesel(sql_type = Nullable)] + due: Option, + } + + let account = self.device_id(); + let deadline = self + .db() + .read(move |conn| { + diesel::sql_query( + "SELECT MIN(send_at_ms) AS due FROM scheduled_messages WHERE device_id = ?1", + ) + .bind::(account) + .get_result::(conn) + .map_err(db_err) + }) + .await?; + Ok(deadline.due) + } +} + +impl ChatStore { + pub async fn scheduled_messages( + &self, + jid: String, + ) -> Result> { + #[derive(QueryableByName)] + struct ScheduledRow { + #[diesel(sql_type = BigInt)] + id: i64, + #[diesel(sql_type = Text)] + preview: String, + #[diesel(sql_type = BigInt)] + send_at_ms: i64, + } + + let account = self.device_id(); + let rows = self + .db() + .read(move |conn| { + diesel::sql_query( + "SELECT id, substr(text, 1, 120) AS preview, send_at_ms FROM scheduled_messages + WHERE device_id = ? AND jid = ? ORDER BY send_at_ms, id", + ) + .bind::(account) + .bind::(jid) + .load::(conn) + .map_err(db_err) + }) + .await?; + Ok(rows + .into_iter() + .map(|row| oxidezap_core::ScheduledMessage { + id: row.id, + preview: row.preview, + send_at_ms: row.send_at_ms, + }) + .collect()) + } + + pub async fn cancel_scheduled_message(&self, jid: String, id: i64) -> Result { + let account = self.device_id(); + let removed = self + .db() + .run(move |conn| { + diesel::sql_query( + "DELETE FROM scheduled_messages WHERE device_id = ? AND jid = ? AND id = ?", + ) + .bind::(account) + .bind::(jid) + .bind::(id) + .execute(conn) + .map_err(db_err) + }) + .await?; + Ok(removed == 1) + } +} diff --git a/crates/chat-store/tests/scheduled_messages.rs b/crates/chat-store/tests/scheduled_messages.rs new file mode 100644 index 00000000..d0352851 --- /dev/null +++ b/crates/chat-store/tests/scheduled_messages.rs @@ -0,0 +1,97 @@ +mod common; + +use common::*; + +#[tokio::test] +async fn scheduled_messages_survive_reopen_and_are_claimed_once() { + let (device, queue) = test_store().await; + queue + .schedule_message(PEER.into(), "second".into(), 200) + .await + .unwrap(); + queue + .schedule_message(PEER.into(), "first".into(), 100) + .await + .unwrap(); + queue + .schedule_message(GROUP.into(), "third".into(), 200) + .await + .unwrap(); + drop(queue); + + let queue = ChatStore::new(&device).await.unwrap(); + assert_eq!(queue.next_scheduled_message().await.unwrap(), Some(100)); + assert_eq!(queue.take_scheduled_message(99).await.unwrap(), None); + let (one, two) = tokio::join!( + queue.take_scheduled_message(100), + queue.take_scheduled_message(100), + ); + let claims = [one.unwrap(), two.unwrap()] + .into_iter() + .flatten() + .collect::>(); + assert_eq!(claims, vec![(PEER.into(), "first".into())]); + assert_eq!( + queue.take_scheduled_message(200).await.unwrap(), + Some((PEER.into(), "second".into())) + ); + assert_eq!( + queue.take_scheduled_message(200).await.unwrap(), + Some((GROUP.into(), "third".into())) + ); + assert_eq!(queue.next_scheduled_message().await.unwrap(), None); +} + +#[tokio::test] +async fn cancellation_and_reset_only_affect_the_owning_account() { + let (device, queue) = test_store().await; + let second = device.database().create_device().await.unwrap(); + let other = ChatStore::new(&second).await.unwrap(); + queue + .schedule_message(PEER.into(), "cancel me".into(), 100) + .await + .unwrap(); + queue + .schedule_message(PEER.into(), "reset me".into(), 200) + .await + .unwrap(); + other + .schedule_message(PEER.into(), "retain me".into(), 50) + .await + .unwrap(); + + let rows = queue.scheduled_messages(PEER.into()).await.unwrap(); + assert_eq!(rows.len(), 2); + assert!( + !other + .cancel_scheduled_message(PEER.into(), rows[0].id) + .await + .unwrap() + ); + assert!( + !queue + .cancel_scheduled_message(GROUP.into(), rows[0].id) + .await + .unwrap() + ); + assert!( + queue + .cancel_scheduled_message(PEER.into(), rows[0].id) + .await + .unwrap() + ); + assert_eq!(queue.take_scheduled_message(100).await.unwrap(), None); + + drop(queue); + device + .database() + .reset_device(device.device_id()) + .await + .unwrap(); + let queue = ChatStore::new(&device).await.unwrap(); + assert_eq!(queue.next_scheduled_message().await.unwrap(), None); + assert_eq!( + other.take_scheduled_message(100).await.unwrap(), + Some((PEER.into(), "retain me".into())) + ); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ac224574..f84ad46c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -83,3 +83,11 @@ pub use video::{CallVideo, CallVideoFrame, VideoStream}; mod business; pub use business::{BusinessAction, BusinessButton, BusinessContent, BusinessKind}; + +/// A pending text message preview for the scheduling dialog. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ScheduledMessage { + pub id: i64, + pub preview: String, + pub send_at_ms: i64, +} diff --git a/crates/daemon/src/server/requests.rs b/crates/daemon/src/server/requests.rs index 7904a720..47931db2 100644 --- a/crates/daemon/src/server/requests.rs +++ b/crates/daemon/src/server/requests.rs @@ -103,6 +103,47 @@ pub(super) async fn handle_request( ClientRequest::SendText(request) => { acted(dispatch(hub, commands, Action::SendText(*request)).await) } + ClientRequest::ScheduleMessage { + jid, + text, + send_at_ms, + } => acted( + dispatch( + hub, + commands, + Action::ScheduleMessage { + jid, + text, + send_at_ms, + }, + ) + .await, + ), + ClientRequest::CancelScheduledMessage { jid, scheduled_id } => acted( + dispatch( + hub, + commands, + Action::CancelScheduledMessage { jid, scheduled_id }, + ) + .await, + ), + ClientRequest::ListScheduledMessages { jid } => { + let id = match addressed(id, "listing scheduled messages needs an id") { + Ok(id) => id, + Err(refusal) => return refusal, + }; + out_of_band( + hub, + commands, + id, + Action::ListScheduledMessages { + id, + jid, + answer_to: outbox.clone(), + }, + ) + .await + } ClientRequest::SyncedStickers { favorites } => { let id = match addressed(id, "sticker sync needs an id to answer under") { Ok(id) => id, diff --git a/crates/daemon/src/server/tests.rs b/crates/daemon/src/server/tests.rs index c5fef113..cfc29bca 100644 --- a/crates/daemon/src/server/tests.rs +++ b/crates/daemon/src/server/tests.rs @@ -750,6 +750,28 @@ async fn a_command_reaches_the_session_rather_than_being_refused() { )); } +#[tokio::test] +async fn an_offline_account_can_schedule_a_text_message() { + let hub = StateHub::for_account(oxidezap_core::AccountId::LEGACY); + let (commands, taken) = bridge(CommandOutcome::Accepted); + let deadline = 2_100_000_000_000; + let request = bare(ClientRequest::ScheduleMessage { + jid: "120363000000000001@g.us".into(), + text: "on time".into(), + send_at_ms: deadline, + }); + let answer = handle_request(request, &hub, &no_plugins(), &commands, &outbox()).await; + assert!(matches!( + parse(answer.frame), + DaemonMessage::Accepted { .. } + )); + assert!(matches!( + taken.await.unwrap(), + Some(Action::ScheduleMessage { jid, text, send_at_ms }) + if jid == "120363000000000001@g.us" && text == "on time" && send_at_ms == deadline + )); +} + /// The payload moves rather than being unpacked and rebuilt, so what the /// session is handed is the struct the client sent. A field dropped between /// the two compiles and arrives as a document called "file" with no type on diff --git a/crates/daemon/src/session_bridge/act.rs b/crates/daemon/src/session_bridge/act.rs index 52ef535d..90ff87e6 100644 --- a/crates/daemon/src/session_bridge/act.rs +++ b/crates/daemon/src/session_bridge/act.rs @@ -126,6 +126,23 @@ impl Bridge { }); None } + Action::ListScheduledMessages { id, jid, answer_to } => { + let Some(permit) = self.permit() else { + let _ = reply.send(too_busy()); + return None; + }; + let task = client.scheduled_messages(jid); + oxidezap_session::spawn(async move { + let result = match task.await { + Ok(Ok(items)) => Ok(DaemonMessage::ScheduledMessages { id, items }), + other => mutation_answer(id, other), + }; + answer_now(&answer_to, answered(id, result)); + let _ = reply.send(CommandOutcome::Accepted); + drop(permit); + }); + None + } Action::SyncedStickers { id, favorites, @@ -1573,9 +1590,33 @@ impl Bridge { | Action::PublishStatus { .. } | Action::PublishStatusMedia { .. } | Action::SyncedStickers { .. } + | Action::ListScheduledMessages { .. } | Action::ReuseComposerMedia { .. } => { unreachable!("addressed actions are handled in begin_slow") } + Action::ScheduleMessage { + jid, + text, + send_at_ms, + } => match client.schedule_message(&jid, text, send_at_ms).await { + Ok(()) => { + self.next_scheduled = Some( + self.next_scheduled + .map_or(send_at_ms, |current| current.min(send_at_ms)), + ); + CommandOutcome::Accepted + } + Err(error) => CommandOutcome::Refused(error), + }, + Action::CancelScheduledMessage { jid, scheduled_id } => { + match client.cancel_scheduled_message(jid, scheduled_id).await { + Ok(()) => { + self.refresh_schedule(client).await; + CommandOutcome::Accepted + } + Err(error) => CommandOutcome::Refused(error), + } + } Action::SendText(oxidezap_ipc::SendText { jid, text, @@ -2198,7 +2239,10 @@ impl Bridge { /// where it was taken; a task that outlives this one holds it until every /// handle has resolved. `JoinHandle` errors are the session's runtime going /// away, which is a shutdown, not something to report. -fn hold(permit: OwnedSemaphorePermit, work: [oxidezap_session::Task<()>; N]) { +pub(super) fn hold( + permit: OwnedSemaphorePermit, + work: [oxidezap_session::Task<()>; N], +) { oxidezap_session::spawn(async move { for handle in work { let _ = handle.await; @@ -2333,7 +2377,7 @@ fn answered(id: RequestId, result: Result) -> Stri /// A millisecond timestamp alone collides on fast double-sends, and the /// session renames the bubble by this id when the server assigns the real /// one, so a collision would rename the wrong message. -fn next_local_id() -> String { +pub(super) fn next_local_id() -> String { use portable_atomic::AtomicU64; use std::sync::atomic::Ordering; static SEQ: AtomicU64 = AtomicU64::new(0); diff --git a/crates/daemon/src/session_bridge/action.rs b/crates/daemon/src/session_bridge/action.rs index dffd4f98..01557abf 100644 --- a/crates/daemon/src/session_bridge/action.rs +++ b/crates/daemon/src/session_bridge/action.rs @@ -24,6 +24,20 @@ use oxidezap_ipc::{CallAction, RequestId}; #[derive(Debug)] pub enum Action { SendText(oxidezap_ipc::SendText), + ScheduleMessage { + jid: String, + text: String, + send_at_ms: i64, + }, + ListScheduledMessages { + id: RequestId, + jid: String, + answer_to: Outbox, + }, + CancelScheduledMessage { + jid: String, + scheduled_id: i64, + }, SyncedStickers { id: RequestId, favorites: bool, @@ -257,6 +271,9 @@ impl Action { _ => !matches!( self, Self::CallDevices { .. } + | Self::ScheduleMessage { .. } + | Self::ListScheduledMessages { .. } + | Self::CancelScheduledMessage { .. } | Self::ReloadHistory | Self::ReconnectSession | Self::RefreshVideo diff --git a/crates/daemon/src/session_bridge/mod.rs b/crates/daemon/src/session_bridge/mod.rs index 74f38932..0c719b1a 100644 --- a/crates/daemon/src/session_bridge/mod.rs +++ b/crates/daemon/src/session_bridge/mod.rs @@ -344,7 +344,11 @@ pub async fn run( let mute_timer = wait_for_mute_expiry(bridge.hub.clone()); tokio::pin!(mute_timer); loop { + let was_connected = bridge.hub.connection().is_connected(); tokio::select! { + () = wait_for_schedule(bridge.next_scheduled.filter(|_| was_connected)) => { + bridge.send_scheduled(&client).await; + } () = &mut mute_timer => { mute_timer.set(wait_for_mute_expiry(bridge.hub.clone())); }, @@ -357,6 +361,9 @@ pub async fn run( // reopens this account. No reset/removal is requested. Answer::Restart => break, } + if !was_connected && bridge.hub.connection().is_connected() { + bridge.refresh_schedule(&client).await; + } mute_timer.set(wait_for_mute_expiry(bridge.hub.clone())); } // The session dropped its sender: the run loop is gone and no @@ -676,6 +683,7 @@ const FORGET_GRACE: std::time::Duration = std::time::Duration::from_secs(30); /// Everything the event loop carries between one event and the next. struct Bridge { devices: call_devices::Devices, + next_scheduled: Option, hub: Arc, lifecycle: RuntimeLifecycle, /// The plugins, fed the same events the front ends get. @@ -715,7 +723,55 @@ struct Bridge { avatar_recorder: oxidezap_session::AvatarRecorder, } +async fn wait_for_schedule(deadline: Option) { + let Some(deadline) = deadline else { + return std::future::pending().await; + }; + let delay = deadline + .saturating_sub(wacore::time::now_millis()) + .clamp(0, 60_000); + if delay > 0 { + oxidezap_platform::sleep(std::time::Duration::from_millis(delay as u64)).await; + } +} + impl Bridge { + async fn refresh_schedule(&mut self, client: &WhatsAppClient) { + self.next_scheduled = match client.next_scheduled_message().await { + Ok(next) => next, + Err(error) => { + log::warn!("could not read scheduled messages: {error}"); + Some(wacore::time::now_millis().saturating_add(5_000)) + } + }; + } + + async fn send_scheduled(&mut self, client: &WhatsAppClient) { + if self + .next_scheduled + .is_some_and(|due| due > wacore::time::now_millis()) + { + return; + } + let Some(permit) = self.permit() else { + self.next_scheduled = Some(wacore::time::now_millis().saturating_add(1_000)); + return; + }; + match client.take_scheduled_message().await { + Ok(Some((jid, text))) => act::hold( + permit, + [client.send_message(&jid, &text, act::next_local_id(), None)], + ), + Ok(None) => {} + Err(error) => { + log::warn!("could not claim a scheduled message: {error}"); + self.next_scheduled = Some(wacore::time::now_millis().saturating_add(5_000)); + return; + } + } + self.refresh_schedule(client).await; + } + #[cfg(test)] fn new(hub: Arc, plugins: Arc) -> Self { // No session behind it: these tests fold events without opening a @@ -746,6 +802,7 @@ impl Bridge { Self { devices: call_devices::Devices::new(&hub), + next_scheduled: None, hub, lifecycle, plugins, diff --git a/crates/gui/src/app/mod.rs b/crates/gui/src/app/mod.rs index ad4600f3..a0736489 100644 --- a/crates/gui/src/app/mod.rs +++ b/crates/gui/src/app/mod.rs @@ -29,6 +29,7 @@ mod paging; mod plugins_ctl; mod recording; mod recovery; +mod scheduled_messages; mod search; mod settings; mod status; @@ -3276,6 +3277,10 @@ impl WhatsAppApp { self.send_message(text, cx); } } + InputAreaEvent::ListScheduledMessages => self.open_scheduled_messages(window, cx), + InputAreaEvent::ScheduleMessage(text) => { + self.open_schedule_message(text, input_area, window, cx); + } InputAreaEvent::LoadPickerMedia(tab) => self.load_picker_media(*tab, input_area, cx), InputAreaEvent::SendPickerMedia(request) => self.send_picker_media(request, cx), InputAreaEvent::AttachFiles(category) => { diff --git a/crates/gui/src/app/scheduled_messages.rs b/crates/gui/src/app/scheduled_messages.rs new file mode 100644 index 00000000..98e0ba49 --- /dev/null +++ b/crates/gui/src/app/scheduled_messages.rs @@ -0,0 +1,235 @@ +use chrono::{Local, NaiveDateTime, TimeZone as _}; +use gpui::{AppContext as _, Context, Entity, ParentElement as _, Styled as _, Window, div}; +use gpui_component::{ + WindowExt as _, + input::{Input, InputState}, +}; + +use super::{WhatsAppApp, notices::Tone}; +use crate::components::InputAreaView; +use crate::theme::ActiveProductTheme as _; + +impl WhatsAppApp { + pub(super) fn open_schedule_message( + &mut self, + text: &str, + input_area: &Entity, + window: &mut Window, + cx: &mut Context, + ) { + let (Some(jid), Some(session)) = (self.selected_chat.clone(), &self.client) else { + return; + }; + let account = session.account(); + let time = cx.new(|cx| InputState::new(window, cx).placeholder("YYYY-MM-DD HH:MM")); + let draft = text.to_owned(); + let composer = input_area.downgrade(); + let app = cx.entity().downgrade(); + window.open_alert_dialog(cx, move |dialog, _, cx| { + let metrics = cx.product().metrics; + let time_input = time.clone(); + let jid = jid.clone(); + let draft = draft.clone(); + let composer = composer.clone(); + let app = app.clone(); + dialog + .confirm() + .title(crate::tr!(ScheduleMessage)) + .ok_text(crate::tr!(ScheduleMessage)) + .cancel_text(crate::tr!(Cancel)) + .child( + div() + .flex() + .flex_col() + .gap(metrics.space_md()) + .child(crate::tr!(ScheduleMessageTime)) + .child(Input::new(&time)) + .child(crate::tr!(ScheduleMessageDelivery)), + ) + .on_ok(move |_, window, cx| { + let raw = time_input.read(cx).value(); + let at = NaiveDateTime::parse_from_str(raw.trim(), "%Y-%m-%d %H:%M") + .ok() + .and_then(|local| Local.from_local_datetime(&local).single()) + .map(|at| at.timestamp_millis()) + .filter(|at| *at > wacore::time::now_millis()); + let Some(at) = at else { + let _ = app.update(cx, |app, cx| { + app.notify_user( + crate::tr!(ScheduleMessageInvalidTime), + Tone::Problem, + cx, + ); + }); + return false; + }; + let window = window.window_handle(); + let composer = composer.clone(); + let jid = jid.clone(); + let draft = draft.clone(); + let _ = app.update(cx, |app, cx| { + if app.selected_chat.as_deref() != Some(jid.as_str()) { + return; + } + let Some(session) = app + .client + .as_ref() + .filter(|session| session.account() == account) + else { + return; + }; + let reply = session.schedule_message(jid.clone(), draft.clone(), at); + cx.spawn(async move |app, cx| { + let result = reply + .await + .map_err(|error| error.to_string()) + .and_then(|result| result.map_err(|error| error.to_string())); + let _ = app.update(cx, |app, cx| match result { + Ok(()) => { + if app.selected_chat.as_deref() == Some(jid.as_str()) + && app + .client + .as_ref() + .is_some_and(|session| session.account() == account) + { + let _ = window.update(cx, |_, window, cx| { + let _ = composer.update(cx, |view, cx| { + view.clear_scheduled_draft(&draft, window, cx); + }); + }); + } + app.notify_user(crate::tr!(ScheduledMessage), Tone::Info, cx); + } + Err(error) => app.notify_user(error, Tone::Problem, cx), + }); + }) + .detach(); + }); + true + }) + }); + } +} + +impl WhatsAppApp { + pub(super) fn open_scheduled_messages(&mut self, window: &mut Window, cx: &mut Context) { + let (Some(jid), Some(session)) = (self.selected_chat.clone(), &self.client) else { + return; + }; + let account = session.account(); + let reply = session.scheduled_messages(jid.clone()); + let window = window.window_handle(); + cx.spawn(async move |app, cx| { + let result = reply + .await + .map_err(|error| error.to_string()) + .and_then(|result| result.map_err(|error| error.to_string())); + let _ = window.update(cx, |_, window, cx| { + let _ = app.update(cx, |view, cx| { + if view.selected_chat.as_deref() != Some(jid.as_str()) + || !view + .client + .as_ref() + .is_some_and(|session| session.account() == account) + { + return; + } + match result { + Ok(items) => { + let items = cx.new(|_| items); + show_scheduled_messages(window, cx, app.clone(), account, jid, items); + } + Err(error) => view.notify_user(error, Tone::Problem, cx), + } + }); + }); + }) + .detach(); + } +} + +fn show_scheduled_messages( + window: &mut Window, + cx: &mut gpui::App, + app: gpui::WeakEntity, + account: oxidezap_core::AccountId, + jid: String, + items: Entity>, +) { + use gpui::{InteractiveElement as _, StatefulInteractiveElement as _}; + use gpui_component::button::{Button, ButtonVariants as _}; + + window.open_alert_dialog(cx, move |dialog, _, cx| { + let metrics = cx.product().metrics; + let rows = items.read(cx); + let content = div() + .id("scheduled-messages-list") + .flex() + .flex_col() + .gap(metrics.space_md()) + .max_h(gpui::rems(20.)) + .overflow_y_scroll() + .children(rows.iter().map(|message| { + let id = message.id; + let app = app.clone(); + let jid = jid.clone(); + let items = items.clone(); + let time = chrono::DateTime::from_timestamp_millis(message.send_at_ms) + .map(|time| { + time.with_timezone(&Local) + .format("%Y-%m-%d %H:%M") + .to_string() + }) + .unwrap_or_default(); + div() + .flex() + .flex_col() + .gap(metrics.space_sm()) + .child(time) + .child(message.preview.clone()) + .child( + Button::new(format!("cancel-scheduled-{id}")) + .ghost() + .label(crate::tr!(CancelScheduledMessage)) + .on_click(move |_, _, cx| { + let jid = jid.clone(); + let items = items.clone(); + let _ = app.update(cx, |app, cx| { + let Some(session) = app + .client + .as_ref() + .filter(|session| session.account() == account) + else { + return; + }; + let reply = session.cancel_scheduled_message(jid, id); + cx.spawn(async move |app, cx| { + let result = reply + .await + .map_err(|error| error.to_string()) + .and_then(|result| { + result.map_err(|error| error.to_string()) + }); + let _ = app.update(cx, |app, cx| match result { + Ok(()) => items.update(cx, |items, cx| { + items.retain(|item| item.id != id); + cx.notify(); + }), + Err(error) => app.notify_user(error, Tone::Problem, cx), + }); + }) + .detach(); + }); + }), + ) + })); + let dialog = dialog + .title(crate::tr!(ScheduledMessages)) + .ok_text(crate::tr!(Close)); + if rows.is_empty() { + dialog.child(crate::tr!(NoScheduledMessages)) + } else { + dialog.child(content) + } + }); +} diff --git a/crates/gui/src/components/input_area_view.rs b/crates/gui/src/components/input_area_view.rs index 2e91ad26..195e4953 100644 --- a/crates/gui/src/components/input_area_view.rs +++ b/crates/gui/src/components/input_area_view.rs @@ -29,6 +29,8 @@ pub(crate) use composer_picker::{PickerItem, PickerRequest, PickerTab}; pub enum InputAreaEvent { /// User wants to send the current message SendMessage(String), + ScheduleMessage(String), + ListScheduledMessages, LoadPickerMedia(PickerTab), SendPickerMedia(PickerRequest), /// User picked an attachment category from the composer menu. @@ -347,6 +349,18 @@ impl InputAreaView { old } + pub(crate) fn clear_scheduled_draft( + &mut self, + text: &str, + window: &mut Window, + cx: &mut Context, + ) { + if !self.editing && self.reply.is_none() && self.input.read(cx).text() == text { + self.swap_text("", window, cx); + self.stop_typing_internal(cx); + } + } + /// Read, trim-check, clear and emit the composed message (Enter and the /// send button share this path). fn submit_input(&mut self, window: &mut Window, cx: &mut Context) { @@ -555,6 +569,7 @@ impl InputAreaView { .chars() .any(|c| !c.is_whitespace()); + let schedule_entity = entity.clone(); div() .key_context("MessageComposer") .on_action(|action: &Enter, _, cx| { @@ -629,6 +644,47 @@ impl InputAreaView { ), ) .child(self.render_picker(control, cx)) + .when(!self.editing, |row| { + let can_schedule = has_text && self.reply.is_none(); + row.child( + parts::icon_button( + "schedule-message", + Icon::new(ProductIcon::Clock), + crate::tr!(ScheduledMessages), + control, + ) + .dropdown_menu(move |menu, _, _| { + let list = schedule_entity.clone(); + let mut menu = + menu.item(PopupMenuItem::new(crate::tr!(ScheduledMessages)).on_click( + move |_, _, cx| { + list.update(cx, |_, cx| { + cx.emit(InputAreaEvent::ListScheduledMessages) + }); + }, + )); + if can_schedule { + let schedule = schedule_entity.clone(); + menu = menu.item( + PopupMenuItem::new(crate::tr!(ScheduleMessage)).on_click( + move |_, _, cx| { + schedule.update(cx, |view, cx| { + let text = view.input.read(cx).text().to_string(); + if !view.editing + && view.reply.is_none() + && !text.trim().is_empty() + { + cx.emit(InputAreaEvent::ScheduleMessage(text)); + } + }); + }, + ), + ); + } + menu + }), + ) + }) // Record or send, never both: which one is available follows // whether there is anything to send, the way every messaging // client behaves. diff --git a/crates/gui/src/i18n/catalog.rs b/crates/gui/src/i18n/catalog.rs index cca02207..72a3f152 100644 --- a/crates/gui/src/i18n/catalog.rs +++ b/crates/gui/src/i18n/catalog.rs @@ -7,6 +7,14 @@ catalog! { More => ("More", "Mais"); You => ("You", "Você"); TypeAMessage => ("Type a message", "Digite uma mensagem"); + ScheduledMessages => ("Scheduled messages", "Mensagens agendadas"); + NoScheduledMessages => ("No scheduled messages in this chat.", "Nenhuma mensagem agendada nesta conversa."); + CancelScheduledMessage => ("Cancel send", "Cancelar envio"); + ScheduleMessage => ("Schedule message", "Agendar mensagem"); + ScheduledMessage => ("Message scheduled", "Mensagem agendada"); + ScheduleMessageTime => ("Local time (YYYY-MM-DD HH:MM)", "Hora local (AAAA-MM-DD HH:MM)"); + ScheduleMessageInvalidTime => ("Enter an unambiguous future local time.", "Digite uma hora local futura e sem ambiguidade."); + ScheduleMessageDelivery => ("The message sends when OxideZap is running and connected.", "A mensagem será enviada quando o OxideZap estiver em execução e conectado."); SavingEdit => ("Saving edit...", "Salvando edição..."); EditingMessage => ("Editing message", "Editando mensagem"); Cancel => ("Cancel", "Cancelar"); diff --git a/crates/gui/src/session/frames.rs b/crates/gui/src/session/frames.rs index d4506de0..849e8335 100644 --- a/crates/gui/src/session/frames.rs +++ b/crates/gui/src/session/frames.rs @@ -381,6 +381,18 @@ impl<'a> Frames<'a> { None => debug!("a plugin listing arrived for {id}, which nobody is waiting on"), } } + DaemonMessage::ScheduledMessages { id, items } => { + match take_pending(self.pending, id) { + Some(Awaiting::ScheduledMessages(tx)) => { + let _ = tx.send(Ok(items)); + } + Some(waiting) => self.fail( + waiting, + &Failure::permanent("unexpected scheduled message listing"), + ), + None => debug!("a scheduled message listing arrived for a cancelled request"), + } + } DaemonMessage::SyncedStickers { id, items } => match take_pending(self.pending, id) { Some(Awaiting::SyncedStickers(tx)) => { let _ = tx.send(Ok(items)); diff --git a/crates/gui/src/session/mod.rs b/crates/gui/src/session/mod.rs index 670c1e86..b9579fc0 100644 --- a/crates/gui/src/session/mod.rs +++ b/crates/gui/src/session/mod.rs @@ -308,7 +308,10 @@ impl From<&oxidezap_ipc::ProtocolError> for Failure { /// drew is already able to render. type SyncedStickers = Vec; +type ScheduledMessages = Vec; + enum Awaiting { + ScheduledMessages(oneshot::Sender>), SyncedStickers(oneshot::Sender>), Account(oneshot::Sender>), /// A message mutation whose result must reach the action that opened it. @@ -396,6 +399,7 @@ impl Awaiting { Self::Mutation(tx) => tx.is_closed(), Self::StagedMutation { tx, .. } => tx.is_closed(), Self::SyncedStickers(tx) => tx.is_closed(), + Self::ScheduledMessages(tx) => tx.is_closed(), Self::Download(tx) => tx.is_closed(), Self::Storage(tx) => tx.is_closed(), Self::CallDevices(tx) => tx.is_closed(), @@ -435,6 +439,9 @@ impl Awaiting { Self::CallDevices(tx) => { let _ = tx.send(Err(detail.to_string())); } + Self::ScheduledMessages(tx) => { + let _ = tx.send(Err(failure.clone())); + } Self::SyncedStickers(tx) => { let _ = tx.send(Err(failure.clone())); } @@ -1144,6 +1151,49 @@ impl SessionHandle { ); } + pub fn scheduled_messages( + &self, + jid: String, + ) -> oneshot::Receiver> { + let (tx, rx) = oneshot::channel(); + self.ask( + ClientRequest::ListScheduledMessages { jid }, + Awaiting::ScheduledMessages(tx), + ); + rx + } + + pub fn cancel_scheduled_message( + &self, + jid: String, + scheduled_id: i64, + ) -> oneshot::Receiver> { + let (tx, rx) = oneshot::channel(); + self.ask( + ClientRequest::CancelScheduledMessage { jid, scheduled_id }, + Awaiting::Mutation(tx), + ); + rx + } + + pub fn schedule_message( + &self, + jid: String, + text: String, + send_at_ms: i64, + ) -> oneshot::Receiver> { + let (tx, rx) = oneshot::channel(); + self.ask( + ClientRequest::ScheduleMessage { + jid, + text, + send_at_ms, + }, + Awaiting::Mutation(tx), + ); + rx + } + pub fn sticker_library( &self, favorites: bool, diff --git a/crates/ipc/src/protocol.rs b/crates/ipc/src/protocol.rs index 04942797..b82e873f 100644 --- a/crates/ipc/src/protocol.rs +++ b/crates/ipc/src/protocol.rs @@ -420,6 +420,10 @@ pub enum DaemonMessage { protocol: u32, snapshot: Box, }, + ScheduledMessages { + id: RequestId, + items: Vec, + }, /// The linked account’s favorite or recently sent stickers. SyncedStickers { id: RequestId, @@ -1036,6 +1040,19 @@ pub enum ClientRequest { /// — and the serde working set — of every request. The wire is unchanged: /// `Box` is transparent to serde, and the round-trip test pins the bytes. SendText(Box), + /// Save a text message for the account to send on or after a UTC deadline. + ScheduleMessage { + jid: String, + text: String, + send_at_ms: i64, + }, + ListScheduledMessages { + jid: String, + }, + CancelScheduledMessage { + jid: String, + scheduled_id: i64, + }, SyncedStickers { favorites: bool, }, diff --git a/crates/ipc/src/transport.rs b/crates/ipc/src/transport.rs index b9a81e3a..f6879635 100644 --- a/crates/ipc/src/transport.rs +++ b/crates/ipc/src/transport.rs @@ -5,6 +5,8 @@ use std::path::PathBuf; /// Bumped whenever a frame changes shape in a way an older peer would /// misread. The daemon refuses a mismatch rather than guessing. /// +/// 44: The scheduling requests save, list and cancel account-scoped text sends. +/// /// 40: `ReconnectSession` interrupts the WhatsApp reconnect wait without /// replacing the account session. Older daemons cannot act on this request. /// @@ -291,7 +293,7 @@ use std::path::PathBuf; /// 43 adds the status, sticker-library and composer-media requests, among them /// `PublishStatusMedia`, which an older daemon would refuse as malformed after /// the file had been staged. -pub const PROTOCOL_VERSION: u32 = 43; +pub const PROTOCOL_VERSION: u32 = 44; /// Where the daemon's web bridge listens when nobody says otherwise. /// diff --git a/crates/session/src/whatsapp/mod.rs b/crates/session/src/whatsapp/mod.rs index 6a5dfa7d..f45c5e5d 100644 --- a/crates/session/src/whatsapp/mod.rs +++ b/crates/session/src/whatsapp/mod.rs @@ -27,6 +27,7 @@ mod mutations; /// Polls, profiles, contacts, channels, media fetch and history coverage. mod ops; mod profile; +mod scheduled_messages; /// Sends a scriptable front end asks for, read from daemon-local paths. mod sends; mod sticker_sync; diff --git a/crates/session/src/whatsapp/scheduled_messages.rs b/crates/session/src/whatsapp/scheduled_messages.rs new file mode 100644 index 00000000..d678295b --- /dev/null +++ b/crates/session/src/whatsapp/scheduled_messages.rs @@ -0,0 +1,83 @@ +use whatsapp_rust::wacore_binary::JidExt as _; + +use super::{Jid, WhatsAppClient}; + +impl WhatsAppClient { + pub async fn schedule_message( + &self, + jid: &str, + text: String, + send_at_ms: i64, + ) -> Result<(), String> { + let jid = jid + .parse::() + .map_err(|_| "invalid scheduled recipient")?; + if !(jid.is_group() || jid.is_pn() || jid.is_lid()) { + return Err("scheduled messages require a direct chat or group".into()); + } + if text.trim().is_empty() || text.len() > 32 * 1024 { + return Err("scheduled text must contain between 1 and 32,768 bytes".into()); + } + let delay = send_at_ms.saturating_sub(wacore::time::now_millis()); + if !(1..=366 * 24 * 60 * 60 * 1000).contains(&delay) { + return Err("scheduled time must be within the next year".into()); + } + let live = self.session.lock().await.clone().ok_or("no session yet")?; + if !live + .chat_store + .schedule_message(jid.to_non_ad_string(), text, send_at_ms) + .await + .map_err(|error| error.to_string())? + { + return Err("this account has 256 scheduled messages".into()); + } + Ok(()) + } + + pub async fn next_scheduled_message(&self) -> Result, String> { + let live = self.session.lock().await.clone().ok_or("no session yet")?; + live.chat_store + .next_scheduled_message() + .await + .map_err(|error| error.to_string()) + } + + pub async fn take_scheduled_message(&self) -> Result, String> { + let live = self.session.lock().await.clone().ok_or("no session yet")?; + live.chat_store + .take_scheduled_message(wacore::time::now_millis()) + .await + .map_err(|error| error.to_string()) + } +} + +impl WhatsAppClient { + pub fn scheduled_messages( + &self, + jid: String, + ) -> super::Task, String>> { + let session = self.session.clone(); + self.exec.spawn(async move { + let jid = jid.parse::().map_err(|_| "invalid chat")?; + let live = session.lock().await.clone().ok_or("no session yet")?; + live.chat_store + .scheduled_messages(jid.to_non_ad_string()) + .await + .map_err(|error| error.to_string()) + }) + } + + pub async fn cancel_scheduled_message(&self, jid: String, id: i64) -> Result<(), String> { + let jid = jid.parse::().map_err(|_| "invalid chat")?; + let live = self.session.lock().await.clone().ok_or("no session yet")?; + if !live + .chat_store + .cancel_scheduled_message(jid.to_non_ad_string(), id) + .await + .map_err(|error| error.to_string())? + { + return Err("the message is no longer scheduled".into()); + } + Ok(()) + } +} diff --git a/docs/gotchas.md b/docs/gotchas.md index fd3b6518..0ca54bf6 100644 --- a/docs/gotchas.md +++ b/docs/gotchas.md @@ -185,6 +185,15 @@ Non-obvious behaviour, and the reasoning behind it. Read the entry before changi Teardown gives accounts ten seconds to disconnect, followed by a separate three-second deadline for the runtime. On macOS the status item appears when Background is enabled, and a left click opens its menu. +- **Scheduled text lives in the account's SQLite queue.** The composer clock + schedules a direct or group message in local time and lists or cancels + pending messages in that chat. The daemon uses UTC deadlines. It attempts + overdue sends when the account reconnects, including after a restart. + The web daemon needs a running tab. A claim removes the row before the + regular send path starts, so a crash after the claim can lose the attempt + but a restart cannot dispatch it again. A network send failure uses the + regular failed message bubble and retry UI. Resetting or removing an + account deletes its schedule. - **A daemon the window starts must reset its own signals.** It inherits the window's signal state across the spawn, and the GUI's left SIGTERM and SIGINT without effect: the same binary stopped in a second from a shell and From 8273dfab0f627e1ea3bf56d1ca414f41585cfe57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 14:38:26 -0300 Subject: [PATCH 02/11] fix(chat): find scheduled messages across linked addresses --- crates/chat-store/src/schema.rs | 10 ++++ .../src/store/scheduled_messages.rs | 57 +++++++++---------- crates/chat-store/tests/scheduled_messages.rs | 19 +++++++ .../src/whatsapp/scheduled_messages.rs | 2 - 4 files changed, 57 insertions(+), 31 deletions(-) diff --git a/crates/chat-store/src/schema.rs b/crates/chat-store/src/schema.rs index cc5845c8..c03fc4bd 100644 --- a/crates/chat-store/src/schema.rs +++ b/crates/chat-store/src/schema.rs @@ -189,3 +189,13 @@ diesel::table! { received_at_ms -> BigInt, } } + +diesel::table! { + scheduled_messages (id) { + id -> BigInt, + device_id -> Integer, + jid -> Text, + text -> Text, + send_at_ms -> BigInt, + } +} diff --git a/crates/chat-store/src/store/scheduled_messages.rs b/crates/chat-store/src/store/scheduled_messages.rs index e3725f0e..92653c71 100644 --- a/crates/chat-store/src/store/scheduled_messages.rs +++ b/crates/chat-store/src/store/scheduled_messages.rs @@ -84,58 +84,57 @@ impl ChatStore { .await?; Ok(deadline.due) } -} -impl ChatStore { pub async fn scheduled_messages( &self, jid: String, ) -> Result> { - #[derive(QueryableByName)] - struct ScheduledRow { - #[diesel(sql_type = BigInt)] - id: i64, - #[diesel(sql_type = Text)] - preview: String, - #[diesel(sql_type = BigInt)] - send_at_ms: i64, - } + use crate::schema::scheduled_messages as scheduled; let account = self.device_id(); let rows = self .db() .read(move |conn| { - diesel::sql_query( - "SELECT id, substr(text, 1, 120) AS preview, send_at_ms FROM scheduled_messages - WHERE device_id = ? AND jid = ? ORDER BY send_at_ms, id", - ) - .bind::(account) - .bind::(jid) - .load::(conn) - .map_err(db_err) + let keys = crate::lid::chat_key_candidates(conn, account, &jid).map_err(db_err)?; + scheduled::table + .filter(scheduled::device_id.eq(account)) + .filter(scheduled::jid.eq_any(keys)) + .order((scheduled::send_at_ms.asc(), scheduled::id.asc())) + .select(( + scheduled::id, + diesel::dsl::sql::("substr(text, 1, 120)"), + scheduled::send_at_ms, + )) + .load::<(i64, String, i64)>(conn) + .map_err(db_err) }) .await?; Ok(rows .into_iter() - .map(|row| oxidezap_core::ScheduledMessage { - id: row.id, - preview: row.preview, - send_at_ms: row.send_at_ms, - }) + .map( + |(id, preview, send_at_ms)| oxidezap_core::ScheduledMessage { + id, + preview, + send_at_ms, + }, + ) .collect()) } pub async fn cancel_scheduled_message(&self, jid: String, id: i64) -> Result { + use crate::schema::scheduled_messages as scheduled; + let account = self.device_id(); let removed = self .db() .run(move |conn| { - diesel::sql_query( - "DELETE FROM scheduled_messages WHERE device_id = ? AND jid = ? AND id = ?", + let keys = crate::lid::chat_key_candidates(conn, account, &jid).map_err(db_err)?; + diesel::delete( + scheduled::table + .filter(scheduled::device_id.eq(account)) + .filter(scheduled::id.eq(id)) + .filter(scheduled::jid.eq_any(keys)), ) - .bind::(account) - .bind::(jid) - .bind::(id) .execute(conn) .map_err(db_err) }) diff --git a/crates/chat-store/tests/scheduled_messages.rs b/crates/chat-store/tests/scheduled_messages.rs index d0352851..9429ac6d 100644 --- a/crates/chat-store/tests/scheduled_messages.rs +++ b/crates/chat-store/tests/scheduled_messages.rs @@ -95,3 +95,22 @@ async fn cancellation_and_reset_only_affect_the_owning_account() { Some((PEER.into(), "retain me".into())) ); } + +#[tokio::test] +async fn a_chat_can_cancel_a_send_scheduled_under_its_previous_address() { + let (device, queue) = test_store().await; + queue + .schedule_message(PEER.into(), "pending before migration".into(), 100) + .await + .unwrap(); + add_lid_mapping(&device).await; + let rows = queue.scheduled_messages(PEER_LID.into()).await.unwrap(); + assert_eq!(rows.len(), 1); + assert!( + queue + .cancel_scheduled_message(PEER_LID.into(), rows[0].id) + .await + .unwrap() + ); + assert_eq!(queue.take_scheduled_message(100).await.unwrap(), None); +} diff --git a/crates/session/src/whatsapp/scheduled_messages.rs b/crates/session/src/whatsapp/scheduled_messages.rs index d678295b..b7c643d4 100644 --- a/crates/session/src/whatsapp/scheduled_messages.rs +++ b/crates/session/src/whatsapp/scheduled_messages.rs @@ -49,9 +49,7 @@ impl WhatsAppClient { .await .map_err(|error| error.to_string()) } -} -impl WhatsAppClient { pub fn scheduled_messages( &self, jid: String, From 2110a7b01f94603c627d089114b501bf476655d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 14:43:14 -0300 Subject: [PATCH 03/11] fix(gui): clear scheduled drafts after changing chats --- crates/gui/src/app/scheduled_messages.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/gui/src/app/scheduled_messages.rs b/crates/gui/src/app/scheduled_messages.rs index 98e0ba49..28371b15 100644 --- a/crates/gui/src/app/scheduled_messages.rs +++ b/crates/gui/src/app/scheduled_messages.rs @@ -86,17 +86,21 @@ impl WhatsAppApp { .and_then(|result| result.map_err(|error| error.to_string())); let _ = app.update(cx, |app, cx| match result { Ok(()) => { - if app.selected_chat.as_deref() == Some(jid.as_str()) - && app - .client - .as_ref() - .is_some_and(|session| session.account() == account) + if app + .client + .as_ref() + .is_some_and(|session| session.account() == account) { - let _ = window.update(cx, |_, window, cx| { - let _ = composer.update(cx, |view, cx| { - view.clear_scheduled_draft(&draft, window, cx); + if app.drafts.get(&jid) == Some(&draft) { + app.drafts.remove(&jid); + } + if app.selected_chat.as_deref() == Some(jid.as_str()) { + let _ = window.update(cx, |_, window, cx| { + let _ = composer.update(cx, |view, cx| { + view.clear_scheduled_draft(&draft, window, cx); + }); }); - }); + } } app.notify_user(crate::tr!(ScheduledMessage), Tone::Info, cx); } From 8739119f3a3fa48a880747d20dffd2fa9d204d03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 14:43:14 -0300 Subject: [PATCH 04/11] fix(chat): transfer scheduled text to history atomically --- .../src/store/scheduled_messages.rs | 69 ++++++++++++--- crates/chat-store/src/store/writer.rs | 4 +- crates/chat-store/tests/scheduled_messages.rs | 83 ++++++++++++++++--- crates/daemon/src/session_bridge/act.rs | 2 +- crates/daemon/src/session_bridge/mod.rs | 7 +- .../src/whatsapp/scheduled_messages.rs | 34 +++++++- docs/gotchas.md | 7 +- 7 files changed, 166 insertions(+), 40 deletions(-) diff --git a/crates/chat-store/src/store/scheduled_messages.rs b/crates/chat-store/src/store/scheduled_messages.rs index 92653c71..1326b3b9 100644 --- a/crates/chat-store/src/store/scheduled_messages.rs +++ b/crates/chat-store/src/store/scheduled_messages.rs @@ -32,7 +32,19 @@ impl ChatStore { Ok(inserted == 1) } - pub async fn take_scheduled_message(&self, now_ms: i64) -> Result> { + /// Transfer one due row to outgoing history before attempting network delivery. + pub async fn claim_scheduled_message( + &self, + now_ms: i64, + message_id: String, + ) -> Result> { + use super::{ + WriterMsg, + ack::DeferredAcks, + writer::{ChangeSet, apply_writer_msg, emit_changes}, + }; + use waproto::whatsapp as wa; + #[derive(QueryableByName)] struct ScheduledMessage { #[diesel(sql_type = Text)] @@ -42,23 +54,54 @@ impl ChatStore { } let account = self.device_id(); - let due = self + let claimed = self .db() .run(move |conn| { - diesel::sql_query( - "DELETE FROM scheduled_messages WHERE id = ( - SELECT id FROM scheduled_messages WHERE device_id = ?1 AND send_at_ms <= ?2 - ORDER BY send_at_ms, id LIMIT 1 - ) RETURNING jid, text", - ) - .bind::(account) - .bind::(now_ms) - .get_result::(conn) - .optional() + conn.immediate_transaction(|conn| { + let due = diesel::sql_query( + "DELETE FROM scheduled_messages WHERE id = ( + SELECT id FROM scheduled_messages WHERE device_id = ?1 AND send_at_ms <= ?2 + ORDER BY send_at_ms, id LIMIT 1 + ) RETURNING jid, text", + ) + .bind::(account) + .bind::(now_ms) + .get_result::(conn) + .optional()?; + let Some(due) = due else { + return Ok(None); + }; + let jid = due.jid.parse::().map_err(|error| { + diesel::result::Error::DeserializationError(Box::new(error)) + })?; + let mut message = wa::Message::default(); + message.conversation = Some(due.text.clone()); + let mut changes = ChangeSet::default(); + // The network has not seen this fresh stanza ID, so no + // deferred ACK for this send can exist. + apply_writer_msg( + conn, + account, + &WriterMsg::Outgoing { + chat: jid.clone(), + msg_id: message_id, + proto: waproto::codec::message_to_vec(&message), + kind: crate::materialize::message_kind(&message), + text: Some(due.text), + timestamp_ms: now_ms, + }, + &mut changes, + &mut DeferredAcks::default(), + )?; + Ok(Some((jid, message, changes))) + }) .map_err(db_err) }) .await?; - Ok(due.map(|message| (message.jid, message.text))) + Ok(claimed.map(|(jid, message, changes)| { + emit_changes(&self.changes, changes); + (jid, message) + })) } pub async fn next_scheduled_message(&self) -> Result> { diff --git a/crates/chat-store/src/store/writer.rs b/crates/chat-store/src/store/writer.rs index 2573c55a..d6817317 100644 --- a/crates/chat-store/src/store/writer.rs +++ b/crates/chat-store/src/store/writer.rs @@ -374,7 +374,7 @@ fn is_commit_barrier_error(error: &(dyn std::error::Error + 'static)) -> bool { false } -fn emit_changes(changes: &broadcast::Sender, cs: ChangeSet) { +pub(super) fn emit_changes(changes: &broadcast::Sender, cs: ChangeSet) { if cs.chats { let _ = changes.send(StoreChange::Chats); } @@ -388,7 +388,7 @@ fn emit_changes(changes: &broadcast::Sender, cs: ChangeSet) { } } -fn apply_writer_msg( +pub(super) fn apply_writer_msg( conn: &mut SqliteConnection, device_id: i32, msg: &WriterMsg, diff --git a/crates/chat-store/tests/scheduled_messages.rs b/crates/chat-store/tests/scheduled_messages.rs index 9429ac6d..c3a4a5b0 100644 --- a/crates/chat-store/tests/scheduled_messages.rs +++ b/crates/chat-store/tests/scheduled_messages.rs @@ -2,6 +2,14 @@ mod common; use common::*; +async fn claim(queue: &ChatStore, now_ms: i64, id: &str) -> Option<(String, String)> { + queue + .claim_scheduled_message(now_ms, id.into()) + .await + .unwrap() + .map(|(jid, message)| (jid.to_string(), message.conversation.unwrap())) +} + #[tokio::test] async fn scheduled_messages_survive_reopen_and_are_claimed_once() { let (device, queue) = test_store().await; @@ -21,22 +29,19 @@ async fn scheduled_messages_survive_reopen_and_are_claimed_once() { let queue = ChatStore::new(&device).await.unwrap(); assert_eq!(queue.next_scheduled_message().await.unwrap(), Some(100)); - assert_eq!(queue.take_scheduled_message(99).await.unwrap(), None); + assert_eq!(claim(&queue, 99, "before").await, None); let (one, two) = tokio::join!( - queue.take_scheduled_message(100), - queue.take_scheduled_message(100), + claim(&queue, 100, "first"), + claim(&queue, 100, "concurrent"), ); - let claims = [one.unwrap(), two.unwrap()] - .into_iter() - .flatten() - .collect::>(); + let claims = [one, two].into_iter().flatten().collect::>(); assert_eq!(claims, vec![(PEER.into(), "first".into())]); assert_eq!( - queue.take_scheduled_message(200).await.unwrap(), + claim(&queue, 200, "second").await, Some((PEER.into(), "second".into())) ); assert_eq!( - queue.take_scheduled_message(200).await.unwrap(), + claim(&queue, 200, "third").await, Some((GROUP.into(), "third".into())) ); assert_eq!(queue.next_scheduled_message().await.unwrap(), None); @@ -80,7 +85,7 @@ async fn cancellation_and_reset_only_affect_the_owning_account() { .await .unwrap() ); - assert_eq!(queue.take_scheduled_message(100).await.unwrap(), None); + assert_eq!(claim(&queue, 100, "cancelled").await, None); drop(queue); device @@ -91,7 +96,7 @@ async fn cancellation_and_reset_only_affect_the_owning_account() { let queue = ChatStore::new(&device).await.unwrap(); assert_eq!(queue.next_scheduled_message().await.unwrap(), None); assert_eq!( - other.take_scheduled_message(100).await.unwrap(), + claim(&other, 100, "other").await, Some((PEER.into(), "retain me".into())) ); } @@ -112,5 +117,59 @@ async fn a_chat_can_cancel_a_send_scheduled_under_its_previous_address() { .await .unwrap() ); - assert_eq!(queue.take_scheduled_message(100).await.unwrap(), None); + assert_eq!(claim(&queue, 100, "cancelled").await, None); +} + +#[tokio::test] +async fn failed_outgoing_insert_leaves_the_due_message_scheduled() { + let (device, queue) = test_store().await; + queue + .schedule_message(PEER.into(), "keep me".into(), 100) + .await + .unwrap(); + device + .shared() + .run(|conn| { + diesel::sql_query( + "CREATE TRIGGER refuse_scheduled_insert BEFORE INSERT ON messages + BEGIN SELECT RAISE(ABORT, 'forced outgoing write failure'); END", + ) + .execute(conn) + .map_err(db_err) + }) + .await + .unwrap(); + + assert!( + queue + .claim_scheduled_message(100, "failed".into()) + .await + .is_err() + ); + assert_eq!(queue.next_scheduled_message().await.unwrap(), Some(100)); + assert_eq!( + queue.scheduled_messages(PEER.into()).await.unwrap()[0].preview, + "keep me" + ); + + device + .shared() + .run(|conn| { + diesel::sql_query("DROP TRIGGER refuse_scheduled_insert") + .execute(conn) + .map_err(db_err) + }) + .await + .unwrap(); + assert_eq!( + claim(&queue, 100, "recorded").await, + Some((PEER.into(), "keep me".into())) + ); + let outgoing = queue + .message(&jid(PEER), "recorded") + .await + .unwrap() + .unwrap(); + assert_eq!(outgoing.text.as_deref(), Some("keep me")); + assert_eq!(queue.next_scheduled_message().await.unwrap(), None); } diff --git a/crates/daemon/src/session_bridge/act.rs b/crates/daemon/src/session_bridge/act.rs index 90ff87e6..de4fd244 100644 --- a/crates/daemon/src/session_bridge/act.rs +++ b/crates/daemon/src/session_bridge/act.rs @@ -2377,7 +2377,7 @@ fn answered(id: RequestId, result: Result) -> Stri /// A millisecond timestamp alone collides on fast double-sends, and the /// session renames the bubble by this id when the server assigns the real /// one, so a collision would rename the wrong message. -pub(super) fn next_local_id() -> String { +fn next_local_id() -> String { use portable_atomic::AtomicU64; use std::sync::atomic::Ordering; static SEQ: AtomicU64 = AtomicU64::new(0); diff --git a/crates/daemon/src/session_bridge/mod.rs b/crates/daemon/src/session_bridge/mod.rs index 0c719b1a..e57fcca9 100644 --- a/crates/daemon/src/session_bridge/mod.rs +++ b/crates/daemon/src/session_bridge/mod.rs @@ -757,11 +757,8 @@ impl Bridge { self.next_scheduled = Some(wacore::time::now_millis().saturating_add(1_000)); return; }; - match client.take_scheduled_message().await { - Ok(Some((jid, text))) => act::hold( - permit, - [client.send_message(&jid, &text, act::next_local_id(), None)], - ), + match client.send_scheduled_message().await { + Ok(Some(task)) => act::hold(permit, [task]), Ok(None) => {} Err(error) => { log::warn!("could not claim a scheduled message: {error}"); diff --git a/crates/session/src/whatsapp/scheduled_messages.rs b/crates/session/src/whatsapp/scheduled_messages.rs index b7c643d4..f283f6a7 100644 --- a/crates/session/src/whatsapp/scheduled_messages.rs +++ b/crates/session/src/whatsapp/scheduled_messages.rs @@ -42,12 +42,38 @@ impl WhatsAppClient { .map_err(|error| error.to_string()) } - pub async fn take_scheduled_message(&self) -> Result, String> { + pub async fn send_scheduled_message(&self) -> Result>, String> { let live = self.session.lock().await.clone().ok_or("no session yet")?; - live.chat_store - .take_scheduled_message(wacore::time::now_millis()) + let id = live.client.generate_message_id(); + let Some((jid, message)) = live + .chat_store + .claim_scheduled_message(wacore::time::now_millis(), id.to_string()) .await - .map_err(|error| error.to_string()) + .map_err(|error| error.to_string())? + else { + return Ok(None); + }; + if jid.is_group() { + live.resolve_chat_names + .request_named([jid.to_non_ad_string()]); + } + let ui_sender = self.ui_sender.clone(); + Ok(Some(self.exec.spawn(async move { + let options = whatsapp_rust::SendOptions::default().with_message_id(id.clone()); + if let Err(error) = live + .client + .send(whatsapp_rust::SendRequest::new(&jid, message).with_options(options)) + .await + { + super::mark_send_failed(&live.chat_store, &jid, id.as_str()); + super::notify_send_failed( + &ui_sender, + &jid.to_string(), + id.as_str(), + error.to_string(), + ); + } + }))) } pub fn scheduled_messages( diff --git a/docs/gotchas.md b/docs/gotchas.md index 0ca54bf6..b1cf27c8 100644 --- a/docs/gotchas.md +++ b/docs/gotchas.md @@ -189,9 +189,10 @@ Non-obvious behaviour, and the reasoning behind it. Read the entry before changi schedules a direct or group message in local time and lists or cancels pending messages in that chat. The daemon uses UTC deadlines. It attempts overdue sends when the account reconnects, including after a restart. - The web daemon needs a running tab. A claim removes the row before the - regular send path starts, so a crash after the claim can lose the attempt - but a restart cannot dispatch it again. A network send failure uses the + The web daemon needs a running tab. The claim replaces the scheduled row with an + outgoing history row in one transaction. After a crash between that + commit and delivery, the message remains in history and is not sent + again automatically. A network send failure uses the regular failed message bubble and retry UI. Resetting or removing an account deletes its schedule. - **A daemon the window starts must reset its own signals.** It inherits the From 4437f9bd4336ca7191daec0d1068c7297183bc3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 15:10:40 -0300 Subject: [PATCH 05/11] refactor(chat): remove built-in message scheduling --- .../down.sql | 1 - .../up.sql | 9 - crates/chat-store/src/schema.rs | 10 - crates/chat-store/src/store/mod.rs | 1 - .../src/store/scheduled_messages.rs | 187 -------------- crates/chat-store/src/store/writer.rs | 4 +- crates/chat-store/tests/scheduled_messages.rs | 175 ------------- crates/core/src/lib.rs | 8 - crates/daemon/src/server/requests.rs | 41 --- crates/daemon/src/server/tests.rs | 22 -- crates/daemon/src/session_bridge/act.rs | 46 +--- crates/daemon/src/session_bridge/action.rs | 17 -- crates/daemon/src/session_bridge/mod.rs | 54 ---- crates/gui/src/app/mod.rs | 5 - crates/gui/src/app/scheduled_messages.rs | 239 ------------------ crates/gui/src/components/input_area_view.rs | 56 ---- crates/gui/src/i18n/catalog.rs | 8 - crates/gui/src/session/frames.rs | 12 - crates/gui/src/session/mod.rs | 50 ---- crates/ipc/src/protocol.rs | 17 -- crates/ipc/src/transport.rs | 4 +- crates/session/src/whatsapp/mod.rs | 1 - .../src/whatsapp/scheduled_messages.rs | 107 -------- docs/gotchas.md | 10 - 24 files changed, 4 insertions(+), 1080 deletions(-) delete mode 100644 crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql delete mode 100644 crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql delete mode 100644 crates/chat-store/src/store/scheduled_messages.rs delete mode 100644 crates/chat-store/tests/scheduled_messages.rs delete mode 100644 crates/gui/src/app/scheduled_messages.rs delete mode 100644 crates/session/src/whatsapp/scheduled_messages.rs diff --git a/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql b/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql deleted file mode 100644 index bfe988c3..00000000 --- a/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE scheduled_messages; diff --git a/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql b/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql deleted file mode 100644 index 1d75af10..00000000 --- a/crates/chat-store/migrations/2026-11-18-000000_scheduled_messages/up.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE scheduled_messages ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - device_id INTEGER NOT NULL REFERENCES device(id) ON DELETE CASCADE, - jid TEXT NOT NULL, - text TEXT NOT NULL, - send_at_ms BIGINT NOT NULL -); - -CREATE INDEX scheduled_messages_due ON scheduled_messages(device_id, send_at_ms, id); diff --git a/crates/chat-store/src/schema.rs b/crates/chat-store/src/schema.rs index c03fc4bd..cc5845c8 100644 --- a/crates/chat-store/src/schema.rs +++ b/crates/chat-store/src/schema.rs @@ -189,13 +189,3 @@ diesel::table! { received_at_ms -> BigInt, } } - -diesel::table! { - scheduled_messages (id) { - id -> BigInt, - device_id -> Integer, - jid -> Text, - text -> Text, - send_at_ms -> BigInt, - } -} diff --git a/crates/chat-store/src/store/mod.rs b/crates/chat-store/src/store/mod.rs index 2de1fd21..49232fa0 100644 --- a/crates/chat-store/src/store/mod.rs +++ b/crates/chat-store/src/store/mod.rs @@ -28,7 +28,6 @@ mod receipt; mod recovery; pub(crate) mod retirement; mod revoke; -mod scheduled_messages; pub(crate) mod shared_history; mod writer; diff --git a/crates/chat-store/src/store/scheduled_messages.rs b/crates/chat-store/src/store/scheduled_messages.rs deleted file mode 100644 index 1326b3b9..00000000 --- a/crates/chat-store/src/store/scheduled_messages.rs +++ /dev/null @@ -1,187 +0,0 @@ -use diesel::prelude::*; -use diesel::sql_types::{BigInt, Integer, Text}; - -use super::ChatStore; -use crate::error::{Result, db_err}; - -impl ChatStore { - pub async fn schedule_message( - &self, - jid: String, - text: String, - send_at_ms: i64, - ) -> Result { - let account = self.device_id(); - let inserted = self - .db() - .run(move |conn| { - diesel::sql_query( - "INSERT INTO scheduled_messages (device_id, jid, text, send_at_ms) - SELECT ?1, ?2, ?3, ?4 WHERE ( - SELECT COUNT(*) FROM scheduled_messages WHERE device_id = ?1 - ) < 256", - ) - .bind::(account) - .bind::(jid) - .bind::(text) - .bind::(send_at_ms) - .execute(conn) - .map_err(db_err) - }) - .await?; - Ok(inserted == 1) - } - - /// Transfer one due row to outgoing history before attempting network delivery. - pub async fn claim_scheduled_message( - &self, - now_ms: i64, - message_id: String, - ) -> Result> { - use super::{ - WriterMsg, - ack::DeferredAcks, - writer::{ChangeSet, apply_writer_msg, emit_changes}, - }; - use waproto::whatsapp as wa; - - #[derive(QueryableByName)] - struct ScheduledMessage { - #[diesel(sql_type = Text)] - jid: String, - #[diesel(sql_type = Text)] - text: String, - } - - let account = self.device_id(); - let claimed = self - .db() - .run(move |conn| { - conn.immediate_transaction(|conn| { - let due = diesel::sql_query( - "DELETE FROM scheduled_messages WHERE id = ( - SELECT id FROM scheduled_messages WHERE device_id = ?1 AND send_at_ms <= ?2 - ORDER BY send_at_ms, id LIMIT 1 - ) RETURNING jid, text", - ) - .bind::(account) - .bind::(now_ms) - .get_result::(conn) - .optional()?; - let Some(due) = due else { - return Ok(None); - }; - let jid = due.jid.parse::().map_err(|error| { - diesel::result::Error::DeserializationError(Box::new(error)) - })?; - let mut message = wa::Message::default(); - message.conversation = Some(due.text.clone()); - let mut changes = ChangeSet::default(); - // The network has not seen this fresh stanza ID, so no - // deferred ACK for this send can exist. - apply_writer_msg( - conn, - account, - &WriterMsg::Outgoing { - chat: jid.clone(), - msg_id: message_id, - proto: waproto::codec::message_to_vec(&message), - kind: crate::materialize::message_kind(&message), - text: Some(due.text), - timestamp_ms: now_ms, - }, - &mut changes, - &mut DeferredAcks::default(), - )?; - Ok(Some((jid, message, changes))) - }) - .map_err(db_err) - }) - .await?; - Ok(claimed.map(|(jid, message, changes)| { - emit_changes(&self.changes, changes); - (jid, message) - })) - } - - pub async fn next_scheduled_message(&self) -> Result> { - use diesel::sql_types::Nullable; - - #[derive(QueryableByName)] - struct Deadline { - #[diesel(sql_type = Nullable)] - due: Option, - } - - let account = self.device_id(); - let deadline = self - .db() - .read(move |conn| { - diesel::sql_query( - "SELECT MIN(send_at_ms) AS due FROM scheduled_messages WHERE device_id = ?1", - ) - .bind::(account) - .get_result::(conn) - .map_err(db_err) - }) - .await?; - Ok(deadline.due) - } - - pub async fn scheduled_messages( - &self, - jid: String, - ) -> Result> { - use crate::schema::scheduled_messages as scheduled; - - let account = self.device_id(); - let rows = self - .db() - .read(move |conn| { - let keys = crate::lid::chat_key_candidates(conn, account, &jid).map_err(db_err)?; - scheduled::table - .filter(scheduled::device_id.eq(account)) - .filter(scheduled::jid.eq_any(keys)) - .order((scheduled::send_at_ms.asc(), scheduled::id.asc())) - .select(( - scheduled::id, - diesel::dsl::sql::("substr(text, 1, 120)"), - scheduled::send_at_ms, - )) - .load::<(i64, String, i64)>(conn) - .map_err(db_err) - }) - .await?; - Ok(rows - .into_iter() - .map( - |(id, preview, send_at_ms)| oxidezap_core::ScheduledMessage { - id, - preview, - send_at_ms, - }, - ) - .collect()) - } - - pub async fn cancel_scheduled_message(&self, jid: String, id: i64) -> Result { - use crate::schema::scheduled_messages as scheduled; - - let account = self.device_id(); - let removed = self - .db() - .run(move |conn| { - let keys = crate::lid::chat_key_candidates(conn, account, &jid).map_err(db_err)?; - diesel::delete( - scheduled::table - .filter(scheduled::device_id.eq(account)) - .filter(scheduled::id.eq(id)) - .filter(scheduled::jid.eq_any(keys)), - ) - .execute(conn) - .map_err(db_err) - }) - .await?; - Ok(removed == 1) - } -} diff --git a/crates/chat-store/src/store/writer.rs b/crates/chat-store/src/store/writer.rs index d6817317..2573c55a 100644 --- a/crates/chat-store/src/store/writer.rs +++ b/crates/chat-store/src/store/writer.rs @@ -374,7 +374,7 @@ fn is_commit_barrier_error(error: &(dyn std::error::Error + 'static)) -> bool { false } -pub(super) fn emit_changes(changes: &broadcast::Sender, cs: ChangeSet) { +fn emit_changes(changes: &broadcast::Sender, cs: ChangeSet) { if cs.chats { let _ = changes.send(StoreChange::Chats); } @@ -388,7 +388,7 @@ pub(super) fn emit_changes(changes: &broadcast::Sender, cs: ChangeS } } -pub(super) fn apply_writer_msg( +fn apply_writer_msg( conn: &mut SqliteConnection, device_id: i32, msg: &WriterMsg, diff --git a/crates/chat-store/tests/scheduled_messages.rs b/crates/chat-store/tests/scheduled_messages.rs deleted file mode 100644 index c3a4a5b0..00000000 --- a/crates/chat-store/tests/scheduled_messages.rs +++ /dev/null @@ -1,175 +0,0 @@ -mod common; - -use common::*; - -async fn claim(queue: &ChatStore, now_ms: i64, id: &str) -> Option<(String, String)> { - queue - .claim_scheduled_message(now_ms, id.into()) - .await - .unwrap() - .map(|(jid, message)| (jid.to_string(), message.conversation.unwrap())) -} - -#[tokio::test] -async fn scheduled_messages_survive_reopen_and_are_claimed_once() { - let (device, queue) = test_store().await; - queue - .schedule_message(PEER.into(), "second".into(), 200) - .await - .unwrap(); - queue - .schedule_message(PEER.into(), "first".into(), 100) - .await - .unwrap(); - queue - .schedule_message(GROUP.into(), "third".into(), 200) - .await - .unwrap(); - drop(queue); - - let queue = ChatStore::new(&device).await.unwrap(); - assert_eq!(queue.next_scheduled_message().await.unwrap(), Some(100)); - assert_eq!(claim(&queue, 99, "before").await, None); - let (one, two) = tokio::join!( - claim(&queue, 100, "first"), - claim(&queue, 100, "concurrent"), - ); - let claims = [one, two].into_iter().flatten().collect::>(); - assert_eq!(claims, vec![(PEER.into(), "first".into())]); - assert_eq!( - claim(&queue, 200, "second").await, - Some((PEER.into(), "second".into())) - ); - assert_eq!( - claim(&queue, 200, "third").await, - Some((GROUP.into(), "third".into())) - ); - assert_eq!(queue.next_scheduled_message().await.unwrap(), None); -} - -#[tokio::test] -async fn cancellation_and_reset_only_affect_the_owning_account() { - let (device, queue) = test_store().await; - let second = device.database().create_device().await.unwrap(); - let other = ChatStore::new(&second).await.unwrap(); - queue - .schedule_message(PEER.into(), "cancel me".into(), 100) - .await - .unwrap(); - queue - .schedule_message(PEER.into(), "reset me".into(), 200) - .await - .unwrap(); - other - .schedule_message(PEER.into(), "retain me".into(), 50) - .await - .unwrap(); - - let rows = queue.scheduled_messages(PEER.into()).await.unwrap(); - assert_eq!(rows.len(), 2); - assert!( - !other - .cancel_scheduled_message(PEER.into(), rows[0].id) - .await - .unwrap() - ); - assert!( - !queue - .cancel_scheduled_message(GROUP.into(), rows[0].id) - .await - .unwrap() - ); - assert!( - queue - .cancel_scheduled_message(PEER.into(), rows[0].id) - .await - .unwrap() - ); - assert_eq!(claim(&queue, 100, "cancelled").await, None); - - drop(queue); - device - .database() - .reset_device(device.device_id()) - .await - .unwrap(); - let queue = ChatStore::new(&device).await.unwrap(); - assert_eq!(queue.next_scheduled_message().await.unwrap(), None); - assert_eq!( - claim(&other, 100, "other").await, - Some((PEER.into(), "retain me".into())) - ); -} - -#[tokio::test] -async fn a_chat_can_cancel_a_send_scheduled_under_its_previous_address() { - let (device, queue) = test_store().await; - queue - .schedule_message(PEER.into(), "pending before migration".into(), 100) - .await - .unwrap(); - add_lid_mapping(&device).await; - let rows = queue.scheduled_messages(PEER_LID.into()).await.unwrap(); - assert_eq!(rows.len(), 1); - assert!( - queue - .cancel_scheduled_message(PEER_LID.into(), rows[0].id) - .await - .unwrap() - ); - assert_eq!(claim(&queue, 100, "cancelled").await, None); -} - -#[tokio::test] -async fn failed_outgoing_insert_leaves_the_due_message_scheduled() { - let (device, queue) = test_store().await; - queue - .schedule_message(PEER.into(), "keep me".into(), 100) - .await - .unwrap(); - device - .shared() - .run(|conn| { - diesel::sql_query( - "CREATE TRIGGER refuse_scheduled_insert BEFORE INSERT ON messages - BEGIN SELECT RAISE(ABORT, 'forced outgoing write failure'); END", - ) - .execute(conn) - .map_err(db_err) - }) - .await - .unwrap(); - - assert!( - queue - .claim_scheduled_message(100, "failed".into()) - .await - .is_err() - ); - assert_eq!(queue.next_scheduled_message().await.unwrap(), Some(100)); - assert_eq!( - queue.scheduled_messages(PEER.into()).await.unwrap()[0].preview, - "keep me" - ); - - device - .shared() - .run(|conn| { - diesel::sql_query("DROP TRIGGER refuse_scheduled_insert") - .execute(conn) - .map_err(db_err) - }) - .await - .unwrap(); - assert_eq!( - claim(&queue, 100, "recorded").await, - Some((PEER.into(), "keep me".into())) - ); - let outgoing = queue - .message(&jid(PEER), "recorded") - .await - .unwrap() - .unwrap(); - assert_eq!(outgoing.text.as_deref(), Some("keep me")); - assert_eq!(queue.next_scheduled_message().await.unwrap(), None); -} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index f84ad46c..ac224574 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -83,11 +83,3 @@ pub use video::{CallVideo, CallVideoFrame, VideoStream}; mod business; pub use business::{BusinessAction, BusinessButton, BusinessContent, BusinessKind}; - -/// A pending text message preview for the scheduling dialog. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub struct ScheduledMessage { - pub id: i64, - pub preview: String, - pub send_at_ms: i64, -} diff --git a/crates/daemon/src/server/requests.rs b/crates/daemon/src/server/requests.rs index 47931db2..7904a720 100644 --- a/crates/daemon/src/server/requests.rs +++ b/crates/daemon/src/server/requests.rs @@ -103,47 +103,6 @@ pub(super) async fn handle_request( ClientRequest::SendText(request) => { acted(dispatch(hub, commands, Action::SendText(*request)).await) } - ClientRequest::ScheduleMessage { - jid, - text, - send_at_ms, - } => acted( - dispatch( - hub, - commands, - Action::ScheduleMessage { - jid, - text, - send_at_ms, - }, - ) - .await, - ), - ClientRequest::CancelScheduledMessage { jid, scheduled_id } => acted( - dispatch( - hub, - commands, - Action::CancelScheduledMessage { jid, scheduled_id }, - ) - .await, - ), - ClientRequest::ListScheduledMessages { jid } => { - let id = match addressed(id, "listing scheduled messages needs an id") { - Ok(id) => id, - Err(refusal) => return refusal, - }; - out_of_band( - hub, - commands, - id, - Action::ListScheduledMessages { - id, - jid, - answer_to: outbox.clone(), - }, - ) - .await - } ClientRequest::SyncedStickers { favorites } => { let id = match addressed(id, "sticker sync needs an id to answer under") { Ok(id) => id, diff --git a/crates/daemon/src/server/tests.rs b/crates/daemon/src/server/tests.rs index cfc29bca..c5fef113 100644 --- a/crates/daemon/src/server/tests.rs +++ b/crates/daemon/src/server/tests.rs @@ -750,28 +750,6 @@ async fn a_command_reaches_the_session_rather_than_being_refused() { )); } -#[tokio::test] -async fn an_offline_account_can_schedule_a_text_message() { - let hub = StateHub::for_account(oxidezap_core::AccountId::LEGACY); - let (commands, taken) = bridge(CommandOutcome::Accepted); - let deadline = 2_100_000_000_000; - let request = bare(ClientRequest::ScheduleMessage { - jid: "120363000000000001@g.us".into(), - text: "on time".into(), - send_at_ms: deadline, - }); - let answer = handle_request(request, &hub, &no_plugins(), &commands, &outbox()).await; - assert!(matches!( - parse(answer.frame), - DaemonMessage::Accepted { .. } - )); - assert!(matches!( - taken.await.unwrap(), - Some(Action::ScheduleMessage { jid, text, send_at_ms }) - if jid == "120363000000000001@g.us" && text == "on time" && send_at_ms == deadline - )); -} - /// The payload moves rather than being unpacked and rebuilt, so what the /// session is handed is the struct the client sent. A field dropped between /// the two compiles and arrives as a document called "file" with no type on diff --git a/crates/daemon/src/session_bridge/act.rs b/crates/daemon/src/session_bridge/act.rs index de4fd244..52ef535d 100644 --- a/crates/daemon/src/session_bridge/act.rs +++ b/crates/daemon/src/session_bridge/act.rs @@ -126,23 +126,6 @@ impl Bridge { }); None } - Action::ListScheduledMessages { id, jid, answer_to } => { - let Some(permit) = self.permit() else { - let _ = reply.send(too_busy()); - return None; - }; - let task = client.scheduled_messages(jid); - oxidezap_session::spawn(async move { - let result = match task.await { - Ok(Ok(items)) => Ok(DaemonMessage::ScheduledMessages { id, items }), - other => mutation_answer(id, other), - }; - answer_now(&answer_to, answered(id, result)); - let _ = reply.send(CommandOutcome::Accepted); - drop(permit); - }); - None - } Action::SyncedStickers { id, favorites, @@ -1590,33 +1573,9 @@ impl Bridge { | Action::PublishStatus { .. } | Action::PublishStatusMedia { .. } | Action::SyncedStickers { .. } - | Action::ListScheduledMessages { .. } | Action::ReuseComposerMedia { .. } => { unreachable!("addressed actions are handled in begin_slow") } - Action::ScheduleMessage { - jid, - text, - send_at_ms, - } => match client.schedule_message(&jid, text, send_at_ms).await { - Ok(()) => { - self.next_scheduled = Some( - self.next_scheduled - .map_or(send_at_ms, |current| current.min(send_at_ms)), - ); - CommandOutcome::Accepted - } - Err(error) => CommandOutcome::Refused(error), - }, - Action::CancelScheduledMessage { jid, scheduled_id } => { - match client.cancel_scheduled_message(jid, scheduled_id).await { - Ok(()) => { - self.refresh_schedule(client).await; - CommandOutcome::Accepted - } - Err(error) => CommandOutcome::Refused(error), - } - } Action::SendText(oxidezap_ipc::SendText { jid, text, @@ -2239,10 +2198,7 @@ impl Bridge { /// where it was taken; a task that outlives this one holds it until every /// handle has resolved. `JoinHandle` errors are the session's runtime going /// away, which is a shutdown, not something to report. -pub(super) fn hold( - permit: OwnedSemaphorePermit, - work: [oxidezap_session::Task<()>; N], -) { +fn hold(permit: OwnedSemaphorePermit, work: [oxidezap_session::Task<()>; N]) { oxidezap_session::spawn(async move { for handle in work { let _ = handle.await; diff --git a/crates/daemon/src/session_bridge/action.rs b/crates/daemon/src/session_bridge/action.rs index 01557abf..dffd4f98 100644 --- a/crates/daemon/src/session_bridge/action.rs +++ b/crates/daemon/src/session_bridge/action.rs @@ -24,20 +24,6 @@ use oxidezap_ipc::{CallAction, RequestId}; #[derive(Debug)] pub enum Action { SendText(oxidezap_ipc::SendText), - ScheduleMessage { - jid: String, - text: String, - send_at_ms: i64, - }, - ListScheduledMessages { - id: RequestId, - jid: String, - answer_to: Outbox, - }, - CancelScheduledMessage { - jid: String, - scheduled_id: i64, - }, SyncedStickers { id: RequestId, favorites: bool, @@ -271,9 +257,6 @@ impl Action { _ => !matches!( self, Self::CallDevices { .. } - | Self::ScheduleMessage { .. } - | Self::ListScheduledMessages { .. } - | Self::CancelScheduledMessage { .. } | Self::ReloadHistory | Self::ReconnectSession | Self::RefreshVideo diff --git a/crates/daemon/src/session_bridge/mod.rs b/crates/daemon/src/session_bridge/mod.rs index e57fcca9..74f38932 100644 --- a/crates/daemon/src/session_bridge/mod.rs +++ b/crates/daemon/src/session_bridge/mod.rs @@ -344,11 +344,7 @@ pub async fn run( let mute_timer = wait_for_mute_expiry(bridge.hub.clone()); tokio::pin!(mute_timer); loop { - let was_connected = bridge.hub.connection().is_connected(); tokio::select! { - () = wait_for_schedule(bridge.next_scheduled.filter(|_| was_connected)) => { - bridge.send_scheduled(&client).await; - } () = &mut mute_timer => { mute_timer.set(wait_for_mute_expiry(bridge.hub.clone())); }, @@ -361,9 +357,6 @@ pub async fn run( // reopens this account. No reset/removal is requested. Answer::Restart => break, } - if !was_connected && bridge.hub.connection().is_connected() { - bridge.refresh_schedule(&client).await; - } mute_timer.set(wait_for_mute_expiry(bridge.hub.clone())); } // The session dropped its sender: the run loop is gone and no @@ -683,7 +676,6 @@ const FORGET_GRACE: std::time::Duration = std::time::Duration::from_secs(30); /// Everything the event loop carries between one event and the next. struct Bridge { devices: call_devices::Devices, - next_scheduled: Option, hub: Arc, lifecycle: RuntimeLifecycle, /// The plugins, fed the same events the front ends get. @@ -723,52 +715,7 @@ struct Bridge { avatar_recorder: oxidezap_session::AvatarRecorder, } -async fn wait_for_schedule(deadline: Option) { - let Some(deadline) = deadline else { - return std::future::pending().await; - }; - let delay = deadline - .saturating_sub(wacore::time::now_millis()) - .clamp(0, 60_000); - if delay > 0 { - oxidezap_platform::sleep(std::time::Duration::from_millis(delay as u64)).await; - } -} - impl Bridge { - async fn refresh_schedule(&mut self, client: &WhatsAppClient) { - self.next_scheduled = match client.next_scheduled_message().await { - Ok(next) => next, - Err(error) => { - log::warn!("could not read scheduled messages: {error}"); - Some(wacore::time::now_millis().saturating_add(5_000)) - } - }; - } - - async fn send_scheduled(&mut self, client: &WhatsAppClient) { - if self - .next_scheduled - .is_some_and(|due| due > wacore::time::now_millis()) - { - return; - } - let Some(permit) = self.permit() else { - self.next_scheduled = Some(wacore::time::now_millis().saturating_add(1_000)); - return; - }; - match client.send_scheduled_message().await { - Ok(Some(task)) => act::hold(permit, [task]), - Ok(None) => {} - Err(error) => { - log::warn!("could not claim a scheduled message: {error}"); - self.next_scheduled = Some(wacore::time::now_millis().saturating_add(5_000)); - return; - } - } - self.refresh_schedule(client).await; - } - #[cfg(test)] fn new(hub: Arc, plugins: Arc) -> Self { // No session behind it: these tests fold events without opening a @@ -799,7 +746,6 @@ impl Bridge { Self { devices: call_devices::Devices::new(&hub), - next_scheduled: None, hub, lifecycle, plugins, diff --git a/crates/gui/src/app/mod.rs b/crates/gui/src/app/mod.rs index a0736489..ad4600f3 100644 --- a/crates/gui/src/app/mod.rs +++ b/crates/gui/src/app/mod.rs @@ -29,7 +29,6 @@ mod paging; mod plugins_ctl; mod recording; mod recovery; -mod scheduled_messages; mod search; mod settings; mod status; @@ -3277,10 +3276,6 @@ impl WhatsAppApp { self.send_message(text, cx); } } - InputAreaEvent::ListScheduledMessages => self.open_scheduled_messages(window, cx), - InputAreaEvent::ScheduleMessage(text) => { - self.open_schedule_message(text, input_area, window, cx); - } InputAreaEvent::LoadPickerMedia(tab) => self.load_picker_media(*tab, input_area, cx), InputAreaEvent::SendPickerMedia(request) => self.send_picker_media(request, cx), InputAreaEvent::AttachFiles(category) => { diff --git a/crates/gui/src/app/scheduled_messages.rs b/crates/gui/src/app/scheduled_messages.rs deleted file mode 100644 index 28371b15..00000000 --- a/crates/gui/src/app/scheduled_messages.rs +++ /dev/null @@ -1,239 +0,0 @@ -use chrono::{Local, NaiveDateTime, TimeZone as _}; -use gpui::{AppContext as _, Context, Entity, ParentElement as _, Styled as _, Window, div}; -use gpui_component::{ - WindowExt as _, - input::{Input, InputState}, -}; - -use super::{WhatsAppApp, notices::Tone}; -use crate::components::InputAreaView; -use crate::theme::ActiveProductTheme as _; - -impl WhatsAppApp { - pub(super) fn open_schedule_message( - &mut self, - text: &str, - input_area: &Entity, - window: &mut Window, - cx: &mut Context, - ) { - let (Some(jid), Some(session)) = (self.selected_chat.clone(), &self.client) else { - return; - }; - let account = session.account(); - let time = cx.new(|cx| InputState::new(window, cx).placeholder("YYYY-MM-DD HH:MM")); - let draft = text.to_owned(); - let composer = input_area.downgrade(); - let app = cx.entity().downgrade(); - window.open_alert_dialog(cx, move |dialog, _, cx| { - let metrics = cx.product().metrics; - let time_input = time.clone(); - let jid = jid.clone(); - let draft = draft.clone(); - let composer = composer.clone(); - let app = app.clone(); - dialog - .confirm() - .title(crate::tr!(ScheduleMessage)) - .ok_text(crate::tr!(ScheduleMessage)) - .cancel_text(crate::tr!(Cancel)) - .child( - div() - .flex() - .flex_col() - .gap(metrics.space_md()) - .child(crate::tr!(ScheduleMessageTime)) - .child(Input::new(&time)) - .child(crate::tr!(ScheduleMessageDelivery)), - ) - .on_ok(move |_, window, cx| { - let raw = time_input.read(cx).value(); - let at = NaiveDateTime::parse_from_str(raw.trim(), "%Y-%m-%d %H:%M") - .ok() - .and_then(|local| Local.from_local_datetime(&local).single()) - .map(|at| at.timestamp_millis()) - .filter(|at| *at > wacore::time::now_millis()); - let Some(at) = at else { - let _ = app.update(cx, |app, cx| { - app.notify_user( - crate::tr!(ScheduleMessageInvalidTime), - Tone::Problem, - cx, - ); - }); - return false; - }; - let window = window.window_handle(); - let composer = composer.clone(); - let jid = jid.clone(); - let draft = draft.clone(); - let _ = app.update(cx, |app, cx| { - if app.selected_chat.as_deref() != Some(jid.as_str()) { - return; - } - let Some(session) = app - .client - .as_ref() - .filter(|session| session.account() == account) - else { - return; - }; - let reply = session.schedule_message(jid.clone(), draft.clone(), at); - cx.spawn(async move |app, cx| { - let result = reply - .await - .map_err(|error| error.to_string()) - .and_then(|result| result.map_err(|error| error.to_string())); - let _ = app.update(cx, |app, cx| match result { - Ok(()) => { - if app - .client - .as_ref() - .is_some_and(|session| session.account() == account) - { - if app.drafts.get(&jid) == Some(&draft) { - app.drafts.remove(&jid); - } - if app.selected_chat.as_deref() == Some(jid.as_str()) { - let _ = window.update(cx, |_, window, cx| { - let _ = composer.update(cx, |view, cx| { - view.clear_scheduled_draft(&draft, window, cx); - }); - }); - } - } - app.notify_user(crate::tr!(ScheduledMessage), Tone::Info, cx); - } - Err(error) => app.notify_user(error, Tone::Problem, cx), - }); - }) - .detach(); - }); - true - }) - }); - } -} - -impl WhatsAppApp { - pub(super) fn open_scheduled_messages(&mut self, window: &mut Window, cx: &mut Context) { - let (Some(jid), Some(session)) = (self.selected_chat.clone(), &self.client) else { - return; - }; - let account = session.account(); - let reply = session.scheduled_messages(jid.clone()); - let window = window.window_handle(); - cx.spawn(async move |app, cx| { - let result = reply - .await - .map_err(|error| error.to_string()) - .and_then(|result| result.map_err(|error| error.to_string())); - let _ = window.update(cx, |_, window, cx| { - let _ = app.update(cx, |view, cx| { - if view.selected_chat.as_deref() != Some(jid.as_str()) - || !view - .client - .as_ref() - .is_some_and(|session| session.account() == account) - { - return; - } - match result { - Ok(items) => { - let items = cx.new(|_| items); - show_scheduled_messages(window, cx, app.clone(), account, jid, items); - } - Err(error) => view.notify_user(error, Tone::Problem, cx), - } - }); - }); - }) - .detach(); - } -} - -fn show_scheduled_messages( - window: &mut Window, - cx: &mut gpui::App, - app: gpui::WeakEntity, - account: oxidezap_core::AccountId, - jid: String, - items: Entity>, -) { - use gpui::{InteractiveElement as _, StatefulInteractiveElement as _}; - use gpui_component::button::{Button, ButtonVariants as _}; - - window.open_alert_dialog(cx, move |dialog, _, cx| { - let metrics = cx.product().metrics; - let rows = items.read(cx); - let content = div() - .id("scheduled-messages-list") - .flex() - .flex_col() - .gap(metrics.space_md()) - .max_h(gpui::rems(20.)) - .overflow_y_scroll() - .children(rows.iter().map(|message| { - let id = message.id; - let app = app.clone(); - let jid = jid.clone(); - let items = items.clone(); - let time = chrono::DateTime::from_timestamp_millis(message.send_at_ms) - .map(|time| { - time.with_timezone(&Local) - .format("%Y-%m-%d %H:%M") - .to_string() - }) - .unwrap_or_default(); - div() - .flex() - .flex_col() - .gap(metrics.space_sm()) - .child(time) - .child(message.preview.clone()) - .child( - Button::new(format!("cancel-scheduled-{id}")) - .ghost() - .label(crate::tr!(CancelScheduledMessage)) - .on_click(move |_, _, cx| { - let jid = jid.clone(); - let items = items.clone(); - let _ = app.update(cx, |app, cx| { - let Some(session) = app - .client - .as_ref() - .filter(|session| session.account() == account) - else { - return; - }; - let reply = session.cancel_scheduled_message(jid, id); - cx.spawn(async move |app, cx| { - let result = reply - .await - .map_err(|error| error.to_string()) - .and_then(|result| { - result.map_err(|error| error.to_string()) - }); - let _ = app.update(cx, |app, cx| match result { - Ok(()) => items.update(cx, |items, cx| { - items.retain(|item| item.id != id); - cx.notify(); - }), - Err(error) => app.notify_user(error, Tone::Problem, cx), - }); - }) - .detach(); - }); - }), - ) - })); - let dialog = dialog - .title(crate::tr!(ScheduledMessages)) - .ok_text(crate::tr!(Close)); - if rows.is_empty() { - dialog.child(crate::tr!(NoScheduledMessages)) - } else { - dialog.child(content) - } - }); -} diff --git a/crates/gui/src/components/input_area_view.rs b/crates/gui/src/components/input_area_view.rs index 195e4953..2e91ad26 100644 --- a/crates/gui/src/components/input_area_view.rs +++ b/crates/gui/src/components/input_area_view.rs @@ -29,8 +29,6 @@ pub(crate) use composer_picker::{PickerItem, PickerRequest, PickerTab}; pub enum InputAreaEvent { /// User wants to send the current message SendMessage(String), - ScheduleMessage(String), - ListScheduledMessages, LoadPickerMedia(PickerTab), SendPickerMedia(PickerRequest), /// User picked an attachment category from the composer menu. @@ -349,18 +347,6 @@ impl InputAreaView { old } - pub(crate) fn clear_scheduled_draft( - &mut self, - text: &str, - window: &mut Window, - cx: &mut Context, - ) { - if !self.editing && self.reply.is_none() && self.input.read(cx).text() == text { - self.swap_text("", window, cx); - self.stop_typing_internal(cx); - } - } - /// Read, trim-check, clear and emit the composed message (Enter and the /// send button share this path). fn submit_input(&mut self, window: &mut Window, cx: &mut Context) { @@ -569,7 +555,6 @@ impl InputAreaView { .chars() .any(|c| !c.is_whitespace()); - let schedule_entity = entity.clone(); div() .key_context("MessageComposer") .on_action(|action: &Enter, _, cx| { @@ -644,47 +629,6 @@ impl InputAreaView { ), ) .child(self.render_picker(control, cx)) - .when(!self.editing, |row| { - let can_schedule = has_text && self.reply.is_none(); - row.child( - parts::icon_button( - "schedule-message", - Icon::new(ProductIcon::Clock), - crate::tr!(ScheduledMessages), - control, - ) - .dropdown_menu(move |menu, _, _| { - let list = schedule_entity.clone(); - let mut menu = - menu.item(PopupMenuItem::new(crate::tr!(ScheduledMessages)).on_click( - move |_, _, cx| { - list.update(cx, |_, cx| { - cx.emit(InputAreaEvent::ListScheduledMessages) - }); - }, - )); - if can_schedule { - let schedule = schedule_entity.clone(); - menu = menu.item( - PopupMenuItem::new(crate::tr!(ScheduleMessage)).on_click( - move |_, _, cx| { - schedule.update(cx, |view, cx| { - let text = view.input.read(cx).text().to_string(); - if !view.editing - && view.reply.is_none() - && !text.trim().is_empty() - { - cx.emit(InputAreaEvent::ScheduleMessage(text)); - } - }); - }, - ), - ); - } - menu - }), - ) - }) // Record or send, never both: which one is available follows // whether there is anything to send, the way every messaging // client behaves. diff --git a/crates/gui/src/i18n/catalog.rs b/crates/gui/src/i18n/catalog.rs index 72a3f152..cca02207 100644 --- a/crates/gui/src/i18n/catalog.rs +++ b/crates/gui/src/i18n/catalog.rs @@ -7,14 +7,6 @@ catalog! { More => ("More", "Mais"); You => ("You", "Você"); TypeAMessage => ("Type a message", "Digite uma mensagem"); - ScheduledMessages => ("Scheduled messages", "Mensagens agendadas"); - NoScheduledMessages => ("No scheduled messages in this chat.", "Nenhuma mensagem agendada nesta conversa."); - CancelScheduledMessage => ("Cancel send", "Cancelar envio"); - ScheduleMessage => ("Schedule message", "Agendar mensagem"); - ScheduledMessage => ("Message scheduled", "Mensagem agendada"); - ScheduleMessageTime => ("Local time (YYYY-MM-DD HH:MM)", "Hora local (AAAA-MM-DD HH:MM)"); - ScheduleMessageInvalidTime => ("Enter an unambiguous future local time.", "Digite uma hora local futura e sem ambiguidade."); - ScheduleMessageDelivery => ("The message sends when OxideZap is running and connected.", "A mensagem será enviada quando o OxideZap estiver em execução e conectado."); SavingEdit => ("Saving edit...", "Salvando edição..."); EditingMessage => ("Editing message", "Editando mensagem"); Cancel => ("Cancel", "Cancelar"); diff --git a/crates/gui/src/session/frames.rs b/crates/gui/src/session/frames.rs index 849e8335..d4506de0 100644 --- a/crates/gui/src/session/frames.rs +++ b/crates/gui/src/session/frames.rs @@ -381,18 +381,6 @@ impl<'a> Frames<'a> { None => debug!("a plugin listing arrived for {id}, which nobody is waiting on"), } } - DaemonMessage::ScheduledMessages { id, items } => { - match take_pending(self.pending, id) { - Some(Awaiting::ScheduledMessages(tx)) => { - let _ = tx.send(Ok(items)); - } - Some(waiting) => self.fail( - waiting, - &Failure::permanent("unexpected scheduled message listing"), - ), - None => debug!("a scheduled message listing arrived for a cancelled request"), - } - } DaemonMessage::SyncedStickers { id, items } => match take_pending(self.pending, id) { Some(Awaiting::SyncedStickers(tx)) => { let _ = tx.send(Ok(items)); diff --git a/crates/gui/src/session/mod.rs b/crates/gui/src/session/mod.rs index b9579fc0..670c1e86 100644 --- a/crates/gui/src/session/mod.rs +++ b/crates/gui/src/session/mod.rs @@ -308,10 +308,7 @@ impl From<&oxidezap_ipc::ProtocolError> for Failure { /// drew is already able to render. type SyncedStickers = Vec; -type ScheduledMessages = Vec; - enum Awaiting { - ScheduledMessages(oneshot::Sender>), SyncedStickers(oneshot::Sender>), Account(oneshot::Sender>), /// A message mutation whose result must reach the action that opened it. @@ -399,7 +396,6 @@ impl Awaiting { Self::Mutation(tx) => tx.is_closed(), Self::StagedMutation { tx, .. } => tx.is_closed(), Self::SyncedStickers(tx) => tx.is_closed(), - Self::ScheduledMessages(tx) => tx.is_closed(), Self::Download(tx) => tx.is_closed(), Self::Storage(tx) => tx.is_closed(), Self::CallDevices(tx) => tx.is_closed(), @@ -439,9 +435,6 @@ impl Awaiting { Self::CallDevices(tx) => { let _ = tx.send(Err(detail.to_string())); } - Self::ScheduledMessages(tx) => { - let _ = tx.send(Err(failure.clone())); - } Self::SyncedStickers(tx) => { let _ = tx.send(Err(failure.clone())); } @@ -1151,49 +1144,6 @@ impl SessionHandle { ); } - pub fn scheduled_messages( - &self, - jid: String, - ) -> oneshot::Receiver> { - let (tx, rx) = oneshot::channel(); - self.ask( - ClientRequest::ListScheduledMessages { jid }, - Awaiting::ScheduledMessages(tx), - ); - rx - } - - pub fn cancel_scheduled_message( - &self, - jid: String, - scheduled_id: i64, - ) -> oneshot::Receiver> { - let (tx, rx) = oneshot::channel(); - self.ask( - ClientRequest::CancelScheduledMessage { jid, scheduled_id }, - Awaiting::Mutation(tx), - ); - rx - } - - pub fn schedule_message( - &self, - jid: String, - text: String, - send_at_ms: i64, - ) -> oneshot::Receiver> { - let (tx, rx) = oneshot::channel(); - self.ask( - ClientRequest::ScheduleMessage { - jid, - text, - send_at_ms, - }, - Awaiting::Mutation(tx), - ); - rx - } - pub fn sticker_library( &self, favorites: bool, diff --git a/crates/ipc/src/protocol.rs b/crates/ipc/src/protocol.rs index b82e873f..04942797 100644 --- a/crates/ipc/src/protocol.rs +++ b/crates/ipc/src/protocol.rs @@ -420,10 +420,6 @@ pub enum DaemonMessage { protocol: u32, snapshot: Box, }, - ScheduledMessages { - id: RequestId, - items: Vec, - }, /// The linked account’s favorite or recently sent stickers. SyncedStickers { id: RequestId, @@ -1040,19 +1036,6 @@ pub enum ClientRequest { /// — and the serde working set — of every request. The wire is unchanged: /// `Box` is transparent to serde, and the round-trip test pins the bytes. SendText(Box), - /// Save a text message for the account to send on or after a UTC deadline. - ScheduleMessage { - jid: String, - text: String, - send_at_ms: i64, - }, - ListScheduledMessages { - jid: String, - }, - CancelScheduledMessage { - jid: String, - scheduled_id: i64, - }, SyncedStickers { favorites: bool, }, diff --git a/crates/ipc/src/transport.rs b/crates/ipc/src/transport.rs index f6879635..b9a81e3a 100644 --- a/crates/ipc/src/transport.rs +++ b/crates/ipc/src/transport.rs @@ -5,8 +5,6 @@ use std::path::PathBuf; /// Bumped whenever a frame changes shape in a way an older peer would /// misread. The daemon refuses a mismatch rather than guessing. /// -/// 44: The scheduling requests save, list and cancel account-scoped text sends. -/// /// 40: `ReconnectSession` interrupts the WhatsApp reconnect wait without /// replacing the account session. Older daemons cannot act on this request. /// @@ -293,7 +291,7 @@ use std::path::PathBuf; /// 43 adds the status, sticker-library and composer-media requests, among them /// `PublishStatusMedia`, which an older daemon would refuse as malformed after /// the file had been staged. -pub const PROTOCOL_VERSION: u32 = 44; +pub const PROTOCOL_VERSION: u32 = 43; /// Where the daemon's web bridge listens when nobody says otherwise. /// diff --git a/crates/session/src/whatsapp/mod.rs b/crates/session/src/whatsapp/mod.rs index f45c5e5d..6a5dfa7d 100644 --- a/crates/session/src/whatsapp/mod.rs +++ b/crates/session/src/whatsapp/mod.rs @@ -27,7 +27,6 @@ mod mutations; /// Polls, profiles, contacts, channels, media fetch and history coverage. mod ops; mod profile; -mod scheduled_messages; /// Sends a scriptable front end asks for, read from daemon-local paths. mod sends; mod sticker_sync; diff --git a/crates/session/src/whatsapp/scheduled_messages.rs b/crates/session/src/whatsapp/scheduled_messages.rs deleted file mode 100644 index f283f6a7..00000000 --- a/crates/session/src/whatsapp/scheduled_messages.rs +++ /dev/null @@ -1,107 +0,0 @@ -use whatsapp_rust::wacore_binary::JidExt as _; - -use super::{Jid, WhatsAppClient}; - -impl WhatsAppClient { - pub async fn schedule_message( - &self, - jid: &str, - text: String, - send_at_ms: i64, - ) -> Result<(), String> { - let jid = jid - .parse::() - .map_err(|_| "invalid scheduled recipient")?; - if !(jid.is_group() || jid.is_pn() || jid.is_lid()) { - return Err("scheduled messages require a direct chat or group".into()); - } - if text.trim().is_empty() || text.len() > 32 * 1024 { - return Err("scheduled text must contain between 1 and 32,768 bytes".into()); - } - let delay = send_at_ms.saturating_sub(wacore::time::now_millis()); - if !(1..=366 * 24 * 60 * 60 * 1000).contains(&delay) { - return Err("scheduled time must be within the next year".into()); - } - let live = self.session.lock().await.clone().ok_or("no session yet")?; - if !live - .chat_store - .schedule_message(jid.to_non_ad_string(), text, send_at_ms) - .await - .map_err(|error| error.to_string())? - { - return Err("this account has 256 scheduled messages".into()); - } - Ok(()) - } - - pub async fn next_scheduled_message(&self) -> Result, String> { - let live = self.session.lock().await.clone().ok_or("no session yet")?; - live.chat_store - .next_scheduled_message() - .await - .map_err(|error| error.to_string()) - } - - pub async fn send_scheduled_message(&self) -> Result>, String> { - let live = self.session.lock().await.clone().ok_or("no session yet")?; - let id = live.client.generate_message_id(); - let Some((jid, message)) = live - .chat_store - .claim_scheduled_message(wacore::time::now_millis(), id.to_string()) - .await - .map_err(|error| error.to_string())? - else { - return Ok(None); - }; - if jid.is_group() { - live.resolve_chat_names - .request_named([jid.to_non_ad_string()]); - } - let ui_sender = self.ui_sender.clone(); - Ok(Some(self.exec.spawn(async move { - let options = whatsapp_rust::SendOptions::default().with_message_id(id.clone()); - if let Err(error) = live - .client - .send(whatsapp_rust::SendRequest::new(&jid, message).with_options(options)) - .await - { - super::mark_send_failed(&live.chat_store, &jid, id.as_str()); - super::notify_send_failed( - &ui_sender, - &jid.to_string(), - id.as_str(), - error.to_string(), - ); - } - }))) - } - - pub fn scheduled_messages( - &self, - jid: String, - ) -> super::Task, String>> { - let session = self.session.clone(); - self.exec.spawn(async move { - let jid = jid.parse::().map_err(|_| "invalid chat")?; - let live = session.lock().await.clone().ok_or("no session yet")?; - live.chat_store - .scheduled_messages(jid.to_non_ad_string()) - .await - .map_err(|error| error.to_string()) - }) - } - - pub async fn cancel_scheduled_message(&self, jid: String, id: i64) -> Result<(), String> { - let jid = jid.parse::().map_err(|_| "invalid chat")?; - let live = self.session.lock().await.clone().ok_or("no session yet")?; - if !live - .chat_store - .cancel_scheduled_message(jid.to_non_ad_string(), id) - .await - .map_err(|error| error.to_string())? - { - return Err("the message is no longer scheduled".into()); - } - Ok(()) - } -} diff --git a/docs/gotchas.md b/docs/gotchas.md index b1cf27c8..fd3b6518 100644 --- a/docs/gotchas.md +++ b/docs/gotchas.md @@ -185,16 +185,6 @@ Non-obvious behaviour, and the reasoning behind it. Read the entry before changi Teardown gives accounts ten seconds to disconnect, followed by a separate three-second deadline for the runtime. On macOS the status item appears when Background is enabled, and a left click opens its menu. -- **Scheduled text lives in the account's SQLite queue.** The composer clock - schedules a direct or group message in local time and lists or cancels - pending messages in that chat. The daemon uses UTC deadlines. It attempts - overdue sends when the account reconnects, including after a restart. - The web daemon needs a running tab. The claim replaces the scheduled row with an - outgoing history row in one transaction. After a crash between that - commit and delivery, the message remains in history and is not sent - again automatically. A network send failure uses the - regular failed message bubble and retry UI. Resetting or removing an - account deletes its schedule. - **A daemon the window starts must reset its own signals.** It inherits the window's signal state across the spawn, and the GUI's left SIGTERM and SIGINT without effect: the same binary stopped in a second from a shell and From 33a845c6d047a3fbadafeea63dc24c258b5a9979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 15:18:31 -0300 Subject: [PATCH 06/11] feat(plugins): add chat composer forms --- crates/core/src/plugin.rs | 2 + crates/daemon/src/plugins/mod.rs | 4 ++ crates/daemon/src/plugins/native.rs | 23 ++++---- crates/daemon/src/plugins/web.rs | 5 +- crates/gui/src/app/plugins_ctl.rs | 72 ++++++++++++++++++++------ crates/gui/src/components/plugin_ui.rs | 52 ++++++++++++++++++- crates/gui/src/i18n/catalog.rs | 2 + crates/gui/src/views/chat.rs | 6 ++- crates/ipc/src/transport.rs | 4 +- crates/plugin-abi/src/ui.rs | 16 ++---- crates/plugin-host/src/guest.rs | 1 + crates/plugin-host/src/lib.rs | 2 +- crates/plugin-sdk/src/lib.rs | 2 +- docs/plugin-abi.md | 16 +++--- 14 files changed, 155 insertions(+), 52 deletions(-) diff --git a/crates/core/src/plugin.rs b/crates/core/src/plugin.rs index 6fcb4794..d2c8085a 100644 --- a/crates/core/src/plugin.rs +++ b/crates/core/src/plugin.rs @@ -24,6 +24,8 @@ use serde::{Deserialize, Serialize}; pub enum PluginSlot { /// Beside the conversation's name. ChatHeader, + /// Tools shown beside the conversation composer. + Composer, /// A section of the Settings screen. Settings, } diff --git a/crates/daemon/src/plugins/mod.rs b/crates/daemon/src/plugins/mod.rs index 53797d59..c174e4fd 100644 --- a/crates/daemon/src/plugins/mod.rs +++ b/crates/daemon/src/plugins/mod.rs @@ -329,11 +329,15 @@ fn publishing_to(hub: &Arc) -> Sink { /// the rest of the split. Everything a plugin can actually ask for is here, /// written once on top of it. struct Bridge { + hub: Arc, commands: SessionCommands, } impl Commands for Bridge { fn send_text(&self, jid: &str, text: &str, quoted: Option<&str>) -> Outcome { + if !self.hub.connection().is_connected() { + return Outcome::NoSession; + } self.ask(Action::SendText(oxidezap_ipc::SendText { jid: jid.to_owned(), text: text.to_owned(), diff --git a/crates/daemon/src/plugins/native.rs b/crates/daemon/src/plugins/native.rs index cb2f673a..ea8bec89 100644 --- a/crates/daemon/src/plugins/native.rs +++ b/crates/daemon/src/plugins/native.rs @@ -31,8 +31,12 @@ use crate::state::StateHub; pub(super) async fn start(hub: &Arc, commands: SessionCommands) -> Arc { let sink = publishing_to(hub); let account_id = hub.account_id(); - let fallback = (publishing_to(hub), commands.clone()); - tokio::task::spawn_blocking(move || load(sink, commands, account_id)) + let bridge = Arc::new(Bridge { + hub: hub.clone(), + commands, + }); + let fallback = (publishing_to(hub), bridge.clone()); + tokio::task::spawn_blocking(move || load(sink, bridge, account_id)) .await .unwrap_or_else(|e| { // With the daemon's own sink and bridge, not a discarding pair. @@ -43,28 +47,23 @@ pub(super) async fn start(hub: &Arc, commands: SessionCommands) -> Arc // and every command answering `NoSession` — while reporting the // reload as having worked. log::error!("the plugin loader did not finish: {e}"); - let (sink, commands) = fallback; - Arc::new(Plugins::none(sink, Arc::new(Bridge { commands }))) + let (sink, bridge) = fallback; + Arc::new(Plugins::none(sink, bridge)) }) } /// The scan itself, on the blocking thread [`start`] put it on. -fn load(sink: Sink, commands: SessionCommands, account_id: AccountId) -> Arc { +fn load(sink: Sink, bridge: Arc, account_id: AccountId) -> Arc { let Some(dir) = oxidezap_plugin_host::default_dir() else { log::debug!("no per-user data directory, so no plugins"); - return Arc::new(Plugins::none(sink, Arc::new(Bridge { commands }))); + return Arc::new(Plugins::none(sink, bridge)); }; // Not the daemon's `state_dir`: that one prefers XDG_RUNTIME_DIR, which // is cleared on logout, and a permission answer that does not survive a // logout is a prompt asked forever. Scoped to this account: see // `account_state_dir`. let state_dir = account_state_dir(account_id); - Arc::new(Plugins::load( - &dir, - state_dir.as_deref(), - Arc::new(Bridge { commands }), - sink, - )) + Arc::new(Plugins::load(&dir, state_dir.as_deref(), bridge, sink)) } /// See [`super::reload`]. diff --git a/crates/daemon/src/plugins/web.rs b/crates/daemon/src/plugins/web.rs index 34a1f8f5..d0354b1b 100644 --- a/crates/daemon/src/plugins/web.rs +++ b/crates/daemon/src/plugins/web.rs @@ -59,7 +59,10 @@ pub(super) async fn start(hub: &Arc, commands: SessionCommands) -> Arc Plugins::start( modules, Arc::new(Origin::storage_for_account(hub.account_id())), - Arc::new(Bridge { commands }), + Arc::new(Bridge { + hub: hub.clone(), + commands, + }), sink, ) .await, diff --git a/crates/gui/src/app/plugins_ctl.rs b/crates/gui/src/app/plugins_ctl.rs index 1d1451a0..40ba8958 100644 --- a/crates/gui/src/app/plugins_ctl.rs +++ b/crates/gui/src/app/plugins_ctl.rs @@ -83,7 +83,7 @@ const MAX_FIELD_BYTES: usize = 64 * 1024; /// gone for a context it never had. fn key(plugin: &str, slot: PluginSlot, chat: Option<&str>, id: &str) -> FieldKey { let chat = match slot { - PluginSlot::ChatHeader => chat, + PluginSlot::ChatHeader | PluginSlot::Composer => chat, PluginSlot::Settings => None, }; FieldKey { @@ -378,7 +378,9 @@ impl WhatsAppApp { // what it was. Clicking elsewhere, tabbing away and // closing the screen all blur the box, and all of them // now commit what is in it. - InputEvent::PressEnter { .. } | InputEvent::Blur => { + InputEvent::PressEnter { .. } | InputEvent::Blur + if commit_slot != PluginSlot::Composer => + { this.commit_plugin_field(&commit_plugin, commit_slot, &commit_id, cx); } _ => {} @@ -704,6 +706,30 @@ impl WhatsAppApp { cx.notify(); } + fn composer_form(&self, plugin: &str, cx: &App) -> Option { + let surface = self + .plugins(cx) + .iter() + .find(|surface| surface.id == plugin)?; + let mut fields = Vec::new(); + for node in surface.roots_in(PluginSlot::Composer) { + collect_fields(plugin, PluginSlot::Composer, node, &mut fields); + } + let mut values = std::collections::BTreeMap::new(); + let mut remaining = MAX_FIELD_BYTES; + for field in fields { + let value = self + .plugin_field(plugin, PluginSlot::Composer, &field.id, cx)? + .read(cx) + .value(); + remaining = remaining.checked_sub(field.id.len() + value.len())?; + values.insert(field.id, value.to_string()); + } + serde_json::to_string(&values) + .ok() + .filter(|value| value.len() <= MAX_FIELD_BYTES) + } + /// Tell a plugin one of its widgets was used. /// /// The open conversation goes along only for a slot that has one. A @@ -721,9 +747,22 @@ impl WhatsAppApp { cx: &mut Context, ) { let chat = match slot { - PluginSlot::ChatHeader => self.selected_chat_jid(), + PluginSlot::ChatHeader | PluginSlot::Composer => self.selected_chat_jid(), PluginSlot::Settings => None, }; + let value = if slot == PluginSlot::Composer && widget == PluginWidget::Button { + let Some(form) = self.composer_form(plugin, cx) else { + self.notify_user( + crate::tr!(ComposerPluginFormUnavailable), + super::notices::Tone::Problem, + cx, + ); + return; + }; + Some(form) + } else { + value + }; if let Some(client) = self.client.as_ref() { client.plugin_action(plugin, action, value, chat, slot, widget); } @@ -819,10 +858,10 @@ mod tests { } /// A Settings field is one field whatever is selected, because the action - /// it commits carries no conversation. A header field is one per chat, - /// because the action it commits carries the open one. + /// it commits carries no conversation. Chat tools keep separate fields + /// for each conversation. #[test] - fn only_a_header_field_belongs_to_a_conversation() { + fn chat_tools_fields_belong_to_a_conversation() { let settings = |chat| key("autoreply", PluginSlot::Settings, chat, "keyword"); assert_eq!(settings(Some("a@s.whatsapp.net")), settings(None)); assert_eq!( @@ -830,16 +869,17 @@ mod tests { settings(Some("b@s.whatsapp.net")) ); - let header = |chat| key("autoreply", PluginSlot::ChatHeader, chat, "keyword"); - assert_ne!( - header(Some("a@s.whatsapp.net")), - header(Some("b@s.whatsapp.net")) - ); - assert_ne!( - header(Some("a@s.whatsapp.net")), - settings(Some("a@s.whatsapp.net")), - "and the same id in two slots is still two fields" - ); + for slot in [PluginSlot::ChatHeader, PluginSlot::Composer] { + let chat_field = |chat| key("autoreply", slot, chat, "keyword"); + assert_ne!( + chat_field(Some("a@s.whatsapp.net")), + chat_field(Some("b@s.whatsapp.net")) + ); + assert_ne!( + chat_field(Some("a@s.whatsapp.net")), + settings(Some("a@s.whatsapp.net")) + ); + } } /// The key used to be a formatted string with `/` between its parts. A diff --git a/crates/gui/src/components/plugin_ui.rs b/crates/gui/src/components/plugin_ui.rs index a399362e..8ab44259 100644 --- a/crates/gui/src/components/plugin_ui.rs +++ b/crates/gui/src/components/plugin_ui.rs @@ -12,7 +12,8 @@ //! with a clickable rectangle. use gpui::{ - App, Entity, IntoElement, ParentElement, SharedString, Styled, div, prelude::FluentBuilder as _, + App, Entity, InteractiveElement as _, IntoElement, ParentElement, SharedString, + StatefulInteractiveElement as _, Styled, div, prelude::FluentBuilder as _, rems, }; use gpui_component::ActiveTheme as _; use gpui_component::button::{Button, ButtonVariants as _}; @@ -54,6 +55,51 @@ pub fn slot( .collect() } +pub fn composer(app: &WhatsAppApp, ctx: &PluginContext, cx: &App) -> Option { + let chat = app.selected_chat_jid()?; + if !app + .plugins(cx) + .iter() + .any(|surface| surface.roots_in(PluginSlot::Composer).next().is_some()) + { + return None; + } + let ctx = ctx.clone(); + let metrics = ctx.metrics; + Some( + div() + .px(metrics.space_md()) + .child( + gpui_component::popover::Popover::new(SharedString::from(format!( + "composer-plugins/{chat}" + ))) + .anchor(gpui::Anchor::BottomLeft) + .trigger( + Button::new("composer-plugin-tools") + .label(crate::tr!(ComposerPlugins)) + .ghost() + .small(), + ) + .content(move |_, window, cx| { + let app = ctx.entity.read(cx); + div() + .id("composer-plugin-panel") + .flex() + .flex_col() + .gap(metrics.space_md()) + .w(rems(20.)) + .max_w( + (window.viewport_size().width - metrics.space_xl()).max(gpui::px(0.)), + ) + .max_h(rems(24.)) + .overflow_y_scroll() + .children(slot(app.plugins(cx), PluginSlot::Composer, app, &ctx, cx)) + }), + ) + .into_any_element(), + ) +} + /// One widget and, below it, whatever it holds. fn widget( surface: &PluginSurface, @@ -154,7 +200,9 @@ fn widget( // keyword into, reads back, and leaves — and the plugin goes on // answering the old one. Not drawn over a dead control: a // plugin that stopped cannot be given anything. - let unsaved = live && app.plugin_field_unsaved(&surface.id, slot, &node.id, cx); + let unsaved = live + && slot != PluginSlot::Composer + && app.plugin_field_unsaved(&surface.id, slot, &node.id, cx); div() .flex() .flex_col() diff --git a/crates/gui/src/i18n/catalog.rs b/crates/gui/src/i18n/catalog.rs index 553ec174..50987d6f 100644 --- a/crates/gui/src/i18n/catalog.rs +++ b/crates/gui/src/i18n/catalog.rs @@ -276,6 +276,8 @@ catalog! { Gentle => ("Gentle", "Suave"); TestRingtone => ("Test ringtone", "Testar toque"); Camera => ("CAMERA", "CÂMERA"); + ComposerPluginFormUnavailable => ("This plugin form is unavailable or too large", "Este formulário do plugin está indisponível ou é grande demais"); + ComposerPlugins => ("Chat tools", "Ferramentas da conversa"); CameraModesUnavailable => ("No modes reported for this camera", "Nenhum modo informado para esta câmera"); ResolutionAndFrameRate => ("RESOLUTION AND FRAME RATE", "RESOLUÇÃO E TAXA DE QUADROS"); StopCameraPreview => ("Stop camera preview", "Parar prévia da câmera"); diff --git a/crates/gui/src/views/chat.rs b/crates/gui/src/views/chat.rs index 1c1435a9..5e525990 100644 --- a/crates/gui/src/views/chat.rs +++ b/crates/gui/src/views/chat.rs @@ -51,6 +51,7 @@ pub fn render_connected_view( &plugin_ctx, cx, ); + let plugin_composer = plugin_ui::composer(app, &plugin_ctx, cx); let selected_jid = app.selected_destination_jid(); // Cloned rather than borrowed: building the timeline's rows below needs // the app mutably, and these are handles — a clone is a refcount. @@ -349,6 +350,7 @@ pub fn render_connected_view( offline_recovery, is_own_number, plugin_actions, + plugin_composer, media: media.clone(), }, &message_list, @@ -570,6 +572,7 @@ struct ChatAreaProps<'a> { /// `Context`. Empty when no plugin drew there, which is the ordinary /// case. plugin_actions: Vec, + plugin_composer: Option, media: Option>, } @@ -593,6 +596,7 @@ fn render_chat_area( offline_recovery, is_own_number, plugin_actions, + plugin_composer, media, } = props; let metrics = *layout.metrics(); @@ -665,7 +669,7 @@ fn render_chat_area( if let Some(recovery) = offline_recovery { el.child(render_offline_strip(entity.clone(), recovery, metrics, cx)) } else { - el.children(input_area) + el.children(plugin_composer).children(input_area) } }) .on_drop({ diff --git a/crates/ipc/src/transport.rs b/crates/ipc/src/transport.rs index b9a81e3a..e2d0e6d1 100644 --- a/crates/ipc/src/transport.rs +++ b/crates/ipc/src/transport.rs @@ -291,7 +291,9 @@ use std::path::PathBuf; /// 43 adds the status, sticker-library and composer-media requests, among them /// `PublishStatusMedia`, which an older daemon would refuse as malformed after /// the file had been staged. -pub const PROTOCOL_VERSION: u32 = 43; +/// +/// 44 adds the Composer plugin slot to published widget trees and actions. +pub const PROTOCOL_VERSION: u32 = 44; /// Where the daemon's web bridge listens when nobody says otherwise. /// diff --git a/crates/plugin-abi/src/ui.rs b/crates/plugin-abi/src/ui.rs index 573952c9..225b6fb2 100644 --- a/crates/plugin-abi/src/ui.rs +++ b/crates/plugin-abi/src/ui.rs @@ -120,21 +120,16 @@ pub mod slot { pub const NONE: u8 = 0; /// Beside the conversation's name. The action carries the open chat. pub const CHAT_HEADER: u8 = 1; + /// A panel next to the composer. The action carries the open chat. + pub const COMPOSER: u8 = 2; /// A section of the Settings screen, which is where a plugin's own /// configuration belongs. pub const SETTINGS: u8 = 3; - // 2 is reserved for the composer, which is not drawn yet. It is *not* - // defined here for that reason: a slot the front end silently ignores is - // a button whose author never finds out why it did not appear, which is - // the same failure `ParseError::Misplaced` exists to refuse. A slot - // arrives when something draws it, and arriving is a new constant — an - // addition, not a change. - /// Whether a byte names a slot this format defines. #[must_use] pub const fn is_known(slot: u8) -> bool { - matches!(slot, CHAT_HEADER | SETTINGS) + matches!(slot, CHAT_HEADER | COMPOSER | SETTINGS) } } @@ -943,8 +938,7 @@ mod tests { fn a_slot_this_build_does_not_draw_is_refused() { let mut bytes = vec![FORMAT]; bytes.extend_from_slice(&1u32.to_le_bytes()); - // 2 is reserved for the composer, which nothing renders yet. - bytes.extend_from_slice(&[kind::BUTTON, 2, flags::ENABLED, 0]); + bytes.extend_from_slice(&[kind::BUTTON, 4, flags::ENABLED, 0]); bytes.extend_from_slice(&0u16.to_le_bytes()); for text in ["b", "B", ""] { bytes.extend_from_slice(&(text.len() as u32).to_le_bytes()); @@ -954,7 +948,7 @@ mod tests { parse(&bytes), Err(ParseError::Unknown { kind: kind::BUTTON, - slot: 2 + slot: 4 }) ); } diff --git a/crates/plugin-host/src/guest.rs b/crates/plugin-host/src/guest.rs index bcfb2a08..4eddadf1 100644 --- a/crates/plugin-host/src/guest.rs +++ b/crates/plugin-host/src/guest.rs @@ -1134,6 +1134,7 @@ fn link_free(linker: &mut Linker) -> Result<(), wasmi::Error> { fn root(node: &abi::ui::Node) -> Option { let slot = match node.slot { abi::ui::slot::CHAT_HEADER => PluginSlot::ChatHeader, + abi::ui::slot::COMPOSER => PluginSlot::Composer, abi::ui::slot::SETTINGS => PluginSlot::Settings, _ => return None, }; diff --git a/crates/plugin-host/src/lib.rs b/crates/plugin-host/src/lib.rs index 4c66aca7..9e511a65 100644 --- a/crates/plugin-host/src/lib.rs +++ b/crates/plugin-host/src/lib.rs @@ -954,7 +954,7 @@ impl Live { // produce, so both are somebody else's client rather than a person // pressing something. let chat = match (action.slot, action.chat_jid.as_deref()) { - (PluginSlot::ChatHeader, Some(jid)) if !jid.is_empty() => jid, + (PluginSlot::ChatHeader | PluginSlot::Composer, Some(jid)) if !jid.is_empty() => jid, (PluginSlot::Settings, None) => "", (slot, _) => { log::debug!( diff --git a/crates/plugin-sdk/src/lib.rs b/crates/plugin-sdk/src/lib.rs index b60c0d31..45f28359 100644 --- a/crates/plugin-sdk/src/lib.rs +++ b/crates/plugin-sdk/src/lib.rs @@ -824,7 +824,7 @@ impl Action<'_> { } /// What it now holds — a toggle's new state as `1` or `0`, a field's - /// contents, and nothing at all for a button. + /// contents, or a JSON object of field values for a composer button. #[must_use] pub fn value(self) -> Text<256> { self.0.text(fields::ACTION_VALUE) diff --git a/docs/plugin-abi.md b/docs/plugin-abi.md index a60eadfa..9b412de9 100644 --- a/docs/plugin-abi.md +++ b/docs/plugin-abi.md @@ -253,10 +253,9 @@ node: Kinds: `1` button, `2` toggle, `3` label, `4` text field, `5` row, `6` column, `7` section. Only rows, columns and sections are drawn with children. -Slots: `1` chat header, `3` settings. `2` is **reserved and undefined** — the -composer's number, unassigned on purpose, because a slot the front end -silently ignores is a button whose author never finds out why it did not -appear. +Slots: `1` chat header, `2` composer tools popover, `3` settings. Actions +in the header and composer slots carry the open chat. Use the composer slot +for forms and tools that act on that conversation. Flags: `1` enabled, `2` checked. @@ -299,12 +298,17 @@ so they are decoded strictly — a broken byte in an id is an error, where a broken byte in a label is replaced and drawn. When somebody uses a widget, `UI_ACTION` arrives carrying `ACTION_ID`, -`ACTION_VALUE` (a toggle's *new* state as `1`/`0`, a field's contents, empty -for a button) and `CHAT_JID` for a slot that has a chat behind it. The daemon +`ACTION_VALUE` (a toggle's *new* state as `1`/`0`, a field's contents, or +a composer button's form values) and `CHAT_JID` for a slot that has a chat +behind it. The daemon checks the action against the tree it currently publishes — kind and slot included — so a press from a window whose frame is older than the daemon's does not land as a real one. +Composer text fields are local until a composer button is pressed. That button +receives a JSON object mapping the plugin's composer field IDs to the values +currently visible in the same chat. Other buttons have an empty value. + ## What the host holds a plugin to Fuel meters the instructions a plugin runs, not the work the host does when From 5cb851c4daf003915a36ad2eda2708e2dde4f26e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 15:18:31 -0300 Subject: [PATCH 07/11] feat(plugins): schedule text messages in a WASM plugin --- crates/plugin-host/src/tests.rs | 69 +++++++ examples/schedule/Cargo.lock | 144 ++++++++++++++ examples/schedule/Cargo.toml | 29 +++ examples/schedule/README.md | 24 +++ examples/schedule/src/lib.rs | 323 ++++++++++++++++++++++++++++++++ 5 files changed, 589 insertions(+) create mode 100644 examples/schedule/Cargo.lock create mode 100644 examples/schedule/Cargo.toml create mode 100644 examples/schedule/README.md create mode 100644 examples/schedule/src/lib.rs diff --git a/crates/plugin-host/src/tests.rs b/crates/plugin-host/src/tests.rs index dffea915..09f30840 100644 --- a/crates/plugin-host/src/tests.rs +++ b/crates/plugin-host/src/tests.rs @@ -1133,6 +1133,75 @@ fn shutting_down_joins_every_plugin() { plugins.shutdown(); } +#[test] +#[ignore = "needs examples/schedule built for wasm32-unknown-unknown"] +fn the_schedule_plugin_submits_chat_forms_and_cancels_pending_messages() { + let built = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../examples/schedule/target/wasm32-unknown-unknown/release/schedule.wasm" + ); + let dir = TempDir::new("schedule-example"); + std::fs::copy(built, dir.0.join("schedule.wasm")).expect("build the schedule example first"); + let state = TempDir::new("schedule-example-state"); + let commands = Recorder::new(Outcome::Accepted); + let published = Published::default(); + let plugins = Plugins::load( + &dir.0, + Some(&state.0), + Arc::new(Arc::clone(&commands)), + published.sink(), + ); + published.settles("the composer form", |surfaces| { + surfaces.first().is_some_and(|surface| { + surface.is_running() && surface.roots_in(PluginSlot::Composer).next().is_some() + }) + }); + let chat = "15550100000@s.whatsapp.net"; + plugins.act(&PluginAction { + plugin: "schedule".into(), + action: "schedule".into(), + value: Some(r#"{"message":"see you later","when":"60"}"#.into()), + chat_jid: Some(chat.into()), + slot: PluginSlot::Composer, + widget: PluginWidget::Button, + }); + published.settles("the scheduled job", |surfaces| { + surfaces[0] + .roots_in(PluginSlot::Settings) + .any(|root| root.children.iter().any(|child| child.id == "cancel-1")) + }); + plugins.act(&PluginAction { + plugin: "schedule".into(), + action: "cancel-1".into(), + value: None, + chat_jid: None, + slot: PluginSlot::Settings, + widget: PluginWidget::Button, + }); + published.settles("the cancelled job", |surfaces| { + surfaces[0] + .roots_in(PluginSlot::Settings) + .all(|root| root.children.iter().all(|child| child.id != "cancel-1")) + }); + assert!(commands.sent().is_empty()); + + assert!(plugins.approve("schedule", true)); + let due = wacore::time::now_utc() + Duration::from_secs(3); + plugins.act(&PluginAction { + plugin: "schedule".into(), + action: "schedule".into(), + value: Some(format!( + r#"{{"message":"due now","when":"{}"}}"#, + due.to_rfc3339() + )), + chat_jid: Some(chat.into()), + slot: PluginSlot::Composer, + widget: PluginWidget::Button, + }); + published.settles("the timer sends the job", |_| !commands.sent().is_empty()); + assert_eq!(commands.sent(), [(chat.into(), "due now".into(), None)]); +} + /// The real SDK, against the real host. /// /// Ignored by default because it needs the example built for wasm32, which diff --git a/examples/schedule/Cargo.lock b/examples/schedule/Cargo.lock new file mode 100644 index 00000000..9972705c --- /dev/null +++ b/examples/schedule/Cargo.lock @@ -0,0 +1,144 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oxidezap-plugin" +version = "0.1.0" +dependencies = [ + "oxidezap-plugin-abi", +] + +[[package]] +name = "oxidezap-plugin-abi" +version = "0.1.0" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "schedule" +version = "0.1.0" +dependencies = [ + "chrono", + "oxidezap-plugin", + "serde", + "serde_json", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/examples/schedule/Cargo.toml b/examples/schedule/Cargo.toml new file mode 100644 index 00000000..99781d77 --- /dev/null +++ b/examples/schedule/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "schedule" +description = "Schedule text messages from the OxideZap composer" +version = "0.1.0" +edition = "2024" +rust-version = "1.100.0" +license = "MIT" +publish = false + +[workspace] + +[lib] +crate-type = ["cdylib"] + +[dependencies] +oxidezap-plugin = { path = "../../crates/plugin-sdk" } +chrono = { version = "0.4", default-features = false, features = ["alloc"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[dev-dependencies] +oxidezap-plugin = { path = "../../crates/plugin-sdk", features = ["testing"] } + +[profile.release] +opt-level = "z" +lto = "fat" +codegen-units = 1 +panic = "abort" +strip = true diff --git a/examples/schedule/README.md b/examples/schedule/README.md new file mode 100644 index 00000000..28a504ba --- /dev/null +++ b/examples/schedule/README.md @@ -0,0 +1,24 @@ +# Scheduled messages + +Build the plugin from the repository root: + +```sh +cargo xtask plugin build examples/schedule +``` + +Install the resulting `schedule.wasm` in Settings → Plugins and approve +sending messages. In a direct chat or group, open **Chat tools** by the +composer. Enter the message and either minutes from now or an RFC 3339 +time with an explicit offset, such as `2026-11-21T14:30:00-03:00`. +Press **Schedule**. The plugin's Settings panel lists pending messages and +lets you cancel them. + +The queue is stored per account. Keep the daemon running on desktop or +the app's host tab open on web for on-time attempts. The plugin checks due +messages when it starts and every five seconds thereafter. A disconnected +account keeps its jobs until it reconnects. + +The plugin records an attempt before handing the message to the account. +An accepted command is handed off once. Acceptance is not a WhatsApp +delivery receipt. A crash in the handoff leaves an unconfirmed entry in +Settings for manual inspection. The plugin does not replay it automatically. diff --git a/examples/schedule/src/lib.rs b/examples/schedule/src/lib.rs new file mode 100644 index 00000000..d21b8b66 --- /dev/null +++ b/examples/schedule/src/lib.rs @@ -0,0 +1,323 @@ +use chrono::{DateTime, Utc}; +use oxidezap_plugin::{ + Action, Caps, Declared, Event, Kinds, Outcome, Setup, Which, now_ms, plugin, ui, +}; +use serde::{Deserialize, Serialize}; + +plugin!(init = setup, event = handle, panic = own); + +const STORE: &str = "messages"; +const TICK: i64 = 1; +const MAX_JOBS: usize = 8; +const MAX_MESSAGE: usize = 512; +const POLL_MS: i64 = 5_000; + +#[derive(Clone, Serialize, Deserialize)] +struct Job { + id: u64, + jid: String, + text: String, + at: i64, + attempting: bool, +} + +#[derive(Default, Serialize, Deserialize)] +struct Queue { + last_id: u64, + jobs: Vec, +} + +#[derive(Deserialize)] +struct Form { + message: String, + when: String, +} + +fn setup(p: Setup) -> impl Declared { + let declared = p + .name("Scheduled messages") + .subscribe(Kinds::NONE) + .capabilities(Caps::UI | Caps::STORAGE | Caps::TIMERS | Caps::SEND); + draw(&read_queue(), ""); + oxidezap_plugin::after(100, TICK); + declared +} + +fn read_queue() -> Result { + let stored = oxidezap_plugin::get::<8192>(STORE); + let Some(raw) = stored.whole().filter(|_| !stored.refused()) else { + return if stored.refused() || stored.present() { + Err("The schedule could not be read.") + } else { + Ok(Queue::default()) + }; + }; + if !stored.present() { + return Ok(Queue::default()); + } + serde_json::from_str(raw).map_err(|_| "The stored schedule could not be read.") +} + +fn save(queue: &Queue) -> Result<(), &'static str> { + let raw = serde_json::to_string(queue).map_err(|_| "The schedule could not be saved.")?; + if oxidezap_plugin::set(STORE, &raw) == Outcome::Accepted { + Ok(()) + } else { + Err("The schedule could not be saved.") + } +} + +fn chat_supported(jid: &str) -> bool { + jid.rsplit_once('@').is_some_and(|(user, server)| { + !user.is_empty() + && user.bytes().all(|b| b.is_ascii_digit() || b == b'-') + && matches!(server, "s.whatsapp.net" | "lid" | "g.us") + }) +} + +fn deadline(when: &str, now: i64) -> Option { + let when = when.trim(); + let at = if let Ok(minutes) = when.parse::() { + now.checked_add(minutes.checked_mul(60_000)?)? + } else { + DateTime::parse_from_rfc3339(when).ok()?.timestamp_millis() + }; + (at > now && at.saturating_sub(now) <= 366 * 86_400_000).then_some(at) +} + +fn edit_queue(action: Action<'_>, queue: &mut Queue) -> Result<&'static str, &'static str> { + let id = action.id(); + let chat = action.chat(); + let jid = chat.as_str(); + if let Some(id) = id + .as_str() + .strip_prefix("cancel-") + .and_then(|id| id.parse::().ok()) + { + queue.jobs.retain(|job| job.id != id); + save(queue)?; + return Ok("Removed from the schedule."); + } + if !chat_supported(jid) { + return Err("Open a direct conversation or group to schedule a message."); + } + if id.as_str() != "schedule" { + return Ok(""); + } + if queue.jobs.len() >= MAX_JOBS { + return Err("The schedule is full."); + } + let value = action.value_into::<4096>(); + let form: Form = value + .whole() + .and_then(|raw| serde_json::from_str(raw).ok()) + .ok_or("The form could not be read.")?; + if form.message.trim().is_empty() || form.message.len() > MAX_MESSAGE { + return Err("Enter a message of up to 512 bytes."); + } + let now = now_ms(); + let at = deadline(&form.when, now).ok_or("Enter a future time within one year.")?; + if queue + .jobs + .iter() + .any(|job| job.jid == jid && job.text == form.message && job.at.abs_diff(at) < 5_000) + { + return Err("This message is already in the schedule."); + } + queue.last_id = queue + .last_id + .checked_add(1) + .ok_or("The schedule is full.")?; + queue.jobs.push(Job { + id: queue.last_id, + jid: jid.into(), + text: form.message, + at, + attempting: false, + }); + save(queue)?; + Ok("Message scheduled. Manage it in the plugin settings.") +} + +fn tick(queue: &mut Queue) -> Result { + let now = now_ms(); + let Some(index) = queue + .jobs + .iter() + .enumerate() + .filter(|(_, job)| !job.attempting && job.at <= now) + .min_by_key(|(_, job)| (job.at, job.id)) + .map(|(index, _)| index) + else { + return Ok(false); + }; + // A restart between this write and the send cannot replay an uncertain send. + queue.jobs[index].attempting = true; + save(queue)?; + let job = &queue.jobs[index]; + match oxidezap_plugin::send_text(&job.jid, &job.text) { + Outcome::Accepted => { + queue.jobs.remove(index); + } + Outcome::NoSession | Outcome::Denied | Outcome::Refused => { + queue.jobs[index].attempting = false; + } + Outcome::Invalid | Outcome::State => return Ok(true), + } + save(queue)?; + Ok(true) +} + +fn handle(event: &Event) { + match event.which() { + Which::Action(action) => { + let mut queue = read_queue(); + let status = match queue.as_mut() { + Ok(queue) => match edit_queue(action, queue) { + Ok(status) | Err(status) => status, + }, + Err(error) => error, + }; + draw(&queue, status); + } + Which::Timer(timer) if timer.token() == TICK => { + let mut queue = read_queue(); + match queue.as_mut().map(tick) { + Ok(Ok(true)) => draw(&queue, ""), + Ok(Err(error)) => draw(&queue, error), + _ => {} + } + oxidezap_plugin::after(POLL_MS, TICK); + } + _ => {} + } +} + +fn draw(queue: &Result, notice: &str) { + ui::publish::<16384>(|ui| { + ui.section(ui::slot::COMPOSER, "Schedule a message", |section| { + section.field("message", "Message (up to 512 bytes)", "", true); + section.field( + "when", + "Minutes from now or RFC 3339 date with offset", + "", + true, + ); + section.button("schedule", "Schedule"); + if !notice.is_empty() { + section.label(notice); + } + }); + ui.section(ui::slot::SETTINGS, "Scheduled messages", |section| { + let queue = match queue { + Ok(queue) => queue, + Err(error) => { + section.label(error); + return; + } + }; + if queue.jobs.is_empty() { + section.label("No scheduled messages."); + } + for job in &queue.jobs { + let when = DateTime::::from_timestamp_millis(job.at) + .map(|time| time.to_rfc3339()) + .unwrap_or_default(); + section.label(&format!("{} · {}", job.jid, when)); + section.label(&job.text); + let label = if job.attempting { + "Dismiss unconfirmed send" + } else { + "Cancel scheduled message" + }; + section.button(&format!("cancel-{}", job.id), label); + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use oxidezap_plugin::{ + abi, + testing::{Event as In, Host}, + }; + + const CHAT: &str = "15550100000@s.whatsapp.net"; + + fn schedule(host: &mut Host, chat: &str, when: &str) { + let value = serde_json::json!({"message": "hello", "when": when}).to_string(); + host.deliver( + In::action("schedule", &value).str(abi::fields::CHAT_JID, chat), + handle, + ); + } + + #[test] + fn persisted_job_is_sent_once_at_or_after_its_deadline() { + let mut host = Host::new(); + host.init(setup); + assert!( + host.ui() + .unwrap() + .unwrap() + .iter() + .any(|node| node.slot == ui::slot::COMPOSER) + ); + host.set_now_ms(1_000); + schedule(&mut host, CHAT, "1"); + host.deliver(In::timer(TICK), handle); + assert!(host.sent().is_empty()); + + let saved = host.stored(STORE).unwrap(); + let mut restarted = Host::new(); + restarted.store(STORE, &saved); + restarted.init(setup); + restarted.set_now_ms(61_000); + restarted.deliver(In::timer(TICK), handle); + restarted.deliver(In::timer(TICK), handle); + assert_eq!(restarted.sent(), [(CHAT.to_owned(), "hello".to_owned())]); + } + + #[test] + fn invalid_destinations_and_cancelled_jobs_do_not_send() { + let mut host = Host::new(); + host.init(setup); + schedule(&mut host, "status@broadcast", "1"); + assert!(host.stored(STORE).is_none()); + schedule(&mut host, CHAT, "1"); + host.deliver(In::action("cancel-1", ""), handle); + host.set_now_ms(60_000); + host.deliver(In::timer(TICK), handle); + assert!(host.sent().is_empty()); + } + + #[test] + fn a_restart_does_not_replay_an_unconfirmed_attempt() { + let mut host = Host::new(); + let queue = Queue { + last_id: 1, + jobs: vec![Job { + id: 1, + jid: CHAT.into(), + text: "hello".into(), + at: 100, + attempting: true, + }], + }; + host.store(STORE, &serde_json::to_string(&queue).unwrap()); + host.init(setup); + host.set_now_ms(100); + host.deliver(In::timer(TICK), handle); + assert!(host.sent().is_empty()); + } + + #[test] + fn parses_offsets_without_assuming_the_daemon_timezone() { + assert_eq!(deadline("1970-01-01T00:01:00Z", 0), Some(60_000)); + assert_eq!(deadline("1970-01-01T01:01:00+01:00", 0), Some(60_000)); + assert_eq!(deadline("1970-01-01T00:01:00", 0), None); + assert_eq!(deadline("-1", 0), None); + } +} From f5885a8797e96481adc13a482f9b50043ab03610 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 15:21:28 -0300 Subject: [PATCH 08/11] build(release): ship optional WASM plugins in a zip --- .github/workflows/build.yml | 48 +++++++++++++++++++++++++++++ .github/workflows/nightly.yml | 13 +++++--- .github/workflows/release-check.yml | 18 ++++++++++- README.md | 3 ++ 4 files changed, 77 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 04289fc9..8fce4725 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -252,3 +252,51 @@ jobs: name: oxidezap-${{ matrix.name }} path: ${{ env.ASSET }} if-no-files-found: error + + plugins: + name: Plugin bundle + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + ref: ${{ inputs.ref }} + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + toolchain: "1.100.0" + targets: wasm32-unknown-unknown + - name: Build installable plugins + env: + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + case "$VERSION" in + ""|*[!a-zA-Z0-9._-]*|-*|.*) exit 1 ;; + esac + modules=() + for manifest in examples/*/Cargo.toml; do + plugin="${manifest%/Cargo.toml}" + if [ "$plugin" = examples/template ]; then continue; fi + module="$(cargo xtask plugin build "$plugin")" + modules+=("$module") + done + test "${#modules[@]}" -gt 0 + mkdir -p dist/release + python3 - "dist/release/oxidezap-$VERSION-plugins.zip" "${modules[@]}" <<'PYTHON' + import sys + from pathlib import Path + from zipfile import ZIP_DEFLATED, ZipFile + + modules = [Path(path) for path in sys.argv[2:]] + names = [module.name for module in modules] + if len(set(names)) != len(names): + raise SystemExit("Duplicate plugin module names") + with ZipFile(sys.argv[1], "w", compression=ZIP_DEFLATED) as archive: + for module in modules: + archive.write(module, module.name) + PYTHON + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: oxidezap-plugins + path: dist/release/oxidezap-${{ inputs.version }}-plugins.zip + if-no-files-found: error diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 2040ee3c..a33e57e8 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -67,6 +67,9 @@ jobs: that runs in place, adds its own menu entry and updates through its `.zsync`. `OxideZap.AppImage --cli ...` runs the CLI. + `oxidezap-nightly-plugins.zip` contains optional `.wasm` plugins. + Unpack it and install the modules you want under Settings → Plugins. + The tarballs carry the execute bit. On macOS, clear the quarantine flag before the first run: @@ -83,10 +86,12 @@ jobs: obtains the cross-origin isolation the window needs. `README.md` inside says the rest. NOTES - echo "" >> notes.md - echo "Built from [\`${GITHUB_SHA:0:7}\`](https://github.com/$GH_REPO/commit/$GITHUB_SHA) on $(date -u +"%Y-%m-%d %H:%M") UTC." >> notes.md - echo "" >> notes.md - echo "Verify download integrity with \`sha256sum -c --ignore-missing checksums.sha256\`." >> notes.md + { + echo "" + echo "Built from [\`${GITHUB_SHA:0:7}\`](https://github.com/$GH_REPO/commit/$GITHUB_SHA) on $(date -u +"%Y-%m-%d %H:%M") UTC." + echo "" + echo "Verify download integrity with \`sha256sum -c --ignore-missing checksums.sha256\`." + } >> notes.md # Recreate rather than edit: `gh release edit` cannot move a tag, and # a stale tag would leave the assets pointing at an older commit. gh release delete nightly --yes --cleanup-tag || true diff --git a/.github/workflows/release-check.yml b/.github/workflows/release-check.yml index 0c3fd086..9e98fd0d 100644 --- a/.github/workflows/release-check.yml +++ b/.github/workflows/release-check.yml @@ -42,5 +42,21 @@ jobs: test -s "artifacts/oxidezap-$VERSION-linux-$arch.$suffix" done done - test "$(find artifacts -type f | wc -l)" -eq 12 + python3 - "artifacts/oxidezap-$VERSION-plugins.zip" <<'PYTHON' + import sys + from pathlib import PurePosixPath + from zipfile import ZipFile + + with ZipFile(sys.argv[1]) as archive: + names = archive.namelist() + assert names and len(set(names)) == len(names), names + for name in names: + path = PurePosixPath(name) + assert name == path.name and path.suffix == ".wasm", name + assert name != "template.wasm", name + with archive.open(name) as module: + assert module.read(8) == b"\0asm\x01\0\0\0", name + assert archive.testzip() is None + PYTHON + test "$(find artifacts -type f | wc -l)" -eq 13 (cd artifacts && sha256sum oxidezap-* > checksums.sha256 && sha256sum -c checksums.sha256) diff --git a/README.md b/README.md index c4e64475..3e19b7ac 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,9 @@ history, which is what the in-app "pair again" action does. ## Plugins +Releases include an optional `oxidezap--plugins.zip`. Unpack it and +install the `.wasm` modules you want under Settings → Plugins. + A plugin is a `.wasm` file dropped in `~/.local/share/oxidezap/plugins` — or, in a page running its own session, added under Settings → Plugins, which keeps it in the browser's own storage. Either way it runs inside the daemon — which From 19a9e2ae145200ff7dea899b18ecc3b407165c95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 15:34:09 -0300 Subject: [PATCH 09/11] fix(plugins): persist scheduled sends before dispatch --- crates/plugin-abi/src/lib.rs | 1 + crates/plugin-host/src/guest.rs | 92 +++++++++++++++++++-------------- crates/plugin-host/src/kv.rs | 53 +++++++++++++++++++ crates/plugin-host/src/tests.rs | 2 + crates/plugin-sdk/src/lib.rs | 14 +++++ crates/plugin-sdk/src/raw.rs | 20 +++++++ docs/plugin-abi.md | 8 +++ examples/schedule/src/lib.rs | 68 +++++++++++++++++------- 8 files changed, 202 insertions(+), 56 deletions(-) diff --git a/crates/plugin-abi/src/lib.rs b/crates/plugin-abi/src/lib.rs index 9ad98cce..4ea54405 100644 --- a/crates/plugin-abi/src/lib.rs +++ b/crates/plugin-abi/src/lib.rs @@ -141,6 +141,7 @@ pub mod imports { pub const KV_GET: &str = "oxi_kv_get"; /// `fn(key, key_len, val, val_len) -> i32`. An empty value deletes. pub const KV_SET: &str = "oxi_kv_set"; + pub const KV_SET_DURABLE: &str = "oxi_kv_set_durable"; /// `fn(delay_ms: i64, token: i64) -> i32` — deliver /// [`super::kinds::TIMER`] carrying `token`, once, after `delay_ms`. /// The host holds a floor under the delay and a ceiling over it: a diff --git a/crates/plugin-host/src/guest.rs b/crates/plugin-host/src/guest.rs index 4eddadf1..c74c2781 100644 --- a/crates/plugin-host/src/guest.rs +++ b/crates/plugin-host/src/guest.rs @@ -940,44 +940,60 @@ fn link_acting(linker: &mut Linker) -> Result<(), wasmi::Error> { }, )?; - linker.func_wrap( - m, - abi::imports::KV_SET, - |mut c: Caller<'_, Guest>, key: i32, key_len: i32, val: i32, val_len: i32| -> i32 { - if !c.data().allows(abi::caps::STORAGE) { - return abi::outcome::DENIED; - } - // Refused from the *lengths*, before either string is copied. The - // store rejects an oversized entry anyway, but by then the host - // has already allocated and copied up to 64 KiB twice — a cost - // charged as one fixed-price wasm call, so a loop turns a fuel - // budget into allocation traffic the sandbox never sees. - let too_big = |len: i32| !(0..=(crate::kv::MAX_ENTRY as i32)).contains(&len); - if too_big(key_len) || too_big(val_len) { - return abi::outcome::REFUSED; - } - // And the same question about the call as a whole. One entry is - // bounded; the number of them was not, so a loop rewriting one - // key kept nothing and still moved as much memory as it liked — - // the store's budget bounds what is *kept*, and this bounds what - // is copied to keep it. - let spent = &mut c.data_mut().kv_bytes; - let asked = key_len as usize + val_len as usize; - if asked > MAX_KV_BYTES_PER_CALL.saturating_sub(*spent) { - return abi::outcome::REFUSED; - } - *spent += asked; - let [key, value] = match read_strs(&mut c, [(key, key_len), (val, val_len)]) { - Ok(read) => read, - Err(code) => return code, - }; - if c.data_mut().kv.set(&key, &value) { - abi::outcome::ACCEPTED - } else { - abi::outcome::REFUSED - } - }, - )?; + for (name, durable) in [ + (abi::imports::KV_SET, false), + (abi::imports::KV_SET_DURABLE, true), + ] { + linker.func_wrap( + m, + name, + move |mut c: Caller<'_, Guest>, + key: i32, + key_len: i32, + val: i32, + val_len: i32| + -> i32 { + if !c.data().allows(abi::caps::STORAGE) { + return abi::outcome::DENIED; + } + // Refused from the *lengths*, before either string is copied. The + // store rejects an oversized entry anyway, but by then the host + // has already allocated and copied up to 64 KiB twice — a cost + // charged as one fixed-price wasm call, so a loop turns a fuel + // budget into allocation traffic the sandbox never sees. + let too_big = |len: i32| !(0..=(crate::kv::MAX_ENTRY as i32)).contains(&len); + if too_big(key_len) || too_big(val_len) { + return abi::outcome::REFUSED; + } + // And the same question about the call as a whole. One entry is + // bounded; the number of them was not, so a loop rewriting one + // key kept nothing and still moved as much memory as it liked — + // the store's budget bounds what is *kept*, and this bounds what + // is copied to keep it. + let spent = &mut c.data_mut().kv_bytes; + let asked = key_len as usize + val_len as usize; + if asked > MAX_KV_BYTES_PER_CALL.saturating_sub(*spent) { + return abi::outcome::REFUSED; + } + *spent += asked; + let [key, value] = match read_strs(&mut c, [(key, key_len), (val, val_len)]) { + Ok(read) => read, + Err(code) => return code, + }; + let kv = &mut c.data_mut().kv; + let stored = if durable { + kv.set_durable(&key, &value) + } else { + kv.set(&key, &value) + }; + if stored { + abi::outcome::ACCEPTED + } else { + abi::outcome::REFUSED + } + }, + )?; + } linker.func_wrap( m, diff --git a/crates/plugin-host/src/kv.rs b/crates/plugin-host/src/kv.rs index 322f56fc..8ba6180a 100644 --- a/crates/plugin-host/src/kv.rs +++ b/crates/plugin-host/src/kv.rs @@ -179,6 +179,37 @@ impl Kv { true } + /// Replace one entry and acknowledge only after the backing store writes it. + pub fn set_durable(&mut self, key: &str, value: &str) -> bool { + if !self.store.keeps_answers() + || self + .wrote_at + .is_some_and(|at| at.elapsed() < MIN_WRITE_INTERVAL) + { + return false; + } + let previous = self.entries.get(key).cloned(); + let dirty = self.dirty; + let bytes = self.bytes; + if !self.set(key, value) { + return false; + } + self.write_out(); + if !self.dirty { + return true; + } + + // A failed write must not turn into a delayed commit of a rejected change. + if let Some(previous) = previous { + self.entries.insert(key.to_owned(), previous); + } else { + self.entries.remove(key); + } + self.dirty = dirty; + self.bytes = bytes; + false + } + /// Write out whatever the call changed, if it changed anything. /// /// Called once when a wasm call returns, which is what bounds the I/O a @@ -393,6 +424,28 @@ mod tests { assert_eq!(Kv::open(files(&dir.0), "p").get("k"), Some("second")); } + #[test] + fn durable_writes_acknowledge_persistence_and_refusals_preserve_the_entry() { + let dir = TempDir::new("durable"); + let mut kv = Kv::open(files(&dir.0), "p"); + assert!(kv.set_durable("k", "committed")); + assert_eq!(Kv::open(files(&dir.0), "p").get("k"), Some("committed")); + assert!(!kv.set_durable("k", "too soon")); + assert_eq!(kv.get("k"), Some("committed")); + + let blocked = dir.0.join("blocked"); + std::fs::write(&blocked, "").unwrap(); + let mut kv = Kv::open(files(&blocked), "p"); + assert!(kv.set("k", "buffered")); + assert!(!kv.set_durable("k", "write failed")); + assert_eq!(kv.get("k"), Some("buffered")); + assert!(kv.due_at().is_some()); + + let mut memory_only = Kv::open(Arc::new(crate::store::Nowhere), "p"); + assert!(!memory_only.set_durable("k", "no backing store")); + assert_eq!(memory_only.get("k"), None); + } + #[test] fn an_empty_value_deletes() { let dir = TempDir::new("delete"); diff --git a/crates/plugin-host/src/tests.rs b/crates/plugin-host/src/tests.rs index 09f30840..f31d729f 100644 --- a/crates/plugin-host/src/tests.rs +++ b/crates/plugin-host/src/tests.rs @@ -1170,6 +1170,7 @@ fn the_schedule_plugin_submits_chat_forms_and_cancels_pending_messages() { .roots_in(PluginSlot::Settings) .any(|root| root.children.iter().any(|child| child.id == "cancel-1")) }); + std::thread::sleep(Duration::from_millis(1100)); plugins.act(&PluginAction { plugin: "schedule".into(), action: "cancel-1".into(), @@ -1185,6 +1186,7 @@ fn the_schedule_plugin_submits_chat_forms_and_cancels_pending_messages() { }); assert!(commands.sent().is_empty()); + std::thread::sleep(Duration::from_millis(1100)); assert!(plugins.approve("schedule", true)); let due = wacore::time::now_utc() + Duration::from_secs(3); plugins.act(&PluginAction { diff --git a/crates/plugin-sdk/src/lib.rs b/crates/plugin-sdk/src/lib.rs index 45f28359..e97e71d4 100644 --- a/crates/plugin-sdk/src/lib.rs +++ b/crates/plugin-sdk/src/lib.rs @@ -1207,6 +1207,20 @@ pub fn set(key: &str, value: &str) -> Outcome { }) } +/// Store a value and wait for the backing store to accept the write. +/// +/// Shares the normal storage write limit. A refused change is not queued. +pub fn set_durable(key: &str, value: &str) -> Outcome { + Outcome::of(unsafe { + raw::kv_set_durable( + raw::at(key.as_bytes()), + key.len() as i32, + raw::at(value.as_bytes()), + value.len() as i32, + ) + }) +} + /// A plugin's own small store, in the shapes a plugin actually keeps. /// /// Values are strings on the wire, because that is what the ABI carries. The diff --git a/crates/plugin-sdk/src/raw.rs b/crates/plugin-sdk/src/raw.rs index 6218dd87..87db47a6 100644 --- a/crates/plugin-sdk/src/raw.rs +++ b/crates/plugin-sdk/src/raw.rs @@ -82,6 +82,8 @@ unsafe extern "C" { pub fn kv_get(key: Ptr, key_len: i32, ptr: Ptr, cap: i32) -> i32; #[link_name = "oxi_kv_set"] pub fn kv_set(key: Ptr, key_len: i32, val: Ptr, val_len: i32) -> i32; + #[link_name = "oxi_kv_set_durable"] + pub fn kv_set_durable(key: Ptr, key_len: i32, val: Ptr, val_len: i32) -> i32; #[link_name = "oxi_timer_set"] pub safe fn timer_set(delay_ms: i64, token: i64) -> i32; @@ -199,6 +201,16 @@ mod off_target { borrow(val, val_len) }) } + pub unsafe fn kv_set_durable( + key: super::Ptr, + key_len: i32, + val: super::Ptr, + val_len: i32, + ) -> i32 { + testing::kv_set(unsafe { borrow(key, key_len) }, unsafe { + borrow(val, val_len) + }) + } pub fn timer_set(delay_ms: i64, token: i64) -> i32 { testing::command(testing::Command::Timer { delay_ms, token }) } @@ -271,6 +283,14 @@ mod off_target { pub unsafe fn kv_set(_key: super::Ptr, _key_len: i32, _val: super::Ptr, _val_len: i32) -> i32 { nowhere() } + pub unsafe fn kv_set_durable( + _key: super::Ptr, + _key_len: i32, + _val: super::Ptr, + _val_len: i32, + ) -> i32 { + nowhere() + } pub fn timer_set(_delay_ms: i64, _token: i64) -> i32 { nowhere() } diff --git a/docs/plugin-abi.md b/docs/plugin-abi.md index 9b412de9..d7ff3fd0 100644 --- a/docs/plugin-abi.md +++ b/docs/plugin-abi.md @@ -91,6 +91,7 @@ returns an outcome (below). | `oxi_ui_set` | `(ptr, len) -> i32` | `UI` | | `oxi_kv_get` | `(key, key_len, ptr, cap) -> i32` | `STORAGE` | | `oxi_kv_set` | `(key, key_len, val, val_len) -> i32` | `STORAGE` | +| `oxi_kv_set_durable` | `(key, key_len, val, val_len) -> i32` | `STORAGE` | | `oxi_timer_set` | `(delay_ms: i64, token: i64) -> i32` | `TIMERS` | | `oxi_log` | `(level: i32, ptr: i32, len: i32)` | none | | `oxi_now_ms` | `() -> i64` | none | @@ -102,6 +103,13 @@ action then writes over the user's own. An empty value passed to `oxi_kv_set` deletes the key. `oxi_ui_set` replaces the plugin's whole published tree. +`oxi_kv_set_durable` applies the same limits as `oxi_kv_set`. It returns +`ACCEPTED` only after the backing store acknowledges the write. It refuses +writes without persistent storage, during the normal one-second storage +write interval, or when the backing write fails. A refused change is not +queued. Use it before an external action that must not be replayed on restart. +Modules importing it need a host that provides this import. + `oxi_now_ms` is the only clock: Unix milliseconds, which is the resolution a plugin needs to stamp a message or space its own timers. Read it as the resolution and not as a mitigation. The host neither quantises nor jitters it, diff --git a/examples/schedule/src/lib.rs b/examples/schedule/src/lib.rs index d21b8b66..6c403433 100644 --- a/examples/schedule/src/lib.rs +++ b/examples/schedule/src/lib.rs @@ -8,6 +8,7 @@ plugin!(init = setup, event = handle, panic = own); const STORE: &str = "messages"; const TICK: i64 = 1; +const MAX_QUEUE_BYTES: usize = 8192; const MAX_JOBS: usize = 8; const MAX_MESSAGE: usize = 512; const POLL_MS: i64 = 5_000; @@ -21,7 +22,7 @@ struct Job { attempting: bool, } -#[derive(Default, Serialize, Deserialize)] +#[derive(Clone, Default, Serialize, Deserialize)] struct Queue { last_id: u64, jobs: Vec, @@ -44,7 +45,7 @@ fn setup(p: Setup) -> impl Declared { } fn read_queue() -> Result { - let stored = oxidezap_plugin::get::<8192>(STORE); + let stored = oxidezap_plugin::get::(STORE); let Some(raw) = stored.whole().filter(|_| !stored.refused()) else { return if stored.refused() || stored.present() { Err("The schedule could not be read.") @@ -58,12 +59,20 @@ fn read_queue() -> Result { serde_json::from_str(raw).map_err(|_| "The stored schedule could not be read.") } -fn save(queue: &Queue) -> Result<(), &'static str> { +fn save(queue: &Queue, durable: bool) -> Result<(), &'static str> { let raw = serde_json::to_string(queue).map_err(|_| "The schedule could not be saved.")?; - if oxidezap_plugin::set(STORE, &raw) == Outcome::Accepted { + if raw.len() > MAX_QUEUE_BYTES { + return Err("The schedule is past its storage limit."); + } + let outcome = if durable { + oxidezap_plugin::set_durable(STORE, &raw) + } else { + oxidezap_plugin::set(STORE, &raw) + }; + if outcome == Outcome::Accepted { Ok(()) } else { - Err("The schedule could not be saved.") + Err("The schedule could not be saved. Try again in a moment.") } } @@ -95,7 +104,7 @@ fn edit_queue(action: Action<'_>, queue: &mut Queue) -> Result<&'static str, &'s .and_then(|id| id.parse::().ok()) { queue.jobs.retain(|job| job.id != id); - save(queue)?; + save(queue, true)?; return Ok("Removed from the schedule."); } if !chat_supported(jid) { @@ -135,7 +144,7 @@ fn edit_queue(action: Action<'_>, queue: &mut Queue) -> Result<&'static str, &'s at, attempting: false, }); - save(queue)?; + save(queue, true)?; Ok("Message scheduled. Manage it in the plugin settings.") } @@ -153,7 +162,7 @@ fn tick(queue: &mut Queue) -> Result { }; // A restart between this write and the send cannot replay an uncertain send. queue.jobs[index].attempting = true; - save(queue)?; + save(queue, true)?; let job = &queue.jobs[index]; match oxidezap_plugin::send_text(&job.jid, &job.text) { Outcome::Accepted => { @@ -164,27 +173,26 @@ fn tick(queue: &mut Queue) -> Result { } Outcome::Invalid | Outcome::State => return Ok(true), } - save(queue)?; + save(queue, false)?; Ok(true) } fn handle(event: &Event) { match event.which() { Which::Action(action) => { - let mut queue = read_queue(); - let status = match queue.as_mut() { - Ok(queue) => match edit_queue(action, queue) { - Ok(status) | Err(status) => status, - }, - Err(error) => error, - }; - draw(&queue, status); + let queue = read_queue(); + let mut proposed = queue.clone(); + match proposed.as_mut().map(|queue| edit_queue(action, queue)) { + Ok(Ok(status)) => draw(&proposed, status), + Ok(Err(error)) => draw(&queue, error), + Err(error) => draw(&queue, error), + } } Which::Timer(timer) if timer.token() == TICK => { let mut queue = read_queue(); match queue.as_mut().map(tick) { Ok(Ok(true)) => draw(&queue, ""), - Ok(Err(error)) => draw(&queue, error), + Ok(Err(error)) => draw(&read_queue(), error), _ => {} } oxidezap_plugin::after(POLL_MS, TICK); @@ -313,6 +321,30 @@ mod tests { assert!(host.sent().is_empty()); } + #[test] + fn an_oversized_serialized_queue_does_not_publish_an_unsaved_job() { + let mut host = Host::new(); + host.init(setup); + let value = serde_json::json!({"message": "\0".repeat(512), "when": "1"}).to_string(); + for n in 0..3 { + host.set_now_ms(n * 60_000); + host.deliver( + In::action("schedule", &value).str(abi::fields::CHAT_JID, CHAT), + handle, + ); + } + let saved: Queue = serde_json::from_str(&host.stored(STORE).unwrap()).unwrap(); + assert_eq!(saved.jobs.len(), 2); + let tree = host.ui().unwrap().unwrap(); + assert_eq!( + tree.iter() + .flat_map(|node| &node.children) + .filter(|node| node.id.starts_with("cancel-")) + .count(), + 2 + ); + } + #[test] fn parses_offsets_without_assuming_the_daemon_timezone() { assert_eq!(deadline("1970-01-01T00:01:00Z", 0), Some(60_000)); From d4f51801a50929b85c7af214715836c0232691f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 15:42:47 -0300 Subject: [PATCH 10/11] fix(plugins): report unconfirmed writes and cancellation errors --- crates/plugin-abi/src/lib.rs | 1 + crates/plugin-host/src/guest.rs | 7 +- crates/plugin-host/src/kv.rs | 116 ++++++++++++++++--------- crates/plugin-host/src/lib.rs | 2 +- crates/plugin-host/src/store/mod.rs | 18 ++++ crates/plugin-host/src/store/native.rs | 30 +++---- crates/plugin-sdk/src/lib.rs | 5 +- docs/plugin-abi.md | 7 +- examples/schedule/src/lib.rs | 17 ++-- 9 files changed, 131 insertions(+), 72 deletions(-) diff --git a/crates/plugin-abi/src/lib.rs b/crates/plugin-abi/src/lib.rs index 4ea54405..b6135e5a 100644 --- a/crates/plugin-abi/src/lib.rs +++ b/crates/plugin-abi/src/lib.rs @@ -493,6 +493,7 @@ pub mod outcome { /// Called at a moment this is not allowed — a declaration outside /// `oxi_init`. pub const STATE: i32 = -5; + pub const UNCONFIRMED: i32 = -6; } /// A string field that is not there at all, distinct from one that is present diff --git a/crates/plugin-host/src/guest.rs b/crates/plugin-host/src/guest.rs index c74c2781..39007ece 100644 --- a/crates/plugin-host/src/guest.rs +++ b/crates/plugin-host/src/guest.rs @@ -981,12 +981,9 @@ fn link_acting(linker: &mut Linker) -> Result<(), wasmi::Error> { Err(code) => return code, }; let kv = &mut c.data_mut().kv; - let stored = if durable { + if durable { kv.set_durable(&key, &value) - } else { - kv.set(&key, &value) - }; - if stored { + } else if kv.set(&key, &value) { abi::outcome::ACCEPTED } else { abi::outcome::REFUSED diff --git a/crates/plugin-host/src/kv.rs b/crates/plugin-host/src/kv.rs index 8ba6180a..aa081f1d 100644 --- a/crates/plugin-host/src/kv.rs +++ b/crates/plugin-host/src/kv.rs @@ -14,7 +14,8 @@ use std::collections::BTreeMap; use std::sync::Arc; -use crate::store::Backing; +use crate::store::{Backing, ReplaceError}; +use oxidezap_plugin_abi::outcome; /// How much one plugin may keep. /// @@ -180,23 +181,24 @@ impl Kv { } /// Replace one entry and acknowledge only after the backing store writes it. - pub fn set_durable(&mut self, key: &str, value: &str) -> bool { + pub fn set_durable(&mut self, key: &str, value: &str) -> i32 { if !self.store.keeps_answers() || self .wrote_at .is_some_and(|at| at.elapsed() < MIN_WRITE_INTERVAL) { - return false; + return outcome::REFUSED; } let previous = self.entries.get(key).cloned(); let dirty = self.dirty; let bytes = self.bytes; if !self.set(key, value) { - return false; + return outcome::REFUSED; } - self.write_out(); - if !self.dirty { - return true; + match self.write_out() { + Ok(()) => return outcome::ACCEPTED, + Err(ReplaceError::Unconfirmed(_)) => return outcome::UNCONFIRMED, + Err(ReplaceError::Unchanged(_)) => {} } // A failed write must not turn into a delayed commit of a rejected change. @@ -207,7 +209,7 @@ impl Kv { } self.dirty = dirty; self.bytes = bytes; - false + outcome::REFUSED } /// Write out whatever the call changed, if it changed anything. @@ -225,7 +227,7 @@ impl Kv { { return; } - self.write_out(); + let _ = self.write_out(); } /// When the pending change may be written, if there is one. @@ -251,18 +253,17 @@ impl Kv { /// For the one place where there is no next commit: a plugin that is /// stopping. Everything else goes through [`commit`](Self::commit). pub fn flush_pending(&mut self) { - self.write_out(); + let _ = self.write_out(); } - fn write_out(&mut self) { - if self.dirty { - // Cleared only by a write that landed. Taking the flag first - // meant a full disk lost the change silently: the map held it, - // nothing was dirty any more, and the next restart read back the - // older file. - self.dirty = !self.flush(); - self.wrote_at = Some(wacore::time::Instant::now()); + fn write_out(&mut self) -> Result<(), ReplaceError> { + if !self.dirty { + return Ok(()); } + let result = self.flush(); + self.dirty = result.is_err(); + self.wrote_at = Some(wacore::time::Instant::now()); + result } /// What the entries weigh, computed once when the store is opened. @@ -280,27 +281,22 @@ impl Kv { /// Answers whether what is held is now stored. `true` for a memory-only /// store: there is nothing it could fail to write, so nothing stays /// pending. - fn flush(&mut self) -> bool { - let Ok(json) = serde_json::to_vec(&self.entries) else { - return false; - }; - match self.store.write(&self.name, &json) { - Ok(()) => { - self.complained = false; - true - } - Err(e) => { - if !self.complained { - self.complained = true; - log::warn!( - "cannot write {}: {e}. This plugin's settings will not survive a \ - restart.", - self.store.describe(&self.name) - ); - } - false + fn flush(&mut self) -> Result<(), ReplaceError> { + let json = serde_json::to_vec(&self.entries) + .map_err(|error| ReplaceError::Unchanged(error.to_string()))?; + let result = self.store.replace(&self.name, &json); + if let Err(error) = &result { + if !self.complained { + self.complained = true; + log::warn!( + "cannot confirm write to {}: {error:?}", + self.store.describe(&self.name) + ); } + } else { + self.complained = false; } + result } } @@ -428,24 +424,62 @@ mod tests { fn durable_writes_acknowledge_persistence_and_refusals_preserve_the_entry() { let dir = TempDir::new("durable"); let mut kv = Kv::open(files(&dir.0), "p"); - assert!(kv.set_durable("k", "committed")); + assert_eq!(kv.set_durable("k", "committed"), outcome::ACCEPTED); assert_eq!(Kv::open(files(&dir.0), "p").get("k"), Some("committed")); - assert!(!kv.set_durable("k", "too soon")); + assert_eq!(kv.set_durable("k", "too soon"), outcome::REFUSED); assert_eq!(kv.get("k"), Some("committed")); let blocked = dir.0.join("blocked"); std::fs::write(&blocked, "").unwrap(); let mut kv = Kv::open(files(&blocked), "p"); assert!(kv.set("k", "buffered")); - assert!(!kv.set_durable("k", "write failed")); + assert_eq!(kv.set_durable("k", "write failed"), outcome::REFUSED); assert_eq!(kv.get("k"), Some("buffered")); assert!(kv.due_at().is_some()); let mut memory_only = Kv::open(Arc::new(crate::store::Nowhere), "p"); - assert!(!memory_only.set_durable("k", "no backing store")); + assert_eq!( + memory_only.set_durable("k", "no backing store"), + outcome::REFUSED + ); assert_eq!(memory_only.get("k"), None); } + #[test] + fn a_replacement_with_unconfirmed_persistence_remains_visible() { + struct Unsynced(Files); + + impl Backing for Unsynced { + fn read(&self, name: &str, max: usize) -> Option> { + self.0.read(name, max) + } + + fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String> { + self.0.write(name, bytes) + } + + fn replace(&self, name: &str, bytes: &[u8]) -> Result<(), ReplaceError> { + self.write(name, bytes).map_err(ReplaceError::Unchanged)?; + Err(ReplaceError::Unconfirmed("directory sync failed".into())) + } + + fn remove(&self, name: &str) -> Result<(), String> { + self.0.remove(name) + } + + fn describe(&self, name: &str) -> String { + self.0.describe(name) + } + } + + let dir = TempDir::new("unconfirmed"); + let mut kv = Kv::open(Arc::new(Unsynced(Files::at(&dir.0))), "p"); + assert_eq!(kv.set_durable("k", "replacement"), outcome::UNCONFIRMED); + assert_eq!(kv.get("k"), Some("replacement")); + assert_eq!(Kv::open(files(&dir.0), "p").get("k"), kv.get("k")); + assert!(kv.due_at().is_some()); + } + #[test] fn an_empty_value_deletes() { let dir = TempDir::new("delete"); diff --git a/crates/plugin-host/src/lib.rs b/crates/plugin-host/src/lib.rs index 9e511a65..ea56b179 100644 --- a/crates/plugin-host/src/lib.rs +++ b/crates/plugin-host/src/lib.rs @@ -55,7 +55,7 @@ pub use registry::Sink; pub use store::Files; #[cfg(target_family = "wasm")] pub use store::Origin; -pub use store::{Backing, Nowhere}; +pub use store::{Backing, Nowhere, ReplaceError}; // What the store beside it asks of the filesystem: whether a file is one // another local account could have written, and how a write and a rename diff --git a/crates/plugin-host/src/store/mod.rs b/crates/plugin-host/src/store/mod.rs index 781452b3..63edd6af 100644 --- a/crates/plugin-host/src/store/mod.rs +++ b/crates/plugin-host/src/store/mod.rs @@ -13,6 +13,20 @@ //! What each implementation owes is narrower — hand back what was written, or //! nothing. +#[derive(Debug)] +pub enum ReplaceError { + Unchanged(String), + Unconfirmed(String), +} + +impl ReplaceError { + pub fn reason(self) -> String { + match self { + Self::Unchanged(reason) | Self::Unconfirmed(reason) => reason, + } + } +} + /// A named document that outlives the process. /// /// `Send + Sync` because the approvals are read from every thread the daemon @@ -39,6 +53,10 @@ pub trait Backing: Send + Sync + 'static { /// writes about it. fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String>; + fn replace(&self, name: &str, bytes: &[u8]) -> Result<(), ReplaceError> { + self.write(name, bytes).map_err(ReplaceError::Unchanged) + } + /// Remove `name`, durably. Missing is success. /// /// # Errors diff --git a/crates/plugin-host/src/store/native.rs b/crates/plugin-host/src/store/native.rs index 465877c8..e46fe3fe 100644 --- a/crates/plugin-host/src/store/native.rs +++ b/crates/plugin-host/src/store/native.rs @@ -8,7 +8,7 @@ use std::path::{Path, PathBuf}; -use super::Backing; +use super::{Backing, ReplaceError}; /// Files in one directory. Native only; a page has no directory to name. pub struct Files(PathBuf); @@ -61,6 +61,10 @@ impl Backing for Files { } fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String> { + self.replace(name, bytes).map_err(ReplaceError::reason) + } + + fn replace(&self, name: &str, bytes: &[u8]) -> Result<(), ReplaceError> { let path = self.path(name); // Unique per process and thread. A fixed name is one two daemons // sharing a state directory both write, so one can rename a file the @@ -70,22 +74,16 @@ impl Backing for Files { std::process::id(), std::thread::current().id() )); - let landed = crate::write_private(&temp, bytes) - .and_then(|()| std::fs::rename(&temp, &path)) - // The rename is metadata, and syncing the file did not persist - // it: an answer that reported success while the entry was still - // only in memory is a withdrawal the next start hands back. - .and_then(|()| match path.parent() { - Some(dir) => crate::sync_dir(dir), - None => Ok(()), - }); - match landed { - Ok(()) => Ok(()), - Err(e) => { - let _ = std::fs::remove_file(&temp); - Err(e.to_string()) - } + if let Err(error) = + crate::write_private(&temp, bytes).and_then(|()| std::fs::rename(&temp, &path)) + { + let _ = std::fs::remove_file(&temp); + return Err(ReplaceError::Unchanged(error.to_string())); + } + if let Some(dir) = path.parent() { + crate::sync_dir(dir).map_err(|error| ReplaceError::Unconfirmed(error.to_string()))?; } + Ok(()) } fn remove(&self, name: &str) -> Result<(), String> { diff --git a/crates/plugin-sdk/src/lib.rs b/crates/plugin-sdk/src/lib.rs index e97e71d4..24de042b 100644 --- a/crates/plugin-sdk/src/lib.rs +++ b/crates/plugin-sdk/src/lib.rs @@ -275,6 +275,8 @@ pub enum Outcome { /// [`Invalid`]: Self::Invalid /// [`Denied`]: Self::Denied State, + /// The entry changed, but its persistence could not be confirmed. + Unconfirmed, } impl Outcome { @@ -285,6 +287,7 @@ impl Outcome { abi::outcome::DENIED => Self::Denied, abi::outcome::REFUSED => Self::Refused, abi::outcome::STATE => Self::State, + abi::outcome::UNCONFIRMED => Self::Unconfirmed, _ => Self::Invalid, } } @@ -1209,7 +1212,7 @@ pub fn set(key: &str, value: &str) -> Outcome { /// Store a value and wait for the backing store to accept the write. /// -/// Shares the normal storage write limit. A refused change is not queued. +/// Shares the normal storage write limit. A refused change is not queued. An unconfirmed change is visible in memory. pub fn set_durable(key: &str, value: &str) -> Outcome { Outcome::of(unsafe { raw::kv_set_durable( diff --git a/docs/plugin-abi.md b/docs/plugin-abi.md index d7ff3fd0..6732fa78 100644 --- a/docs/plugin-abi.md +++ b/docs/plugin-abi.md @@ -106,8 +106,10 @@ plugin's whole published tree. `oxi_kv_set_durable` applies the same limits as `oxi_kv_set`. It returns `ACCEPTED` only after the backing store acknowledges the write. It refuses writes without persistent storage, during the normal one-second storage -write interval, or when the backing write fails. A refused change is not -queued. Use it before an external action that must not be replayed on restart. +write interval, or when the backing write fails before replacing the entry. +A refused change is not queued. If replacement succeeded but the backing +store could not confirm persistence, it returns `UNCONFIRMED` and keeps +the new value visible. Use it before an external action that must not be replayed on restart. Modules importing it need a host that provides this import. `oxi_now_ms` is the only clock: Unix milliseconds, which is the resolution a @@ -125,6 +127,7 @@ call's fuel, so nothing here is a promise about timing side channels. | `-2` | `REFUSED` | The daemon will not do this as asked. | | `-3` | `DENIED` | The plugin did not declare this capability, or the user has not agreed to it. | | `-4` | `INVALID` | A pointer outside memory, bytes that are not UTF-8, a length past what the host accepts. | +| `-6` | `UNCONFIRMED` | The store replaced the value but could not confirm persistence. | | `-5` | `STATE` | Right call, wrong moment — declaring outside `oxi_init`, or acting inside it. | `-1` is also `ABSENT` for the field reads, where there is no outcome to diff --git a/examples/schedule/src/lib.rs b/examples/schedule/src/lib.rs index 6c403433..83dec5ea 100644 --- a/examples/schedule/src/lib.rs +++ b/examples/schedule/src/lib.rs @@ -69,10 +69,12 @@ fn save(queue: &Queue, durable: bool) -> Result<(), &'static str> { } else { oxidezap_plugin::set(STORE, &raw) }; - if outcome == Outcome::Accepted { - Ok(()) - } else { - Err("The schedule could not be saved. Try again in a moment.") + match outcome { + Outcome::Accepted => Ok(()), + Outcome::Unconfirmed => Err( + "The schedule changed, but storage could not confirm the write. Check the list before retrying.", + ), + _ => Err("The schedule could not be saved. Try again in a moment."), } } @@ -171,7 +173,7 @@ fn tick(queue: &mut Queue) -> Result { Outcome::NoSession | Outcome::Denied | Outcome::Refused => { queue.jobs[index].attempting = false; } - Outcome::Invalid | Outcome::State => return Ok(true), + Outcome::Invalid | Outcome::State | Outcome::Unconfirmed => return Ok(true), } save(queue, false)?; Ok(true) @@ -184,7 +186,7 @@ fn handle(event: &Event) { let mut proposed = queue.clone(); match proposed.as_mut().map(|queue| edit_queue(action, queue)) { Ok(Ok(status)) => draw(&proposed, status), - Ok(Err(error)) => draw(&queue, error), + Ok(Err(error)) => draw(&read_queue(), error), Err(error) => draw(&queue, error), } } @@ -217,6 +219,9 @@ fn draw(queue: &Result, notice: &str) { } }); ui.section(ui::slot::SETTINGS, "Scheduled messages", |section| { + if !notice.is_empty() { + section.label(notice); + } let queue = match queue { Ok(queue) => queue, Err(error) => { From ee035676970187a25471b11ab119733db3ce1073 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas=20de=20Oliveira=20Lopes?= Date: Wed, 18 Nov 2026 16:01:58 -0300 Subject: [PATCH 11/11] fix(plugins): retain composer drafts and retry unsent jobs --- crates/gui/src/app/plugins_ctl.rs | 54 ++++++++++++++++++++++------- crates/plugin-host/src/store/mod.rs | 4 +++ crates/plugin-sdk/src/raw.rs | 2 +- crates/plugin-sdk/src/testing.rs | 15 ++++++++ examples/schedule/src/lib.rs | 23 +++++++++++- 5 files changed, 84 insertions(+), 14 deletions(-) diff --git a/crates/gui/src/app/plugins_ctl.rs b/crates/gui/src/app/plugins_ctl.rs index 40ba8958..1960beb6 100644 --- a/crates/gui/src/app/plugins_ctl.rs +++ b/crates/gui/src/app/plugins_ctl.rs @@ -6,7 +6,7 @@ //! which needs somewhere to hold what is being typed before anybody commits //! it — and that is what this file is. -use std::collections::HashMap; +use indexmap::IndexMap; use gpui::{App, AppContext as _, Context, Entity, Window}; use gpui_component::input::{InputEvent, InputState}; @@ -58,6 +58,7 @@ impl PluginField { /// oversized setting would disconnect the window. A plugin setting is a /// keyword or a sentence; anything of this size is a mistake either way. const MAX_FIELD_BYTES: usize = 64 * 1024; +const MAX_INACTIVE_COMPOSER_FIELDS: usize = 64; /// A field's address. Two plugins may both call a widget `keyword`, and one /// plugin may draw the same id in two slots. @@ -72,8 +73,8 @@ const MAX_FIELD_BYTES: usize = 64 * 1024; /// selection when Enter is pressed, so a box shared across chats would take /// what somebody typed in one and commit it carrying the other's JID — a /// plugin storing or sending it for the wrong conversation. Switching chats -/// therefore drops what was half-typed in the old one, which is the honest -/// trade: the alternative is not a preserved draft, it is a misdirected one. +/// drops legacy header fields. Composer drafts stay keyed to their own chat +/// until the plugin removes the field, the account changes, or the cache fills. /// /// Which is why the *same* answer `send_plugin_action` gives is taken here /// rather than the selection itself: a Settings action carries no chat, so @@ -289,14 +290,39 @@ impl Plugins { } } - // Gone means gone: a plugin that stopped drawing a field has taken it - // back, and holding the entity would keep a subscription alive that - // fires into a widget nobody can see. let live: std::collections::HashSet = wanted .iter() .map(|f| key(&f.plugin, f.slot, chat, &f.id)) .collect(); - self.fields.retain(|k, _| live.contains(k)); + let composers: std::collections::HashSet<_> = wanted + .iter() + .filter(|f| f.slot == PluginSlot::Composer) + .map(|f| (f.plugin.as_str(), f.id.as_str())) + .collect(); + let mut inactive = 0; + self.fields.retain(|key, field| { + if live.contains(key) { + return true; + } + if key.slot != PluginSlot::Composer + || !composers.contains(&(key.plugin.as_str(), key.id.as_str())) + { + return false; + } + let typed = field.state.read(cx).value(); + let keep = typed.len() <= MAX_FIELD_BYTES && typed.as_ref() != field.published; + inactive += usize::from(keep); + keep + }); + let mut excess = inactive.saturating_sub(MAX_INACTIVE_COMPOSER_FIELDS); + self.fields.retain(|key, _| { + if excess == 0 || live.contains(key) { + true + } else { + excess -= 1; + false + } + }); // What is left is what has no box yet. The ones that do are brought // up to date here, and only when the *plugin* moved them: a tree @@ -706,7 +732,7 @@ impl WhatsAppApp { cx.notify(); } - fn composer_form(&self, plugin: &str, cx: &App) -> Option { + fn composer_form(&self, plugin: &str, chat: &str, cx: &App) -> Option { let surface = self .plugins(cx) .iter() @@ -716,7 +742,8 @@ impl WhatsAppApp { collect_fields(plugin, PluginSlot::Composer, node, &mut fields); } let mut values = std::collections::BTreeMap::new(); - let mut remaining = MAX_FIELD_BYTES; + let limit = MAX_FIELD_BYTES.checked_sub(chat.len())?; + let mut remaining = limit; for field in fields { let value = self .plugin_field(plugin, PluginSlot::Composer, &field.id, cx)? @@ -727,7 +754,7 @@ impl WhatsAppApp { } serde_json::to_string(&values) .ok() - .filter(|value| value.len() <= MAX_FIELD_BYTES) + .filter(|value| value.len() <= limit) } /// Tell a plugin one of its widgets was used. @@ -751,7 +778,10 @@ impl WhatsAppApp { PluginSlot::Settings => None, }; let value = if slot == PluginSlot::Composer && widget == PluginWidget::Button { - let Some(form) = self.composer_form(plugin, cx) else { + let Some(form) = chat + .as_deref() + .and_then(|chat| self.composer_form(plugin, chat, cx)) + else { self.notify_user( crate::tr!(ComposerPluginFormUnavailable), super::notices::Tone::Problem, @@ -799,7 +829,7 @@ fn collect_fields(plugin: &str, slot: PluginSlot, node: &PluginNode, out: &mut V } /// The boxes, keyed by what names each one. -type PluginFields = HashMap; +type PluginFields = IndexMap; #[cfg(test)] mod tests { diff --git a/crates/plugin-host/src/store/mod.rs b/crates/plugin-host/src/store/mod.rs index 63edd6af..a788f3bc 100644 --- a/crates/plugin-host/src/store/mod.rs +++ b/crates/plugin-host/src/store/mod.rs @@ -53,6 +53,10 @@ pub trait Backing: Send + Sync + 'static { /// writes about it. fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String>; + /// Like `write`, preserving whether failure happened before replacement + /// or while confirming a replacement already visible to readers. + /// + /// Backends that can fail after replacement must override this method. fn replace(&self, name: &str, bytes: &[u8]) -> Result<(), ReplaceError> { self.write(name, bytes).map_err(ReplaceError::Unchanged) } diff --git a/crates/plugin-sdk/src/raw.rs b/crates/plugin-sdk/src/raw.rs index 87db47a6..af952760 100644 --- a/crates/plugin-sdk/src/raw.rs +++ b/crates/plugin-sdk/src/raw.rs @@ -207,7 +207,7 @@ mod off_target { val: super::Ptr, val_len: i32, ) -> i32 { - testing::kv_set(unsafe { borrow(key, key_len) }, unsafe { + testing::kv_set_durable(unsafe { borrow(key, key_len) }, unsafe { borrow(val, val_len) }) } diff --git a/crates/plugin-sdk/src/testing.rs b/crates/plugin-sdk/src/testing.rs index cca8c9c1..72609d30 100644 --- a/crates/plugin-sdk/src/testing.rs +++ b/crates/plugin-sdk/src/testing.rs @@ -138,6 +138,7 @@ struct State { subscription: i64, capabilities: i64, now_ms: i64, + unconfirmed_write: bool, } thread_local! { @@ -253,6 +254,11 @@ impl Host { } /// What `oxi_now_ms` answers. Zero unless a test says otherwise, so a + /// Replace the value on the next durable write and report uncertainty. + pub fn unconfirm_next_durable_write(&mut self) { + HOST.with(|host| host.borrow_mut().unconfirmed_write = true); + } + /// plugin that stamps something is testable at all. pub fn set_now_ms(&mut self, now: i64) { HOST.with(|h| h.borrow_mut().now_ms = now); @@ -370,6 +376,15 @@ pub(crate) fn kv_set(key: &str, value: &str) -> i32 { abi::outcome::ACCEPTED } +pub(crate) fn kv_set_durable(key: &str, value: &str) -> i32 { + let outcome = kv_set(key, value); + if HOST.with(|host| core::mem::take(&mut host.borrow_mut().unconfirmed_write)) { + abi::outcome::UNCONFIRMED + } else { + outcome + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/examples/schedule/src/lib.rs b/examples/schedule/src/lib.rs index 83dec5ea..5dbf4bf5 100644 --- a/examples/schedule/src/lib.rs +++ b/examples/schedule/src/lib.rs @@ -164,7 +164,13 @@ fn tick(queue: &mut Queue) -> Result { }; // A restart between this write and the send cannot replay an uncertain send. queue.jobs[index].attempting = true; - save(queue, true)?; + if let Err(error) = save(queue, true) { + // No send was attempted. Undo a marker that may have replaced the + // file so a later timer can try again. + queue.jobs[index].attempting = false; + save(queue, false)?; + return Err(error); + } let job = &queue.jobs[index]; match oxidezap_plugin::send_text(&job.jid, &job.text) { Outcome::Accepted => { @@ -306,6 +312,21 @@ mod tests { assert!(host.sent().is_empty()); } + #[test] + fn an_unconfirmed_marker_is_retried_without_sending_early() { + let mut host = Host::new(); + host.init(setup); + schedule(&mut host, CHAT, "1"); + host.set_now_ms(60_000); + host.unconfirm_next_durable_write(); + host.deliver(In::timer(TICK), handle); + assert!(host.sent().is_empty()); + let stored: Queue = serde_json::from_str(&host.stored(STORE).unwrap()).unwrap(); + assert!(!stored.jobs[0].attempting); + host.deliver(In::timer(TICK), handle); + assert_eq!(host.sent().len(), 1); + } + #[test] fn a_restart_does_not_replay_an_unconfirmed_attempt() { let mut host = Host::new();