Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: files changed app/src-tauri/src/lib.rs,app/src-tauri/src/whatsapp_data/global.rs,app/src-taur

Steven Enamakel8967e44b1bcc
diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs
index 1eaf7d9bb3..77aafb8ef4 100644
--- a/app/src-tauri/src/lib.rs
+++ b/app/src-tauri/src/lib.rs
@@ -73,7 +73,6 @@ mod ptt_overlay;
#[cfg(target_os = "windows")]
mod reset_reboot_schedule;
mod stderr_panic_hook;
-mod whatsapp_data;
mod window_state;
mod workspace_paths;
@@ -2946,7 +2945,6 @@ pub fn run() {
// in-process native handlers so the core agent tools (list/search)
// and the scanner ingest path can reach the SQLite store over the
// native request bus. No handler = graceful degradation core-side.
- whatsapp_data::register_native_handlers();
#[cfg(windows)]
{
@@ -3340,9 +3338,6 @@ pub fn run() {
// and the Save-As fallback needs it there (CodeRabbit on #4127).
artifact_commands::download_artifact_to_downloads,
// Structured WhatsApp data (store lives shell-side).
- whatsapp_data::whatsapp_data_list_chats,
- whatsapp_data::whatsapp_data_list_messages,
- whatsapp_data::whatsapp_data_search_messages,
check_core_update,
apply_core_update,
check_app_update,
diff --git a/app/src-tauri/src/whatsapp_data/global.rs b/app/src-tauri/src/whatsapp_data/global.rs
deleted file mode 100644
index e7e7a542f1..0000000000
--- a/app/src-tauri/src/whatsapp_data/global.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-//! Process-global WhatsApp data store singleton.
-//!
-//! One workspace-bound `WhatsAppDataStore` is active at a time, shared by
-//! native handlers, scanners, and Tauri commands. When the active workspace
-//! changes without relaunching the shell, the singleton is reopened for the new
-//! path so user data cannot leak across sessions.
-//!
-//! # Usage
-//!
-//! ```ignore
-//! // At startup:
-//! whatsapp_data::global::init(workspace_dir)?;
-//!
-//! // In RPC handlers:
-//! let store = whatsapp_data::global::store()?;
-//! ```
-
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, RwLock};
-
-use super::store::WhatsAppDataStore;
-
-/// Shared, thread-safe reference to the store.
-pub type WhatsAppDataStoreRef = Arc<WhatsAppDataStore>;
-
-// `RwLock<Option<…>>` rather than `OnceLock` so tests can swap workspaces
-// between runs (each test uses its own temp dir; without reset, the second
-// test would attach to a dropped sqlite path). Production callers still get
-// strict idempotency: `init` is a no-op once a store is set.
-struct WorkspaceStore {
- workspace_dir: PathBuf,
- store: WhatsAppDataStoreRef,
-}
-
-static GLOBAL_STORE: RwLock<Option<WorkspaceStore>> = RwLock::new(None);
-
-/// Initialise the global store for `workspace_dir`.
-///
-/// Reuses the current instance only when it is bound to the same workspace.
-/// A different path atomically replaces it with a freshly opened store.
-pub fn init(workspace_dir: PathBuf) -> Result<WhatsAppDataStoreRef, String> {
- let mut guard = GLOBAL_STORE
- .write()
- .map_err(|e| format!("[whatsapp_data:global] write lock poisoned: {e}"))?;
- if let Some(existing) = guard
- .as_ref()
- .filter(|entry| same_workspace(&entry.workspace_dir, &workspace_dir))
- {
- log::debug!("[whatsapp_data:global] already initialised");
- return Ok(Arc::clone(&existing.store));
- }
- log::info!(
- "[whatsapp_data:global] opening store workspace={}",
- workspace_dir.display()
- );
- let store = Arc::new(
- WhatsAppDataStore::new(&workspace_dir)
- .map_err(|e| format!("[whatsapp_data] store init failed: {e}"))?,
- );
- *guard = Some(WorkspaceStore {
- workspace_dir,
- store: Arc::clone(&store),
- });
- Ok(store)
-}
-
-fn same_workspace(current: &Path, requested: &Path) -> bool {
- current == requested
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn init_reuses_same_workspace_and_reopens_when_workspace_changes() {
- let first_dir = tempfile::tempdir().unwrap();
- let second_dir = tempfile::tempdir().unwrap();
-
- let first = init(first_dir.path().to_path_buf()).unwrap();
- let same = init(first_dir.path().to_path_buf()).unwrap();
- assert!(Arc::ptr_eq(&first, &same));
-
- let second = init(second_dir.path().to_path_buf()).unwrap();
- assert!(!Arc::ptr_eq(&first, &second));
- assert!(second_dir
- .path()
- .join("whatsapp_data/whatsapp_data.db")
- .exists());
- }
-}
diff --git a/app/src-tauri/src/whatsapp_data/mod.rs b/app/src-tauri/src/whatsapp_data/mod.rs
deleted file mode 100644
index 4dd092d6bf..0000000000
--- a/app/src-tauri/src/whatsapp_data/mod.rs
+++ /dev/null
@@ -1,146 +0,0 @@
-//! Shell-side structured WhatsApp Web data store (relocated from the core).
-//!
-//! Owns the SQLite persistence (`store`), the ingest + list/search business
-//! logic (`ops`), the busy/corrupt retry layer (`sqlite_retry`), and a
-//! process-global store singleton (`global`). The DB lives at
-//! `<workspace_dir>/whatsapp_data/whatsapp_data.db` — the same workspace the
-//! core resolves via [`Config`], so the file stays on the internal-path denylist
-//! (`security::policy` `WORKSPACE_INTERNAL_DIRS`) and agent tools cannot write it.
-//!
-//! Two callers reach this store:
-//!
-//! - **The scanner** (`whatsapp_scanner`) writes via the `whatsapp_data.ingest`
-//! native request (see [`register_native_handlers`]).
-//! - **The core agent tools** (`openhuman::channels::whatsapp_data::tools`) query via the
-//! `whatsapp_data.{list_chats,list_messages,search_messages}` native requests.
-//! - **The frontend** reads via the Tauri commands
-//! [`whatsapp_data_list_chats`] / [`whatsapp_data_list_messages`] /
-//! [`whatsapp_data_search_messages`].
-//!
-//! The shared DTOs (request/response/row types) are defined once in the core
-//! crate (`openhuman_core::openhuman::channels::whatsapp_data::types`) so both sides agree
-//! on a single definition and the native-request `TypeId` checks line up.
-
-mod global;
-mod ops;
-mod sqlite_retry;
-mod store;
-
-use std::sync::Arc;
-
-use openhuman_core::openhuman::channels::whatsapp_data::methods;
-use openhuman_core::openhuman::channels::whatsapp_data::types::{
- IngestRequest, IngestResult, ListChatsRequest, ListMessagesRequest, SearchMessagesRequest,
- WhatsAppChat, WhatsAppMessage,
-};
-use store::WhatsAppDataStore;
-
-/// Lazily open (or return) the shell's whatsapp_data store, bound to the active
-/// OpenHuman workspace dir.
-///
-/// The store is process-global so the scanner, native query handlers, and Tauri
-/// commands share one write lock and recovery lifecycle. Every call resolves
-/// the active workspace; [`global::init`] reuses the store only when that path
-/// still matches, and atomically reopens it after user/reset workspace changes.
-pub async fn ensure_store() -> Result<Arc<WhatsAppDataStore>, String> {
- let cfg = openhuman_core::openhuman::config::Config::load_or_init()
- .await
- .map_err(|e| format!("[whatsapp_data] config load failed: {e:#}"))?;
- log::debug!(
- "[whatsapp_data] ensuring shell store (workspace={})",
- cfg.workspace_dir.display()
- );
- global::init(cfg.workspace_dir.clone())
-}
-
-/// Register the in-process native request handlers that bridge the core (agent
-/// tools + scanner) to this shell store. Call once during Tauri `setup`.
-///
-/// Keyed by the method-name constants the core owns
-/// (`openhuman_core::openhuman::channels::whatsapp_data::methods`) so the two sides never
-/// drift on the string key.
-pub fn register_native_handlers() {
- use openhuman_core::core::bus::BUS;
-
- BUS.native()
- .register::<ListChatsRequest, Vec<WhatsAppChat>, _, _>(
- methods::LIST_CHATS,
- |req| async move {
- let store = ensure_store().await?;
- ops::list_chats(&store, req).map_err(|e| format!("{e:#}"))
- },
- );
- BUS.native()
- .register::<ListMessagesRequest, Vec<WhatsAppMessage>, _, _>(
- methods::LIST_MESSAGES,
- |req| async move {
- let store = ensure_store().await?;
- ops::list_messages(&store, req).map_err(|e| format!("{e:#}"))
- },
- );
- BUS.native()
- .register::<SearchMessagesRequest, Vec<WhatsAppMessage>, _, _>(
- methods::SEARCH_MESSAGES,
- |req| async move {
- let store = ensure_store().await?;
- ops::search_messages(&store, req).map_err(|e| format!("{e:#}"))
- },
- );
- BUS.native()
- .register::<IngestRequest, IngestResult, _, _>(methods::INGEST, |req| async move {
- let store = ensure_store().await?;
- // `{e:#}` renders the full anyhow chain so the underlying SQLite
- // cause (locked / malformed / FK) survives to the scanner's log.
- ops::ingest(&store, req).map_err(|e| format!("[whatsapp_data] ingest failed: {e:#}"))
- });
- log::info!(
- "[whatsapp_data] registered shell native handlers (list_chats / list_messages / search_messages / ingest)"
- );
-}
-
-// ── Tauri commands (frontend read surface) ───────────────────────────────────
-
-/// List locally-stored WhatsApp chats. Frontend replacement for the former
-/// `openhuman.whatsapp_data_list_chats` core RPC.
-#[tauri::command]
-pub async fn whatsapp_data_list_chats(req: ListChatsRequest) -> Result<Vec<WhatsAppChat>, String> {
- log::debug!(
- "[whatsapp_data][cmd] list_chats has_account={} limit={:?} offset={:?}",
- req.account_id.is_some(),
- req.limit,
- req.offset
- );
- let store = ensure_store().await?;
- ops::list_chats(&store, req).map_err(|e| format!("[whatsapp_data] list_chats failed: {e:#}"))
-}
-
-/// List messages for a chat. Frontend replacement for the former
-/// `openhuman.whatsapp_data_list_messages` core RPC.
-#[tauri::command]
-pub async fn whatsapp_data_list_messages(
- req: ListMessagesRequest,
-) -> Result<Vec<WhatsAppMessage>, String> {
- log::debug!(
- "[whatsapp_data][cmd] list_messages has_account={} (chat redacted)",
- req.account_id.is_some()
- );
- let store = ensure_store().await?;
- ops::list_messages(&store, req)
- .map_err(|e| format!("[whatsapp_data] list_messages failed: {e:#}"))
-}
-
-/// Full-text search over stored WhatsApp messages. Frontend-facing companion to
-/// the agent's `whatsapp_data_search_messages` tool.
-#[tauri::command]
-pub async fn whatsapp_data_search_messages(
- req: SearchMessagesRequest,
-) -> Result<Vec<WhatsAppMessage>, String> {
- log::debug!(
- "[whatsapp_data][cmd] search_messages has_account={} has_chat={}",
- req.account_id.is_some(),
- req.chat_id.is_some()
- );
- let store = ensure_store().await?;
- ops::search_messages(&store, req)
- .map_err(|e| format!("[whatsapp_data] search_messages failed: {e:#}"))
-}
diff --git a/app/src-tauri/src/whatsapp_data/ops.rs b/app/src-tauri/src/whatsapp_data/ops.rs
deleted file mode 100644
index efdbe331f7..0000000000
--- a/app/src-tauri/src/whatsapp_data/ops.rs
+++ /dev/null
@@ -1,198 +0,0 @@
-//! Business logic for WhatsApp data ingestion and retrieval.
-//!
-//! All operations take a `&WhatsAppDataStore` so callers control the store
-//! lifetime (shared `Arc` at runtime, fresh instance in tests).
-
-use anyhow::Result;
-
-use super::store::WhatsAppDataStore;
-use openhuman_core::openhuman::channels::whatsapp_data::types::{
- IngestRequest, IngestResult, ListChatsRequest, ListMessagesRequest, SearchMessagesRequest,
- WhatsAppChat, WhatsAppMessage,
-};
-
-/// Number of seconds in 90 days — the auto-prune horizon.
-const PRUNE_HORIZON_SECS: i64 = 90 * 24 * 60 * 60;
-
-/// Ingest a scanner snapshot: upsert chats and messages, then prune messages
-/// older than 90 days.
-///
-/// Returns counts for observability / logging at the RPC layer.
-pub fn ingest(store: &WhatsAppDataStore, req: IngestRequest) -> Result<IngestResult> {
- log::debug!(
- "[whatsapp_data] ingest start chats={} messages={} (account redacted)",
- req.chats.len(),
- req.messages.len()
- );
-
- let chats_upserted = store.upsert_chats(&req.account_id, &req.chats)?;
- let messages_upserted = store.upsert_messages(&req.account_id, &req.messages)?;
-
- let now = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs() as i64)
- .unwrap_or(0);
- let cutoff_ts = now - PRUNE_HORIZON_SECS;
- let messages_pruned = store.prune_old_messages(cutoff_ts)?;
-
- let result = IngestResult {
- chats_upserted,
- messages_upserted,
- messages_pruned,
- };
- log::debug!(
- "[whatsapp_data] ingest done chats_upserted={} messages_upserted={} pruned={} (account redacted)",
- result.chats_upserted,
- result.messages_upserted,
- result.messages_pruned
- );
- Ok(result)
-}
-
-/// Return chats from the local store, optionally filtered by account.
-pub fn list_chats(store: &WhatsAppDataStore, req: ListChatsRequest) -> Result<Vec<WhatsAppChat>> {
- log::debug!(
- "[whatsapp_data] list_chats has_account={} limit={:?} offset={:?}",
- req.account_id.is_some(),
- req.limit,
- req.offset
- );
- store.list_chats(&req)
-}
-
-/// Return messages for a chat, with optional time range and pagination.
-pub fn list_messages(
- store: &WhatsAppDataStore,
- req: ListMessagesRequest,
-) -> Result<Vec<WhatsAppMessage>> {
- log::debug!(
- "[whatsapp_data] list_messages has_account={} (chat/account redacted)",
- req.account_id.is_some()
- );
- store.list_messages(&req)
-}
-
-/// Full-text search over message bodies.
-pub fn search_messages(
- store: &WhatsAppDataStore,
- req: SearchMessagesRequest,
-) -> Result<Vec<WhatsAppMessage>> {
- log::debug!(
- "[whatsapp_data] search_messages has_account={} has_chat={} (query/identifiers redacted)",
- req.account_id.is_some(),
- req.chat_id.is_some()
- );
- store.search_messages(&req)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use openhuman_core::openhuman::channels::whatsapp_data::types::{ChatMeta, IngestMessage};
- use std::collections::HashMap;
- use tempfile::tempdir;
-
- fn make_store() -> (WhatsAppDataStore, tempfile::TempDir) {
- let tmp = tempdir().expect("tempdir");
- let store = WhatsAppDataStore::new(tmp.path()).expect("store");
- (store, tmp)
- }
-
- fn sample_request() -> IngestRequest {
- // Use a timestamp close to "now" so messages are not pruned by the
- // 90-day auto-prune horizon. We derive it from the system clock
- // minus one hour so even on slow CI boxes the message is comfortably
- // within the retention window.
- let recent_ts = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs() as i64 - 3600)
- .unwrap_or(1_750_000_000);
- let mut chats = HashMap::new();
- chats.insert(
- "[email protected]".to_string(),
- ChatMeta {
- name: Some("Alice".to_string()),
- },
- );
- IngestRequest {
- account_id: "acct1".to_string(),
- chats,
- messages: vec![IngestMessage {
- message_id: "msg1".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("Alice".to_string()),
- sender_jid: None,
- from_me: Some(false),
- body: Some("Hello!".to_string()),
- timestamp: Some(recent_ts),
- message_type: Some("chat".to_string()),
- source: Some("cdp-dom".to_string()),
- }],
- }
- }
-
- #[test]
- fn ingest_returns_correct_counts() {
- let (store, _tmp) = make_store();
- let result = ingest(&store, sample_request()).unwrap();
- assert_eq!(result.chats_upserted, 1);
- assert_eq!(result.messages_upserted, 1);
- }
-
- #[test]
- fn list_chats_after_ingest() {
- let (store, _tmp) = make_store();
- ingest(&store, sample_request()).unwrap();
-
- let chats = list_chats(
- &store,
- ListChatsRequest {
- account_id: None,
- limit: None,
- offset: None,
- },
- )
- .unwrap();
- assert_eq!(chats.len(), 1);
- assert_eq!(chats[0].chat_id, "[email protected]");
- }
-
- #[test]
- fn list_messages_after_ingest() {
- let (store, _tmp) = make_store();
- ingest(&store, sample_request()).unwrap();
-
- let msgs = list_messages(
- &store,
- ListMessagesRequest {
- chat_id: "[email protected]".to_string(),
- account_id: None,
- since_ts: None,
- until_ts: None,
- limit: None,
- offset: None,
- },
- )
- .unwrap();
- assert_eq!(msgs.len(), 1);
- assert_eq!(msgs[0].body, "Hello!");
- }
-
- #[test]
- fn search_messages_after_ingest() {
- let (store, _tmp) = make_store();
- ingest(&store, sample_request()).unwrap();
-
- let results = search_messages(
- &store,
- SearchMessagesRequest {
- query: "Hello".to_string(),
- chat_id: None,
- account_id: None,
- limit: None,
- },
- )
- .unwrap();
- assert_eq!(results.len(), 1);
- }
-}
diff --git a/app/src-tauri/src/whatsapp_data/sqlite_retry.rs b/app/src-tauri/src/whatsapp_data/sqlite_retry.rs
deleted file mode 100644
index 2673d28871..0000000000
--- a/app/src-tauri/src/whatsapp_data/sqlite_retry.rs
+++ /dev/null
@@ -1,240 +0,0 @@
-//! SQLite busy/locked detection and retry-with-backoff for WhatsApp data writes.
-//!
-//! The configured `busy_timeout` absorbs short waits inside rusqlite; this layer
-//! catches residual `SQLITE_BUSY` / `SQLITE_LOCKED` after that window.
-
-use std::thread;
-use std::time::Duration;
-
-// `anyhow::Error::context` (used in `retry_on_sqlite_busy`) is the inherent
-// method on `Error`, not the `Context` trait, so only `Result` is imported.
-use anyhow::Result;
-
-/// Per-connection busy handler window (issue #2077).
-pub const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);
-
-/// Application-level retries after rusqlite's busy handler is exhausted.
-const WRITE_RETRY_ATTEMPTS: u32 = 6;
-const WRITE_RETRY_BASE_MS: u64 = 25;
-
-/// Returns true when `err` is transient SQLite write-lock contention.
-pub fn is_sqlite_busy(err: &anyhow::Error) -> bool {
- if let Some(rusqlite::Error::SqliteFailure(sqlite_err, _)) =
- err.downcast_ref::<rusqlite::Error>()
- {
- return matches!(
- sqlite_err.code,
- rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked
- );
- }
- let msg = format!("{err:#}").to_ascii_lowercase();
- msg.contains("database is locked") || msg.contains("database table is locked")
-}
-
-/// Returns true when `err` is a `SQLITE_CORRUPT` malformed-image condition
-/// (primary code `DatabaseCorrupt`, code 11) or the closely-related
-/// `NotADatabase` (code 26 — the header itself is unreadable).
-///
-/// Unlike [`is_sqlite_busy`], a malformed on-disk image is **persistent
-/// damage**: the upsert can never succeed, so every scan poll (2–30s)
-/// re-opens the dead file, re-hits the error, and re-reports to Sentry —
-/// turning one corrupt file into an escalating flood (Sentry TAURI-RUST-KNH:
-/// 1,813 events from a single host). Detecting it here is what lets the store
-/// drive its quarantine + rebuild recovery instead of retrying forever.
-///
-/// Matching on the error **code** is rusqlite-version-stable. The text
-/// fallback covers the case where the rusqlite error was flattened to a plain
-/// `anyhow!` string across `.context()` layers — SQLite renders these as
-/// "database disk image is malformed" (code 11) and "file is not a database"
-/// (code 26).
-pub fn is_sqlite_corrupt(err: &anyhow::Error) -> bool {
- if let Some(rusqlite::Error::SqliteFailure(sqlite_err, _)) =
- err.downcast_ref::<rusqlite::Error>()
- {
- if matches!(
- sqlite_err.code,
- rusqlite::ErrorCode::DatabaseCorrupt | rusqlite::ErrorCode::NotADatabase
- ) {
- return true;
- }
- }
- let msg = format!("{err:#}").to_ascii_lowercase();
- msg.contains("disk image is malformed") || msg.contains("file is not a database")
-}
-
-/// Run `f` up to [`WRITE_RETRY_ATTEMPTS`] times when SQLite reports busy/locked.
-pub fn retry_on_sqlite_busy<T, F>(op_name: &str, mut f: F) -> Result<T>
-where
- F: FnMut() -> Result<T>,
-{
- let mut last_err: Option<anyhow::Error> = None;
-
- for attempt in 0..WRITE_RETRY_ATTEMPTS {
- match f() {
- Ok(val) => {
- if attempt > 0 {
- log::debug!("[whatsapp_data] {op_name} succeeded after {attempt} busy retries");
- }
- return Ok(val);
- }
- Err(e) => {
- if !is_sqlite_busy(&e) {
- return Err(e);
- }
- if attempt + 1 == WRITE_RETRY_ATTEMPTS {
- last_err = Some(e);
- break;
- }
- let sleep_ms = WRITE_RETRY_BASE_MS
- .saturating_mul(2u64.saturating_pow(attempt))
- .min(500);
- log::warn!(
- "[whatsapp_data] {op_name} SQLite busy/locked \
- (attempt {} of {WRITE_RETRY_ATTEMPTS}), retry in {sleep_ms}ms: {e:#}",
- attempt + 1,
- );
- thread::sleep(Duration::from_millis(sleep_ms));
- }
- }
- }
-
- Err(last_err.expect("WRITE_RETRY_ATTEMPTS > 0").context(format!(
- "{op_name} failed after {WRITE_RETRY_ATTEMPTS} SQLite busy retries"
- )))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn is_sqlite_busy_matches_database_busy_code() {
- let raw = rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::DatabaseBusy,
- extended_code: 5,
- },
- Some("database is locked".into()),
- );
- let err = anyhow::Error::from(raw);
- assert!(is_sqlite_busy(&err));
- }
-
- #[test]
- fn is_sqlite_busy_does_not_match_constraint_violation() {
- let raw = rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::ConstraintViolation,
- extended_code: 19,
- },
- Some("UNIQUE constraint failed".into()),
- );
- let err = anyhow::Error::from(raw);
- assert!(!is_sqlite_busy(&err));
- }
-
- #[test]
- fn is_sqlite_corrupt_matches_database_corrupt_code() {
- let raw = rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::DatabaseCorrupt,
- extended_code: 11,
- },
- Some("database disk image is malformed".into()),
- );
- assert!(is_sqlite_corrupt(&anyhow::Error::from(raw)));
- }
-
- #[test]
- fn is_sqlite_corrupt_matches_not_a_database_code() {
- let raw = rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::NotADatabase,
- extended_code: 26,
- },
- Some("file is not a database".into()),
- );
- assert!(is_sqlite_corrupt(&anyhow::Error::from(raw)));
- }
-
- #[test]
- fn is_sqlite_corrupt_matches_through_context_layers() {
- let raw = rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::DatabaseCorrupt,
- extended_code: 11,
- },
- Some("database disk image is malformed".into()),
- );
- let wrapped = anyhow::Error::from(raw)
- .context("upsert wa_chat 207897942335683@lid")
- .context("[whatsapp_data] ingest failed");
- assert!(is_sqlite_corrupt(&wrapped));
- }
-
- #[test]
- fn is_sqlite_corrupt_text_fallback() {
- let err = anyhow::anyhow!(
- "[whatsapp_data] ingest failed: upsert wa_chat 207897942335683@lid: \
- database disk image is malformed: Error code 11: The database disk image is malformed"
- );
- assert!(is_sqlite_corrupt(&err));
- }
-
- #[test]
- fn is_sqlite_corrupt_does_not_match_busy_or_constraint() {
- let busy = rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::DatabaseBusy,
- extended_code: 5,
- },
- Some("database is locked".into()),
- );
- assert!(!is_sqlite_corrupt(&anyhow::Error::from(busy)));
-
- let constraint = rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::ConstraintViolation,
- extended_code: 19,
- },
- Some("UNIQUE constraint failed".into()),
- );
- assert!(!is_sqlite_corrupt(&anyhow::Error::from(constraint)));
-
- assert!(!is_sqlite_corrupt(&anyhow::anyhow!(
- "upstream returned 500: internal server error"
- )));
- }
-
- #[test]
- fn retry_on_sqlite_busy_succeeds_after_transient_busy() {
- let mut calls = 0u32;
- let result = retry_on_sqlite_busy("test_op", || {
- calls += 1;
- if calls < 3 {
- Err(anyhow::Error::from(rusqlite::Error::SqliteFailure(
- rusqlite::ffi::Error {
- code: rusqlite::ErrorCode::DatabaseBusy,
- extended_code: 5,
- },
- Some("database is locked".into()),
- )))
- } else {
- Ok(42usize)
- }
- });
- assert_eq!(result.unwrap(), 42);
- assert_eq!(calls, 3);
- }
-
- #[test]
- fn retry_on_sqlite_busy_does_not_retry_non_busy_errors() {
- let mut calls = 0u32;
- let result: Result<()> = retry_on_sqlite_busy("test_op", || {
- calls += 1;
- anyhow::bail!("permanent failure");
- });
- assert!(result.is_err());
- assert_eq!(calls, 1);
- }
-}
diff --git a/app/src-tauri/src/whatsapp_data/store.rs b/app/src-tauri/src/whatsapp_data/store.rs
deleted file mode 100644
index 889809f319..0000000000
--- a/app/src-tauri/src/whatsapp_data/store.rs
+++ /dev/null
@@ -1,1100 +0,0 @@
-//! SQLite-backed persistence for structured WhatsApp Web data.
-//!
-//! Data is stored in a dedicated `whatsapp_data.db` file inside the
-//! workspace directory. Tables: `wa_chats` and `wa_messages`.
-//!
-//! This store is local-only; no data is transmitted to external services.
-
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::Mutex;
-
-use anyhow::{Context, Result};
-use rusqlite::{params, Connection};
-
-use super::sqlite_retry::{is_sqlite_corrupt, retry_on_sqlite_busy, BUSY_TIMEOUT};
-use openhuman_core::openhuman::channels::whatsapp_data::types::{
- ChatMeta, IngestMessage, ListChatsRequest, ListMessagesRequest, SearchMessagesRequest,
- WhatsAppChat, WhatsAppMessage,
-};
-
-/// Process-wide latch so a `SQLITE_CORRUPT` flood is reported to Sentry
-/// **once**, not on every scan tick. The whatsapp_scanner re-ingests every
-/// 2–30s, so a wedged DB re-hits the malformed-image error on each poll — one
-/// corrupt file produced 1,813 escalating Sentry events from a single host
-/// (TAURI-RUST-KNH). Set on the first detection; cleared once a recovery
-/// attempt settles (quarantine + rebuild, or a quick_check that now passes) so
-/// a genuinely-new, later corruption can still page exactly once.
-static CORRUPT_REPORTED: AtomicBool = AtomicBool::new(false);
-
-/// Test-only override: when set, [`WhatsAppDataStore::integrity_check_ok`]
-/// reports the (rebuilt) DB as failing its integrity check. This is the seam
-/// that lets tests drive the "rebuild still fails integrity_check" branch of
-/// [`WhatsAppDataStore::recover_corrupt_db`] without forging a file that both
-/// survives quarantine and yet fails `PRAGMA integrity_check`.
-#[cfg(test)]
-static FORCE_INTEGRITY_CHECK_FAIL: AtomicBool = AtomicBool::new(false);
-
-/// Test-only serialization guard for the recovery-episode tests. `CORRUPT_REPORTED`
-/// and `FORCE_INTEGRITY_CHECK_FAIL` are process-wide, so tests that mutate them
-/// must not run concurrently or they clobber each other's latch observations.
-#[cfg(test)]
-static CORRUPT_TEST_GUARD: Mutex<()> = Mutex::new(());
-
-/// SQLite-backed store for WhatsApp chats and messages.
-pub struct WhatsAppDataStore {
- db_path: std::path::PathBuf,
- /// Serializes write paths (upsert + prune) so concurrent ingest RPCs do not
- /// open competing writers on the same `whatsapp_data.db` file.
- write_lock: Mutex<()>,
-}
-
-impl WhatsAppDataStore {
- /// Open or create the `whatsapp_data.db` SQLite database in `workspace_dir`.
- /// The directory (and any parents) are created if they do not exist.
- pub fn new(workspace_dir: &Path) -> Result<Self> {
- let db_path = workspace_dir.join("whatsapp_data").join("whatsapp_data.db");
- if let Some(parent) = db_path.parent() {
- std::fs::create_dir_all(parent)
- .with_context(|| format!("create whatsapp_data dir: {}", parent.display()))?;
- }
- log::debug!("[whatsapp_data] opening store at {}", db_path.display());
- let store = Self {
- db_path,
- write_lock: Mutex::new(()),
- };
- store.init_schema_or_recover()?;
- Ok(store)
- }
-
- /// Initialize the schema, self-healing a DB that is already corrupt **at
- /// process startup**.
- ///
- /// Without this, a `whatsapp_data.db` that is malformed before the first
- /// write RPC arrives makes `init_schema()` fail, `global::init` leaves the
- /// store singleton unset, and every subsequent ingest RPC fails with
- /// "store accessed before init" — the corruption never reaches the
- /// quarantine + rebuild path (which only guards the *write* wrapper), so it
- /// survives restarts and re-pages Sentry on every scanner tick. Recovering
- /// here makes a boot-time corrupt DB heal exactly as a mid-run one does.
- ///
- /// The `CORRUPT_REPORTED` latch semantics are reused verbatim via
- /// [`Self::report_and_recover`] (report once per episode, reset only on a
- /// confirmed-healthy rebuild), so a boot-time corruption pages at most once.
- fn init_schema_or_recover(&self) -> Result<()> {
- match self.init_schema() {
- Ok(()) => Ok(()),
- Err(e) if is_sqlite_corrupt(&e) => {
- log::error!(
- "[whatsapp_data] init_schema hit SQLITE_CORRUPT at startup for {} — \
- driving quarantine + rebuild before ingest can begin: {e:#}",
- self.db_path.display()
- );
- // Reports once (latch), quarantines the malformed image, and
- // rebuilds the schema. `recover_corrupt_db` is safe to call on
- // the just-constructed store: it only needs `db_path` +
- // `init_schema`, both available before the store is published.
- self.report_and_recover("init_schema", &e);
- // Confirm the store is now usable. If recovery failed, this
- // re-init returns Err and `global::init` correctly leaves the
- // singleton unset — but now only when the DB is genuinely
- // unrecoverable, not merely corrupt-on-boot.
- self.init_schema()
- .context("re-init whatsapp_data schema after boot-time corrupt-DB recovery")
- }
- Err(e) => Err(e),
- }
- }
-
- /// Initialize the schema. Idempotent — safe to call on every startup.
- fn init_schema(&self) -> Result<()> {
- let conn = self.open_conn()?;
- conn.execute_batch(
- "PRAGMA journal_mode = WAL;
- PRAGMA foreign_keys = ON;
-
- CREATE TABLE IF NOT EXISTS wa_chats (
- account_id TEXT NOT NULL,
- chat_id TEXT NOT NULL,
- display_name TEXT NOT NULL DEFAULT '',
- is_group INTEGER NOT NULL DEFAULT 0,
- last_message_ts INTEGER NOT NULL DEFAULT 0,
- message_count INTEGER NOT NULL DEFAULT 0,
- updated_at INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (account_id, chat_id)
- );
-
- CREATE TABLE IF NOT EXISTS wa_messages (
- account_id TEXT NOT NULL,
- chat_id TEXT NOT NULL,
- message_id TEXT NOT NULL,
- sender TEXT NOT NULL DEFAULT '',
- sender_jid TEXT,
- from_me INTEGER NOT NULL DEFAULT 0,
- body TEXT NOT NULL DEFAULT '',
- timestamp INTEGER NOT NULL DEFAULT 0,
- message_type TEXT,
- source TEXT NOT NULL DEFAULT '',
- ingested_at INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (account_id, chat_id, message_id)
- );
- CREATE INDEX IF NOT EXISTS idx_wa_msg_ts ON wa_messages(account_id, chat_id, timestamp);
- CREATE INDEX IF NOT EXISTS idx_wa_msg_body ON wa_messages(account_id, body);",
- )
- .context("init whatsapp_data schema")?;
- log::debug!("[whatsapp_data] schema ready");
- Ok(())
- }
-
- /// Open a fresh connection to the DB file.
- ///
- /// Read paths (`list_chats` / `list_messages` / `search_messages`) call this
- /// **without** taking `write_lock`, so a read can race the brief file-rename
- /// window inside [`Self::recover_corrupt_db`] (which quarantines the corrupt
- /// image then rebuilds under `write_lock`). We deliberately do NOT serialize
- /// reads behind the write lock: the race is not a correctness or
- /// data-integrity problem, only a rare transient read error that self-heals
- /// on the next poll. Three outcomes are possible and all are safe —
- /// (1) the read opens before the rename and reads valid (old) data via its
- /// still-live fd; (2) it opens after the rebuild and reads the fresh schema;
- /// (3) it opens in the sub-millisecond gap after the rename but before the
- /// rebuild, gets an empty auto-created file, and returns a benign
- /// "no such table" error the caller retries. Guarding this hot path with a
- /// global read/write lock would trade that vanishingly-rare transient for
- /// permanent read/write contention on every list/search — not worth it.
- fn open_conn(&self) -> Result<Connection> {
- let conn = Connection::open(&self.db_path)
- .with_context(|| format!("open whatsapp_data db: {}", self.db_path.display()))?;
- Self::configure_connection(&conn)?;
- Ok(conn)
- }
-
- /// Per-connection pragmas: busy handler + WAL (idempotent on existing DBs).
- fn configure_connection(conn: &Connection) -> Result<()> {
- conn.busy_timeout(BUSY_TIMEOUT)
- .context("configure whatsapp_data busy_timeout")?;
- if let Err(wal_err) = conn.execute_batch("PRAGMA journal_mode=WAL;") {
- log::warn!(
- "[whatsapp_data] failed to enable WAL (filesystem may not support it): {wal_err}"
- );
- }
- Ok(())
- }
-
- #[cfg(test)]
- pub(crate) fn open_conn_for_test(&self) -> Result<Connection> {
- self.open_conn()
- }
-
- fn now_secs() -> i64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs() as i64)
- .unwrap_or(0)
- }
-
- /// Run a write op through the busy-retry loop, and on a confirmed
- /// `SQLITE_CORRUPT` malformed-image error drive a **once-per-call**
- /// quarantine + rebuild recovery, then retry the op a single time against
- /// the rebuilt schema.
- ///
- /// The recovery is bounded: at most one quarantine attempt and one retry
- /// per public write call. A genuinely unrecoverable file therefore returns
- /// the corrupt error to the caller after one recovery pass instead of
- /// spinning — the process-wide report latch (`report_and_recover`) then
- /// keeps Sentry from re-flooding on every scan tick.
- fn write_with_corrupt_recovery<T>(
- &self,
- op_name: &str,
- f: impl Fn() -> Result<T>,
- ) -> Result<T> {
- match retry_on_sqlite_busy(op_name, &f) {
- Ok(val) => Ok(val),
- Err(e) if is_sqlite_corrupt(&e) => {
- self.report_and_recover(op_name, &e);
- // Retry once against the (now rebuilt) DB. If this still fails,
- // the error propagates — no further recovery, so a wedged
- // filesystem can't loop.
- retry_on_sqlite_busy(op_name, &f)
- }
- Err(e) => Err(e),
- }
- }
-
- /// Report a confirmed `SQLITE_CORRUPT` failure to Sentry and drive the
- /// quarantine + rebuild recovery. Factored out of
- /// [`Self::write_with_corrupt_recovery`] so the report + recovery decision
- /// is unit-testable without a live scanner loop.
- fn report_and_recover(&self, op_name: &str, err: &anyhow::Error) {
- // Report to Sentry at most once per corruption episode. Without this
- // latch the scanner's 2–30s poll re-hits the wedged DB and re-pages on
- // every tick (TAURI-RUST-KNH: 1,813 events from one host).
- if !CORRUPT_REPORTED.swap(true, Ordering::Relaxed) {
- openhuman_core::core::observability::report_error(
- err,
- "whatsapp_data",
- "ingest_corrupt",
- &[("op", op_name)],
- );
- }
- log::error!(
- "[whatsapp_data] {op_name} hit SQLITE_CORRUPT (malformed DB image), \
- attempting quarantine + rebuild recovery: {err:#}"
- );
- match self.recover_corrupt_db() {
- Ok(true) => {
- log::warn!(
- "[whatsapp_data] {op_name} quarantined corrupt DB and rebuilt empty schema; \
- ingest will resume"
- );
- // Recovery settled — allow a future, genuinely-new corruption
- // to page once more.
- CORRUPT_REPORTED.store(false, Ordering::Relaxed);
- }
- Ok(false) => {
- log::info!(
- "[whatsapp_data] {op_name} corruption recovery: integrity check now passes, \
- no quarantine needed"
- );
- CORRUPT_REPORTED.store(false, Ordering::Relaxed);
- }
- Err(rec_err) => log::error!(
- "[whatsapp_data] {op_name} corruption recovery FAILED, ingest stays degraded: \
- {rec_err:#}"
- ),
- }
- }
-
- /// Recover from a `SQLITE_CORRUPT` (malformed image) on the whatsapp_data DB.
- ///
- /// A malformed on-disk image never heals on its own — every write fails
- /// forever and the scanner re-pages Sentry on each poll (Sentry
- /// TAURI-RUST-KNH: 1,813 events from a single host). This quarantines the
- /// damaged file (and its WAL/SHM side-files) to a timestamped
- /// `.corrupt-<ts>` copy — **preserved, not deleted**, so the bytes can be
- /// inspected or salvaged — then rebuilds an empty schema so ingest resumes.
- ///
- /// Returns `Ok(true)` when a quarantine + rebuild happened, `Ok(false)`
- /// when a fresh `PRAGMA quick_check` now passes (the earlier failure was
- /// transient and quarantining would have destroyed good data), and `Err`
- /// when the quarantine rename or the schema rebuild failed.
- ///
- /// The store opens a fresh `Connection` per call (no cached handle), so no
- /// connection needs to be dropped before the rename — the next `open_conn`
- /// naturally picks up the rebuilt file.
- pub(crate) fn recover_corrupt_db(&self) -> Result<bool> {
- // 1. Re-confirm corruption against the on-disk file. `quick_check` is
- // the cheap structural scan; if it now reports "ok" the image is
- // actually healthy (e.g. the original error was a transient mmap
- // fault) and we must NOT destroy good data — bail without quarantine.
- if self.db_path.exists() {
- match self.quick_check_ok() {
- Ok(true) => {
- log::info!(
- "[whatsapp_data] quick_check passed for {} — no quarantine needed",
- self.db_path.display()
- );
- return Ok(false);
- }
- Ok(false) => {
- log::warn!(
- "[whatsapp_data] quick_check confirms corruption for {}, quarantining",
- self.db_path.display()
- );
- }
- Err(e) => {
- // The check couldn't even run (unopenable / unreadable
- // header). That is itself a malformed-image signal.
- log::warn!(
- "[whatsapp_data] quick_check could not run for {} ({e:#}); \
- treating as corrupt",
- self.db_path.display()
- );
- }
- }
- } else {
- log::warn!(
- "[whatsapp_data] corrupt-recovery: {} is missing; rebuilding fresh schema",
- self.db_path.display()
- );
- }
-
- // 2. Quarantine the main DB + WAL/SHM side-files to `<name>.corrupt-<ts>`.
- let ts = Self::now_secs();
- let mut quarantined = 0usize;
- for suffix in &["", "-wal", "-shm"] {
- let src = with_name_suffix(&self.db_path, suffix);
- if !src.exists() {
- continue;
- }
- let dst = with_name_suffix(&src, &format!(".corrupt-{ts}"));
- std::fs::rename(&src, &dst).with_context(|| {
- format!(
- "quarantine corrupt whatsapp_data file {} -> {}",
- src.display(),
- dst.display()
- )
- })?;
- log::warn!(
- "[whatsapp_data] quarantined {} -> {}",
- src.display(),
- dst.display()
- );
- quarantined += 1;
- }
-
- // 3. Rebuild an empty schema by re-running init on a fresh file. The
- // damaged rows are not silently dropped — they live on in the
- // `.corrupt-<ts>` copy.
- self.init_schema()
- .context("rebuild whatsapp_data schema after quarantining corrupt DB")?;
-
- // 4. Confirm the rebuilt image is structurally sound. This result is
- // load-bearing: `report_and_recover` only resets the process-wide
- // `CORRUPT_REPORTED` latch (and logs "ingest will resume") on
- // `Ok(true)`. If the rebuild still fails integrity_check — or the
- // check itself can't run — we MUST surface `Err`, otherwise the
- // latch resets, re-arming Sentry to page on the next scan tick and
- // breaking the report-once-per-episode guarantee this recovery
- // exists to protect.
- match self.integrity_check_ok() {
- Ok(true) => {
- log::warn!(
- "[whatsapp_data] corruption recovery complete: quarantined {quarantined} file(s), \
- rebuilt empty schema, integrity_check=ok at {}",
- self.db_path.display()
- );
- Ok(true)
- }
- Ok(false) => {
- log::error!(
- "[whatsapp_data] rebuilt DB still fails integrity_check at {}",
- self.db_path.display()
- );
- Err(anyhow::anyhow!(
- "rebuilt whatsapp_data db still fails integrity_check at {}",
- self.db_path.display()
- ))
- }
- Err(e) => Err(e.context("integrity_check after rebuild could not run")),
- }
- }
-
- /// Run `PRAGMA quick_check(1)` on a fresh, short-lived connection. Returns
- /// `Ok(true)` when the structural scan reports `"ok"`, `Ok(false)` on any
- /// reported corruption, and `Err` when the check itself can't run (file
- /// unopenable / header unreadable — itself a corruption signal the caller
- /// treats as malformed).
- fn quick_check_ok(&self) -> Result<bool> {
- let conn = Connection::open(&self.db_path)
- .with_context(|| format!("open for quick_check: {}", self.db_path.display()))?;
- let _ = conn.busy_timeout(BUSY_TIMEOUT);
- let result: String = conn
- .query_row("PRAGMA quick_check(1)", [], |row| row.get(0))
- .context("running PRAGMA quick_check")?;
- Ok(result.eq_ignore_ascii_case("ok"))
- }
-
- /// Run `PRAGMA integrity_check(1)` against the (rebuilt) DB to confirm it is
- /// structurally sound. Returns `Ok(true)` when it reports `"ok"`.
- fn integrity_check_ok(&self) -> Result<bool> {
- #[cfg(test)]
- if FORCE_INTEGRITY_CHECK_FAIL.load(Ordering::Relaxed) {
- return Ok(false);
- }
- let conn = self.open_conn()?;
- let result: String = conn
- .query_row("PRAGMA integrity_check(1)", [], |row| row.get(0))
- .context("running PRAGMA integrity_check")?;
- Ok(result.eq_ignore_ascii_case("ok"))
- }
-
- /// Upsert chat metadata rows. Returns the number of rows inserted or updated.
- pub fn upsert_chats(
- &self,
- account_id: &str,
- chats: &HashMap<String, ChatMeta>,
- ) -> Result<usize> {
- if chats.is_empty() {
- return Ok(0);
- }
- let _write_guard = self
- .write_lock
- .lock()
- .map_err(|e| anyhow::anyhow!("whatsapp_data write lock poisoned: {e}"))?;
- self.write_with_corrupt_recovery("upsert_chats", || {
- self.upsert_chats_inner(account_id, chats)
- })
- }
-
- fn upsert_chats_inner(
- &self,
- account_id: &str,
- chats: &HashMap<String, ChatMeta>,
- ) -> Result<usize> {
- let conn = self.open_conn()?;
- let now = Self::now_secs();
- let mut count = 0usize;
- for (chat_id, meta) in chats {
- let name = meta.name.as_deref().unwrap_or("");
- let is_group = chat_id.ends_with("@g.us") as i64;
- conn.execute(
- "INSERT INTO wa_chats (account_id, chat_id, display_name, is_group, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5)
- ON CONFLICT(account_id, chat_id) DO UPDATE SET
- display_name = CASE WHEN excluded.display_name != '' THEN excluded.display_name ELSE display_name END,
- is_group = excluded.is_group,
- updated_at = excluded.updated_at",
- params![account_id, chat_id, name, is_group, now],
- )
- .with_context(|| format!("upsert wa_chat {chat_id}"))?;
- count += 1;
- }
- log::debug!(
- "[whatsapp_data] upserted {} chats (account redacted)",
- count
- );
- Ok(count)
- }
-
- /// Upsert message rows. Returns the number of rows inserted or updated.
- pub fn upsert_messages(&self, account_id: &str, msgs: &[IngestMessage]) -> Result<usize> {
- if msgs.is_empty() {
- return Ok(0);
- }
- let _write_guard = self
- .write_lock
- .lock()
- .map_err(|e| anyhow::anyhow!("whatsapp_data write lock poisoned: {e}"))?;
- self.write_with_corrupt_recovery("upsert_messages", || {
- self.upsert_messages_inner(account_id, msgs)
- })
- }
-
- fn upsert_messages_inner(&self, account_id: &str, msgs: &[IngestMessage]) -> Result<usize> {
- let conn = self.open_conn()?;
- let now = Self::now_secs();
- let mut count = 0usize;
- for m in msgs {
- if m.message_id.is_empty() || m.chat_id.is_empty() {
- continue;
- }
- // Persist all messages, including non-text ones (stickers, images,
- // system events). Dropping empty-body rows biases message_count
- // and last_message_ts to text-only messages, making active chats
- // look stale whenever the latest event has no body.
- let body = m.body.as_deref().unwrap_or("");
- let ts = m.timestamp.unwrap_or(0);
- let from_me = m.from_me.unwrap_or(false) as i64;
- conn.execute(
- "INSERT INTO wa_messages
- (account_id, chat_id, message_id, sender, sender_jid, from_me,
- body, timestamp, message_type, source, ingested_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
- ON CONFLICT(account_id, chat_id, message_id) DO UPDATE SET
- sender = CASE WHEN excluded.sender != '' THEN excluded.sender ELSE sender END,
- sender_jid = COALESCE(excluded.sender_jid, sender_jid),
- from_me = excluded.from_me,
- body = CASE WHEN excluded.body != '' THEN excluded.body ELSE body END,
- timestamp = excluded.timestamp,
- message_type = COALESCE(excluded.message_type, message_type),
- source = excluded.source,
- ingested_at = excluded.ingested_at",
- params![
- account_id,
- m.chat_id,
- m.message_id,
- m.sender.as_deref().unwrap_or(""),
- m.sender_jid.as_deref(),
- from_me,
- body,
- ts,
- m.message_type.as_deref(),
- m.source.as_deref().unwrap_or(""),
- now,
- ],
- )
- .with_context(|| {
- format!(
- "upsert wa_message chat={} msg={}",
- m.chat_id, m.message_id
- )
- })?;
- count += 1;
- }
-
- // Refresh chat stats after message upsert.
- if count > 0 {
- conn.execute(
- "UPDATE wa_chats
- SET message_count = (SELECT COUNT(*) FROM wa_messages
- WHERE wa_messages.account_id = wa_chats.account_id
- AND wa_messages.chat_id = wa_chats.chat_id),
- last_message_ts = COALESCE(
- (SELECT MAX(timestamp) FROM wa_messages
- WHERE wa_messages.account_id = wa_chats.account_id
- AND wa_messages.chat_id = wa_chats.chat_id),
- last_message_ts),
- updated_at = ?1
- WHERE account_id = ?2",
- rusqlite::params![now, account_id],
- )
- .context("refresh wa_chats stats")?;
- }
-
- log::debug!(
- "[whatsapp_data] upserted {} messages (account redacted)",
- count
- );
- Ok(count)
- }
-
- /// Delete messages older than `cutoff_ts` (Unix seconds). Returns the count removed.
- ///
- /// After the delete, refreshes `wa_chats.message_count` and
- /// `last_message_ts` for every chat that lost rows, so `list_chats`
- /// returns accurate counts and ordering immediately.
- pub fn prune_old_messages(&self, cutoff_ts: i64) -> Result<u64> {
- let _write_guard = self
- .write_lock
- .lock()
- .map_err(|e| anyhow::anyhow!("whatsapp_data write lock poisoned: {e}"))?;
- self.write_with_corrupt_recovery("prune_old_messages", || {
- self.prune_old_messages_inner(cutoff_ts)
- })
- }
-
- fn prune_old_messages_inner(&self, cutoff_ts: i64) -> Result<u64> {
- let conn = self.open_conn()?;
- let now = Self::now_secs();
-
- // Collect affected (account_id, chat_id) pairs before deleting.
- // Contextualized so a `SQLITE_CORRUPT` surfaced while compiling this
- // scan still carries a `prune` frame marker the observability
- // classifier keys on (otherwise a boot-time prune corruption would
- // reach Sentry unfiltered — the prepare of a plain SELECT still reads
- // the schema/root page where damage commonly lives).
- let mut stmt = conn
- .prepare(
- "SELECT DISTINCT account_id, chat_id FROM wa_messages
- WHERE timestamp > 0 AND timestamp < ?1",
- )
- .context("prune old wa_messages: scan affected chats")?;
- let affected: Vec<(String, String)> = stmt
- .query_map(params![cutoff_ts], |row| Ok((row.get(0)?, row.get(1)?)))?
- .collect::<rusqlite::Result<_>>()
- .context("collect affected chats for prune")?;
-
- let changed = conn
- .execute(
- "DELETE FROM wa_messages WHERE timestamp > 0 AND timestamp < ?1",
- params![cutoff_ts],
- )
- .context("prune old wa_messages")?;
-
- // Refresh aggregate stats for every affected chat so list_chats
- // reflects the post-prune state immediately.
- if changed > 0 {
- for (acct, chat_id) in &affected {
- conn.execute(
- "UPDATE wa_chats
- SET message_count = (SELECT COUNT(*) FROM wa_messages
- WHERE account_id = wa_chats.account_id
- AND chat_id = wa_chats.chat_id),
- last_message_ts = COALESCE(
- (SELECT MAX(timestamp) FROM wa_messages
- WHERE account_id = wa_chats.account_id
- AND chat_id = wa_chats.chat_id),
- last_message_ts),
- updated_at = ?3
- WHERE account_id = ?1 AND chat_id = ?2",
- params![acct, chat_id, now],
- )
- .with_context(|| format!("refresh chat stats after prune: {chat_id}"))?;
- }
- log::debug!(
- "[whatsapp_data] pruned {} messages (affected {} chats)",
- changed,
- affected.len()
- );
- }
- Ok(changed as u64)
- }
-
- /// List chats, optionally filtered by account. Ordered by `last_message_ts` DESC.
- pub fn list_chats(&self, req: &ListChatsRequest) -> Result<Vec<WhatsAppChat>> {
- let conn = self.open_conn()?;
- let limit = req.limit.unwrap_or(50) as i64;
- let offset = req.offset.unwrap_or(0) as i64;
-
- let chats = if let Some(ref acct) = req.account_id {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, display_name, is_group, last_message_ts,
- message_count, updated_at
- FROM wa_chats
- WHERE account_id = ?1
- ORDER BY last_message_ts DESC
- LIMIT ?2 OFFSET ?3",
- )?;
- let rows = stmt
- .query_map(params![acct, limit, offset], map_chat_row)?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("list chats (filtered)")?;
- rows
- } else {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, display_name, is_group, last_message_ts,
- message_count, updated_at
- FROM wa_chats
- ORDER BY last_message_ts DESC
- LIMIT ?1 OFFSET ?2",
- )?;
- let rows = stmt
- .query_map(params![limit, offset], map_chat_row)?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("list chats (all)")?;
- rows
- };
- log::debug!("[whatsapp_data] list_chats returned {} rows", chats.len());
- Ok(chats)
- }
-
- /// List messages for a chat, with optional time range and pagination.
- pub fn list_messages(&self, req: &ListMessagesRequest) -> Result<Vec<WhatsAppMessage>> {
- let conn = self.open_conn()?;
- let limit = req.limit.unwrap_or(100) as i64;
- let offset = req.offset.unwrap_or(0) as i64;
- let since_ts = req.since_ts.unwrap_or(0);
- let until_ts = req.until_ts.unwrap_or(i64::MAX);
-
- let msgs = if let Some(ref acct) = req.account_id {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, message_id, sender, sender_jid, from_me,
- body, timestamp, message_type, source
- FROM wa_messages
- WHERE account_id = ?1
- AND chat_id = ?2
- AND timestamp >= ?3
- AND timestamp <= ?4
- ORDER BY timestamp ASC
- LIMIT ?5 OFFSET ?6",
- )?;
- let rows = stmt
- .query_map(
- params![acct, req.chat_id, since_ts, until_ts, limit, offset],
- map_message_row,
- )?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("list messages (filtered by account)")?;
- rows
- } else {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, message_id, sender, sender_jid, from_me,
- body, timestamp, message_type, source
- FROM wa_messages
- WHERE chat_id = ?1
- AND timestamp >= ?2
- AND timestamp <= ?3
- ORDER BY timestamp ASC
- LIMIT ?4 OFFSET ?5",
- )?;
- let rows = stmt
- .query_map(
- params![req.chat_id, since_ts, until_ts, limit, offset],
- map_message_row,
- )?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("list messages (all accounts)")?;
- rows
- };
- log::debug!(
- "[whatsapp_data] list_messages returned {} rows (chat/account redacted)",
- msgs.len()
- );
- Ok(msgs)
- }
-
- /// Full-text search over message bodies (case-insensitive LIKE).
- pub fn search_messages(&self, req: &SearchMessagesRequest) -> Result<Vec<WhatsAppMessage>> {
- if req.query.trim().is_empty() {
- return Ok(vec![]);
- }
- let conn = self.open_conn()?;
- let limit = req.limit.unwrap_or(20) as i64;
- let pattern = format!("%{}%", req.query.replace('%', "\\%").replace('_', "\\_"));
-
- // Match against both `body` and `sender` so person-name queries like
- // "what did Alice say" surface Alice's messages even when "Alice"
- // does not appear in any message body. Branches are kept explicit so
- // the bind indices stay readable; each `pattern` bind is duplicated
- // because rusqlite does not resolve same-named placeholders for us.
- let msgs: Vec<WhatsAppMessage> = match (&req.account_id, &req.chat_id) {
- (Some(acct), Some(chat_id)) => {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, message_id, sender, sender_jid, from_me,
- body, timestamp, message_type, source
- FROM wa_messages
- WHERE account_id = ?1
- AND chat_id = ?2
- AND (body LIKE ?3 ESCAPE '\\' OR sender LIKE ?3 ESCAPE '\\')
- ORDER BY timestamp DESC
- LIMIT ?4",
- )?;
- let rows = stmt
- .query_map(params![acct, chat_id, pattern, limit], map_message_row)?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("search messages (account+chat)")?;
- rows
- }
- (Some(acct), None) => {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, message_id, sender, sender_jid, from_me,
- body, timestamp, message_type, source
- FROM wa_messages
- WHERE account_id = ?1
- AND (body LIKE ?2 ESCAPE '\\' OR sender LIKE ?2 ESCAPE '\\')
- ORDER BY timestamp DESC
- LIMIT ?3",
- )?;
- let rows = stmt
- .query_map(params![acct, pattern, limit], map_message_row)?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("search messages (account)")?;
- rows
- }
- (None, Some(chat_id)) => {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, message_id, sender, sender_jid, from_me,
- body, timestamp, message_type, source
- FROM wa_messages
- WHERE chat_id = ?1
- AND (body LIKE ?2 ESCAPE '\\' OR sender LIKE ?2 ESCAPE '\\')
- ORDER BY timestamp DESC
- LIMIT ?3",
- )?;
- let rows = stmt
- .query_map(params![chat_id, pattern, limit], map_message_row)?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("search messages (chat)")?;
- rows
- }
- (None, None) => {
- let mut stmt = conn.prepare(
- "SELECT account_id, chat_id, message_id, sender, sender_jid, from_me,
- body, timestamp, message_type, source
- FROM wa_messages
- WHERE body LIKE ?1 ESCAPE '\\' OR sender LIKE ?1 ESCAPE '\\'
- ORDER BY timestamp DESC
- LIMIT ?2",
- )?;
- let rows = stmt
- .query_map(params![pattern, limit], map_message_row)?
- .collect::<rusqlite::Result<Vec<_>>>()
- .context("search messages (all)")?;
- rows
- }
- };
- log::debug!(
- "[whatsapp_data] search_messages returned {} rows (query/account redacted)",
- msgs.len()
- );
- Ok(msgs)
- }
-}
-
-/// Append `suffix` to the *file name* of `path` (so `whatsapp_data.db` + `-wal`
-/// = `whatsapp_data.db-wal`, and `whatsapp_data.db` + `.corrupt-123` =
-/// `whatsapp_data.db.corrupt-123`). SQLite names its side-files this way (not
-/// as a new extension), and the quarantine keeps the corrupt image alongside
-/// the original for inspection.
-fn with_name_suffix(path: &Path, suffix: &str) -> PathBuf {
- let mut p = path.to_path_buf();
- let name = p
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .into_owned();
- p.set_file_name(format!("{name}{suffix}"));
- p
-}
-
-fn map_chat_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<WhatsAppChat> {
- Ok(WhatsAppChat {
- account_id: row.get(0)?,
- chat_id: row.get(1)?,
- display_name: row.get(2)?,
- is_group: row.get::<_, i64>(3)? != 0,
- last_message_ts: row.get(4)?,
- message_count: row.get::<_, i64>(5)? as u32,
- updated_at: row.get(6)?,
- })
-}
-
-fn map_message_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<WhatsAppMessage> {
- Ok(WhatsAppMessage {
- account_id: row.get(0)?,
- chat_id: row.get(1)?,
- message_id: row.get(2)?,
- sender: row.get(3)?,
- sender_jid: row.get(4)?,
- from_me: row.get::<_, i64>(5)? != 0,
- body: row.get(6)?,
- timestamp: row.get(7)?,
- message_type: row.get(8)?,
- source: row.get(9)?,
- })
-}
-
-#[cfg(test)]
-#[path = "store_tests.rs"]
-mod store_tests;
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use tempfile::tempdir;
-
- fn make_store() -> (WhatsAppDataStore, tempfile::TempDir) {
- let tmp = tempdir().expect("tempdir");
- let store = WhatsAppDataStore::new(tmp.path()).expect("store");
- (store, tmp)
- }
-
- #[test]
- fn upsert_and_list_chats() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert(
- "[email protected]".to_string(),
- ChatMeta {
- name: Some("Alice".to_string()),
- },
- );
- chats.insert(
- "[email protected]".to_string(),
- ChatMeta {
- name: Some("My Group".to_string()),
- },
- );
- let count = store.upsert_chats("acct1", &chats).unwrap();
- assert_eq!(count, 2);
-
- let req = ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- };
- let rows = store.list_chats(&req).unwrap();
- assert_eq!(rows.len(), 2);
-
- let group = rows.iter().find(|c| c.chat_id == "[email protected]").unwrap();
- assert!(group.is_group);
- let dm = rows.iter().find(|c| c.chat_id == "[email protected]").unwrap();
- assert!(!dm.is_group);
- }
-
- #[test]
- fn upsert_and_list_messages() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert(
- "[email protected]".to_string(),
- ChatMeta {
- name: Some("Alice".to_string()),
- },
- );
- store.upsert_chats("acct1", &chats).unwrap();
-
- let msgs = vec![
- IngestMessage {
- message_id: "msg1".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("Alice".to_string()),
- sender_jid: None,
- from_me: Some(false),
- body: Some("Hello there".to_string()),
- timestamp: Some(1_700_000_000),
- message_type: Some("chat".to_string()),
- source: Some("cdp-dom".to_string()),
- },
- IngestMessage {
- message_id: "msg2".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("me".to_string()),
- sender_jid: None,
- from_me: Some(true),
- body: Some("Hey!".to_string()),
- timestamp: Some(1_700_000_100),
- message_type: Some("chat".to_string()),
- source: Some("cdp-indexeddb".to_string()),
- },
- ];
- let count = store.upsert_messages("acct1", &msgs).unwrap();
- assert_eq!(count, 2);
-
- let req = ListMessagesRequest {
- chat_id: "[email protected]".to_string(),
- account_id: Some("acct1".to_string()),
- since_ts: None,
- until_ts: None,
- limit: None,
- offset: None,
- };
- let rows = store.list_messages(&req).unwrap();
- assert_eq!(rows.len(), 2);
- assert_eq!(rows[0].body, "Hello there");
- assert_eq!(rows[1].body, "Hey!");
- }
-
- #[test]
- fn search_messages_finds_match() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert(
- "[email protected]".to_string(),
- ChatMeta {
- name: Some("Alice".to_string()),
- },
- );
- store.upsert_chats("acct1", &chats).unwrap();
-
- let msgs = vec![
- IngestMessage {
- message_id: "m1".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("Alice".to_string()),
- sender_jid: None,
- from_me: Some(false),
- body: Some("Can you bring the umbrella?".to_string()),
- timestamp: Some(1_700_000_000),
- message_type: None,
- source: Some("cdp-dom".to_string()),
- },
- IngestMessage {
- message_id: "m2".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("me".to_string()),
- sender_jid: None,
- from_me: Some(true),
- body: Some("Sure, no problem".to_string()),
- timestamp: Some(1_700_000_200),
- message_type: None,
- source: Some("cdp-dom".to_string()),
- },
- ];
- store.upsert_messages("acct1", &msgs).unwrap();
-
- let req = SearchMessagesRequest {
- query: "umbrella".to_string(),
- chat_id: None,
- account_id: None,
- limit: None,
- };
- let results = store.search_messages(&req).unwrap();
- assert_eq!(results.len(), 1);
- assert!(results[0].body.contains("umbrella"));
- }
-
- #[test]
- fn search_messages_matches_sender_name() {
- // Person-name queries ("what did Alice say") only return rows when
- // search also looks at the `sender` column, because the sender's own
- // name almost never appears in the message body.
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert(
- "[email protected]".to_string(),
- ChatMeta {
- name: Some("Alice Q".to_string()),
- },
- );
- store.upsert_chats("acct1", &chats).unwrap();
-
- let msgs = vec![
- IngestMessage {
- message_id: "alice-1".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("Alice".to_string()),
- sender_jid: Some("[email protected]".to_string()),
- from_me: Some(false),
- // Body has no "Alice" — match must come from the sender column.
- body: Some("running 5 minutes late".to_string()),
- timestamp: Some(1_700_001_000),
- message_type: None,
- source: Some("cdp-dom".to_string()),
- },
- IngestMessage {
- message_id: "me-1".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("me".to_string()),
- sender_jid: None,
- from_me: Some(true),
- body: Some("no problem".to_string()),
- timestamp: Some(1_700_001_100),
- message_type: None,
- source: Some("cdp-dom".to_string()),
- },
- ];
- store.upsert_messages("acct1", &msgs).unwrap();
-
- let req = SearchMessagesRequest {
- query: "Alice".to_string(),
- chat_id: None,
- account_id: None,
- limit: None,
- };
- let results = store.search_messages(&req).unwrap();
- assert_eq!(results.len(), 1, "expected sender-name match: {results:?}");
- assert_eq!(results[0].sender, "Alice");
- }
-
- #[test]
- fn prune_removes_old_messages() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), ChatMeta { name: None });
- store.upsert_chats("acct1", &chats).unwrap();
-
- let msgs = vec![
- IngestMessage {
- message_id: "old".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: None,
- sender_jid: None,
- from_me: Some(false),
- body: Some("Old message".to_string()),
- timestamp: Some(1_000_000),
- message_type: None,
- source: None,
- },
- IngestMessage {
- message_id: "new".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: None,
- sender_jid: None,
- from_me: Some(false),
- body: Some("New message".to_string()),
- timestamp: Some(2_000_000_000),
- message_type: None,
- source: None,
- },
- ];
- store.upsert_messages("acct1", &msgs).unwrap();
-
- let pruned = store.prune_old_messages(1_500_000_000).unwrap();
- assert_eq!(pruned, 1);
-
- let req = ListMessagesRequest {
- chat_id: "[email protected]".to_string(),
- account_id: None,
- since_ts: None,
- until_ts: None,
- limit: None,
- offset: None,
- };
- let remaining = store.list_messages(&req).unwrap();
- assert_eq!(remaining.len(), 1);
- assert_eq!(remaining[0].message_id, "new");
- }
-}
diff --git a/app/src-tauri/src/whatsapp_data/store_tests.rs b/app/src-tauri/src/whatsapp_data/store_tests.rs
deleted file mode 100644
index 2dd8547324..0000000000
--- a/app/src-tauri/src/whatsapp_data/store_tests.rs
+++ /dev/null
@@ -1,731 +0,0 @@
-//! Additional unit tests for WhatsApp data store — account isolation and dedup.
-//!
-//! These tests sit alongside the inline `#[cfg(test)] mod tests` block in
-//! `store.rs`. They focus on cross-account scoping guarantees: data written
-//! for one `account_id` must never appear in queries for a different account.
-
-use super::super::sqlite_retry::BUSY_TIMEOUT;
-use super::WhatsAppDataStore;
-use openhuman_core::openhuman::channels::whatsapp_data::types::{
- ChatMeta, IngestMessage, ListChatsRequest, ListMessagesRequest, SearchMessagesRequest,
-};
-use std::collections::HashMap;
-use std::path::PathBuf;
-use std::sync::mpsc;
-use std::thread;
-use std::time::Duration;
-use tempfile::tempdir;
-
-fn make_store() -> (WhatsAppDataStore, tempfile::TempDir) {
- let tmp = tempdir().expect("tempdir");
- let store = WhatsAppDataStore::new(tmp.path()).expect("store");
- (store, tmp)
-}
-
-fn db_path_for(tmp: &tempfile::TempDir) -> PathBuf {
- tmp.path().join("whatsapp_data").join("whatsapp_data.db")
-}
-
-/// Hold an immediate write transaction until the returned sender fires, then commit.
-fn spawn_write_blocker(db_path: PathBuf) -> mpsc::Sender<()> {
- let (hold_tx, hold_rx) = mpsc::channel();
- let (release_tx, release_rx) = mpsc::channel();
- thread::spawn(move || {
- let conn = rusqlite::Connection::open(&db_path).expect("blocker open");
- conn.busy_timeout(BUSY_TIMEOUT)
- .expect("blocker busy_timeout");
- conn.execute_batch("BEGIN IMMEDIATE")
- .expect("blocker BEGIN IMMEDIATE");
- hold_tx.send(()).expect("blocker ready signal");
- let _ = release_rx.recv();
- conn.execute_batch("COMMIT").expect("blocker COMMIT");
- });
- hold_rx.recv().expect("blocker must acquire write lock");
- release_tx
-}
-
-fn chat_meta(name: &str) -> ChatMeta {
- ChatMeta {
- name: Some(name.to_string()),
- }
-}
-
-fn simple_message(msg_id: &str, chat_id: &str, body: &str, ts: i64) -> IngestMessage {
- IngestMessage {
- message_id: msg_id.to_string(),
- chat_id: chat_id.to_string(),
- sender: Some("user".to_string()),
- sender_jid: None,
- from_me: Some(false),
- body: Some(body.to_string()),
- timestamp: Some(ts),
- message_type: Some("chat".to_string()),
- source: Some("cdp-dom".to_string()),
- }
-}
-
-// ── Account isolation ────────────────────────────────────────────────────────
-
-/// Chats written for acct_a must not appear in a query filtered to acct_b.
-#[test]
-fn list_chats_account_filter_isolates_data() {
- let (store, _tmp) = make_store();
-
- let mut chats_a = HashMap::new();
- chats_a.insert("[email protected]".to_string(), chat_meta("Alice"));
- store.upsert_chats("acct_a", &chats_a).unwrap();
-
- let mut chats_b = HashMap::new();
- chats_b.insert("[email protected]".to_string(), chat_meta("Bob"));
- store.upsert_chats("acct_b", &chats_b).unwrap();
-
- // Querying with acct_a filter must only return acct_a's chats.
- let rows_a = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct_a".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(rows_a.len(), 1);
- assert_eq!(rows_a[0].chat_id, "[email protected]");
- assert_eq!(rows_a[0].account_id, "acct_a");
-
- // Querying with acct_b filter must only return acct_b's chats.
- let rows_b = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct_b".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(rows_b.len(), 1);
- assert_eq!(rows_b[0].chat_id, "[email protected]");
- assert_eq!(rows_b[0].account_id, "acct_b");
-}
-
-/// Messages written for acct_a must not appear in a list_messages query
-/// that is filtered to acct_b (same chat_id, different account).
-#[test]
-fn list_messages_account_filter_isolates_data() {
- let (store, _tmp) = make_store();
- let shared_chat = "[email protected]";
-
- // Seed both accounts with the same chat_id but different messages.
- let mut chats = HashMap::new();
- chats.insert(shared_chat.to_string(), chat_meta("Shared"));
- store.upsert_chats("acct_a", &chats).unwrap();
- store.upsert_chats("acct_b", &chats).unwrap();
-
- store
- .upsert_messages(
- "acct_a",
- &[simple_message(
- "msg-a1",
- shared_chat,
- "Hello from A",
- 1_700_000_001,
- )],
- )
- .unwrap();
- store
- .upsert_messages(
- "acct_b",
- &[simple_message(
- "msg-b1",
- shared_chat,
- "Hello from B",
- 1_700_000_002,
- )],
- )
- .unwrap();
-
- // acct_a query: must only return acct_a's message.
- let msgs_a = store
- .list_messages(&ListMessagesRequest {
- chat_id: shared_chat.to_string(),
- account_id: Some("acct_a".to_string()),
- since_ts: None,
- until_ts: None,
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(msgs_a.len(), 1);
- assert_eq!(msgs_a[0].account_id, "acct_a");
- assert_eq!(msgs_a[0].body, "Hello from A");
-
- // acct_b query: must only return acct_b's message.
- let msgs_b = store
- .list_messages(&ListMessagesRequest {
- chat_id: shared_chat.to_string(),
- account_id: Some("acct_b".to_string()),
- since_ts: None,
- until_ts: None,
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(msgs_b.len(), 1);
- assert_eq!(msgs_b[0].account_id, "acct_b");
- assert_eq!(msgs_b[0].body, "Hello from B");
-}
-
-/// search_messages with account_id filter must not surface messages from
-/// the other account even when the query body text matches.
-#[test]
-fn search_messages_account_filter_isolates_results() {
- let (store, _tmp) = make_store();
-
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Chat"));
- store.upsert_chats("acct_a", &chats).unwrap();
- store.upsert_chats("acct_b", &chats).unwrap();
-
- store
- .upsert_messages(
- "acct_a",
- &[simple_message(
- "m-a",
- "umbrella search term",
- 1_700_000_001,
- )],
- )
- .unwrap();
- store
- .upsert_messages(
- "acct_b",
- &[simple_message(
- "m-b",
- "umbrella search term",
- 1_700_000_002,
- )],
- )
- .unwrap();
-
- // Filtered to acct_a — must return exactly 1 result for acct_a.
- let results = store
- .search_messages(&SearchMessagesRequest {
- query: "umbrella".to_string(),
- chat_id: None,
- account_id: Some("acct_a".to_string()),
- limit: None,
- })
- .unwrap();
- assert_eq!(results.len(), 1);
- assert_eq!(results[0].account_id, "acct_a");
-}
-
-// ── Upsert / dedup ───────────────────────────────────────────────────────────
-
-/// Re-upserting the same chat_id for the same account must not create a
-/// duplicate row — the row count stays at 1.
-#[test]
-fn upsert_chat_deduplicates_on_same_account_and_chat_id() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("First Name"));
- store.upsert_chats("acct1", &chats).unwrap();
-
- // Second upsert with an updated display name.
- let mut chats2 = HashMap::new();
- chats2.insert("[email protected]".to_string(), chat_meta("Updated Name"));
- store.upsert_chats("acct1", &chats2).unwrap();
-
- let rows = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(
- rows.len(),
- 1,
- "duplicate upsert must not create an extra row"
- );
- assert_eq!(rows[0].display_name, "Updated Name");
-}
-
-/// Re-upserting the same message_id for the same (account, chat) must not
-/// create a duplicate row — message_count on the parent chat stays consistent.
-#[test]
-fn upsert_message_deduplicates_on_same_account_chat_message_id() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Chat"));
- store.upsert_chats("acct1", &chats).unwrap();
-
- let msg = simple_message("msg1", "[email protected]", "Original body", 1_700_000_001);
- store.upsert_messages("acct1", &[msg]).unwrap();
-
- // Re-upsert the same message_id with updated body.
- let msg_updated = IngestMessage {
- message_id: "msg1".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: Some("user".to_string()),
- sender_jid: None,
- from_me: Some(false),
- body: Some("Updated body".to_string()),
- timestamp: Some(1_700_000_001),
- message_type: Some("chat".to_string()),
- source: Some("cdp-dom".to_string()),
- };
- store.upsert_messages("acct1", &[msg_updated]).unwrap();
-
- let rows = store
- .list_messages(&ListMessagesRequest {
- chat_id: "[email protected]".to_string(),
- account_id: Some("acct1".to_string()),
- since_ts: None,
- until_ts: None,
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(
- rows.len(),
- 1,
- "re-upsert must not create duplicate message row"
- );
- assert_eq!(
- rows[0].body, "Updated body",
- "body must be updated in place"
- );
-}
-
-/// chat message_count stays in sync after multiple upserts of distinct messages.
-#[test]
-fn upsert_messages_updates_chat_message_count() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Chat"));
- store.upsert_chats("acct1", &chats).unwrap();
-
- store
- .upsert_messages(
- "acct1",
- &[
- simple_message("m1", "[email protected]", "first", 1_700_000_001),
- simple_message("m2", "[email protected]", "second", 1_700_000_002),
- simple_message("m3", "[email protected]", "third", 1_700_000_003),
- ],
- )
- .unwrap();
-
- let chats = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(chats[0].message_count, 3);
- assert_eq!(chats[0].last_message_ts, 1_700_000_003);
-}
-
-/// Pruning old messages refreshes chat stats so list_chats returns accurate counts.
-#[test]
-fn prune_old_messages_refreshes_chat_stats() {
- let (store, _tmp) = make_store();
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Chat"));
- store.upsert_chats("acct1", &chats).unwrap();
-
- store
- .upsert_messages(
- "acct1",
- &[
- simple_message("old", "[email protected]", "old message", 1_000_000),
- simple_message("new", "[email protected]", "new message", 2_000_000_000),
- ],
- )
- .unwrap();
-
- // Prune everything below 1.5 billion (keeps "new" only).
- let pruned = store.prune_old_messages(1_500_000_000).unwrap();
- assert_eq!(pruned, 1);
-
- let chats_after = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(
- chats_after[0].message_count, 1,
- "message_count must be refreshed after prune"
- );
- assert_eq!(
- chats_after[0].last_message_ts, 2_000_000_000,
- "last_message_ts must reflect the surviving message"
- );
-}
-
-/// Concurrent external write lock must not fail ingest — busy_timeout +
-/// retry_on_sqlite_busy should wait for the blocker to commit.
-#[test]
-fn upsert_chats_succeeds_after_sqlite_busy_contention() {
- let (store, tmp) = make_store();
- let workspace = tmp.path().to_path_buf();
- let db_path = db_path_for(&tmp);
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Alice"));
-
- let release = spawn_write_blocker(db_path);
- let upsert_handle = thread::spawn(move || store.upsert_chats("acct1", &chats));
- // Let upsert reach SQLite busy wait, then release the external write lock.
- thread::sleep(Duration::from_millis(50));
- release.send(()).expect("release blocker");
-
- let count = upsert_handle
- .join()
- .expect("upsert thread")
- .expect("upsert must succeed once blocker releases");
- assert_eq!(count, 1);
-
- let store = WhatsAppDataStore::new(&workspace).expect("reopen store");
- let rows = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(rows.len(), 1);
-}
-
-#[test]
-fn prune_old_messages_succeeds_after_sqlite_busy_contention() {
- let (store, tmp) = make_store();
- let workspace = tmp.path().to_path_buf();
- let db_path = db_path_for(&tmp);
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Chat"));
- store.upsert_chats("acct1", &chats).unwrap();
- store
- .upsert_messages(
- "acct1",
- &[
- simple_message("old", "[email protected]", "old", 1_000_000),
- simple_message("new", "[email protected]", "new", 2_000_000_000),
- ],
- )
- .unwrap();
-
- let release = spawn_write_blocker(db_path);
- let prune_handle = thread::spawn(move || store.prune_old_messages(1_500_000_000));
- thread::sleep(Duration::from_millis(50));
- release.send(()).expect("release blocker");
-
- let pruned = prune_handle
- .join()
- .expect("prune thread")
- .expect("prune must succeed once blocker releases");
- assert_eq!(pruned, 1);
-
- let store = WhatsAppDataStore::new(&workspace).expect("reopen store");
- let chats_after = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(chats_after[0].message_count, 1);
-}
-
-#[test]
-fn open_conn_configures_busy_timeout_and_wal() {
- let (store, _tmp) = make_store();
- let conn = store.open_conn_for_test().expect("open");
- let busy_ms: i64 = conn
- .pragma_query_value(None, "busy_timeout", |v| v.get(0))
- .expect("busy_timeout pragma");
- assert_eq!(
- busy_ms,
- BUSY_TIMEOUT.as_millis() as i64,
- "busy_timeout must match configured window"
- );
- let journal_mode: String = conn
- .pragma_query_value(None, "journal_mode", |v| v.get(0))
- .expect("journal_mode pragma");
- assert_eq!(
- journal_mode.to_ascii_lowercase(),
- "wal",
- "journal_mode must be WAL"
- );
-}
-
-/// Messages with an empty message_id or chat_id must be silently skipped,
-/// never causing a panic or spurious database error.
-/// A malformed on-disk image must be detected on the upsert write path,
-/// quarantined (never deleted), the schema rebuilt, and the *same* upsert call
-/// must then SUCCEED against the fresh DB — proving ingest self-heals instead of
-/// re-hitting the dead file on every scan tick (Sentry TAURI-RUST-KNH: 1,813
-/// events from a single host). The process-wide report latch must reset after a
-/// successful recovery so it fires at most once per corruption episode.
-#[test]
-fn upsert_recovers_from_corrupt_database() {
- use std::sync::atomic::Ordering;
-
- // Serialize against the other latch-touching recovery tests: the report
- // latch + integrity-fail seam are process-wide statics.
- let _guard = super::CORRUPT_TEST_GUARD
- .lock()
- .unwrap_or_else(|e| e.into_inner());
-
- let (store, tmp) = make_store();
- let workspace = tmp.path().to_path_buf();
- let db_path = db_path_for(&tmp);
-
- // Reset the process-wide latch so this test observes a clean episode.
- super::CORRUPT_REPORTED.store(false, Ordering::Relaxed);
-
- // Corrupt the freshly-created DB: drop any WAL side-files, then overwrite the
- // main file with garbage so the next open reads a malformed image.
- for suffix in ["-wal", "-shm"] {
- let side = db_path.with_file_name(format!("whatsapp_data.db{suffix}"));
- let _ = std::fs::remove_file(&side);
- }
- std::fs::write(
- &db_path,
- b"this is not a sqlite database, just garbage bytes",
- )
- .unwrap();
-
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Alice"));
-
- // First upsert hits the malformed image → detect → quarantine → rebuild →
- // retry against the fresh DB, so the call SUCCEEDS.
- let count = store
- .upsert_chats("acct1", &chats)
- .expect("upsert must succeed after corrupt-DB recovery");
- assert_eq!(count, 1);
-
- // The corrupt bytes are preserved alongside, never silently dropped.
- let quarantined: Vec<_> = std::fs::read_dir(db_path.parent().unwrap())
- .unwrap()
- .filter_map(|e| e.ok())
- .filter(|e| {
- e.file_name()
- .to_string_lossy()
- .contains("whatsapp_data.db.corrupt-")
- })
- .collect();
- assert_eq!(
- quarantined.len(),
- 1,
- "exactly one quarantined copy of the corrupt image should exist"
- );
-
- // The rebuilt DB is healthy and queryable — the chat we just wrote is there.
- let rows = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(rows.len(), 1);
- assert_eq!(rows[0].chat_id, "[email protected]");
-
- // A fresh store over the same workspace also sees the rebuilt, healthy DB.
- let reopened = WhatsAppDataStore::new(&workspace).expect("reopen store");
- let rows2 = reopened
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(rows2.len(), 1);
-
- // Recovery settled, so the report latch was reset: a genuinely-new later
- // corruption can page once more (the report fired at most once this episode).
- assert!(
- !super::CORRUPT_REPORTED.load(Ordering::Relaxed),
- "report latch must reset after a successful recovery"
- );
-}
-
-/// Finding 1 regression: when the quarantine + rebuild leaves a DB that STILL
-/// fails its integrity check, `recover_corrupt_db` must return `Err` (not
-/// swallow it as `Ok(true)`). Consequently `report_and_recover` must NOT reset
-/// the process-wide report latch — preserving the report-once-per-episode
-/// guarantee (a spurious reset would re-arm Sentry to page on the next scan
-/// tick against a DB that never actually recovered).
-#[test]
-fn recover_corrupt_db_errors_and_keeps_latch_when_rebuild_fails_integrity() {
- use std::sync::atomic::Ordering;
-
- let _guard = super::CORRUPT_TEST_GUARD
- .lock()
- .unwrap_or_else(|e| e.into_inner());
-
- let (store, tmp) = make_store();
- let db_path = db_path_for(&tmp);
-
- // Force the post-rebuild integrity_check to report failure via the test seam.
- super::FORCE_INTEGRITY_CHECK_FAIL.store(true, Ordering::Relaxed);
-
- let corrupt = |path: &std::path::Path| {
- for suffix in ["-wal", "-shm"] {
- let side = path.with_file_name(format!("whatsapp_data.db{suffix}"));
- let _ = std::fs::remove_file(&side);
- }
- std::fs::write(path, b"not a sqlite database, just garbage bytes").unwrap();
- };
-
- // (a) Direct call: recovery quarantines + rebuilds, but the forced
- // integrity_check failure makes it return Err instead of Ok(true).
- corrupt(&db_path);
- let direct = store.recover_corrupt_db();
-
- // (b) report_and_recover path: on that recovery failure the report latch,
- // set by the initial report, must remain set (not reset to false).
- corrupt(&db_path);
- super::CORRUPT_REPORTED.store(false, Ordering::Relaxed);
- let err = anyhow::anyhow!(
- "[whatsapp_data] ingest failed: upsert wa_chat 1@lid: database disk image is malformed"
- );
- store.report_and_recover("upsert_chats", &err);
- let latch_after = super::CORRUPT_REPORTED.load(Ordering::Relaxed);
-
- // Clear the seam + latch BEFORE asserting so a failing assert cannot leak
- // the forced-fail state into other tests.
- super::FORCE_INTEGRITY_CHECK_FAIL.store(false, Ordering::Relaxed);
- super::CORRUPT_REPORTED.store(false, Ordering::Relaxed);
-
- assert!(
- direct.is_err(),
- "recover_corrupt_db must return Err when the rebuilt DB still fails integrity_check"
- );
- assert!(
- latch_after,
- "report latch must stay set when recovery fails (report-once-per-episode must hold)"
- );
-}
-
-/// Finding 2 regression: a `whatsapp_data.db` that is already malformed at
-/// process startup must self-heal during store construction. Before the fix,
-/// `WhatsAppDataStore::new()` propagated the `init_schema` corruption error, the
-/// store singleton was never set, and every ingest RPC failed forever — the
-/// corruption survived restarts and re-paged Sentry on every scanner tick.
-#[test]
-fn new_recovers_from_corruption_at_startup() {
- use std::sync::atomic::Ordering;
-
- let _guard = super::CORRUPT_TEST_GUARD
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- super::CORRUPT_REPORTED.store(false, Ordering::Relaxed);
-
- // Pre-create the whatsapp_data dir and plant a malformed DB file BEFORE any
- // store exists, simulating a corrupt image left behind by a prior run.
- let tmp = tempdir().expect("tempdir");
- let workspace = tmp.path().to_path_buf();
- let db_path = db_path_for(&tmp);
- std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
- std::fs::write(
- &db_path,
- b"this is not a sqlite database, just garbage bytes",
- )
- .unwrap();
-
- // Construction must succeed by quarantining + rebuilding, not error out.
- let store = WhatsAppDataStore::new(&workspace)
- .expect("new() must self-heal a boot-time corrupt DB, not propagate the error");
-
- // The corrupt bytes are preserved alongside, never silently dropped.
- let quarantined = std::fs::read_dir(db_path.parent().unwrap())
- .unwrap()
- .filter_map(|e| e.ok())
- .filter(|e| {
- e.file_name()
- .to_string_lossy()
- .contains("whatsapp_data.db.corrupt-")
- })
- .count();
- assert_eq!(
- quarantined, 1,
- "boot-time corrupt image must be quarantined once"
- );
-
- // The rebuilt DB is fully usable — a subsequent upsert lands and reads back.
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Alice"));
- let count = store
- .upsert_chats("acct1", &chats)
- .expect("upsert must succeed against the rebuilt DB");
- assert_eq!(count, 1);
-
- let rows = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(rows.len(), 1);
- assert_eq!(rows[0].chat_id, "[email protected]");
-
- super::CORRUPT_REPORTED.store(false, Ordering::Relaxed);
-}
-
-/// A *healthy* DB must never be quarantined even if `recover_corrupt_db` is
-/// invoked — `quick_check` passes, so good data is preserved and recovery is a
-/// no-op returning `Ok(false)`.
-#[test]
-fn recover_corrupt_db_is_noop_on_healthy_db() {
- let (store, tmp) = make_store();
- let db_path = db_path_for(&tmp);
- // Seed a real row so there is genuine data that must survive.
- let mut chats = HashMap::new();
- chats.insert("[email protected]".to_string(), chat_meta("Alice"));
- store.upsert_chats("acct1", &chats).unwrap();
-
- let recovered = store
- .recover_corrupt_db()
- .expect("recovery on a healthy DB must not error");
- assert!(!recovered, "healthy DB must not be quarantined");
-
- let quarantined = std::fs::read_dir(db_path.parent().unwrap())
- .unwrap()
- .filter_map(|e| e.ok())
- .any(|e| e.file_name().to_string_lossy().contains(".corrupt-"));
- assert!(!quarantined, "no quarantine file should be created");
-
- // Data survives untouched.
- let rows = store
- .list_chats(&ListChatsRequest {
- account_id: Some("acct1".to_string()),
- limit: None,
- offset: None,
- })
- .unwrap();
- assert_eq!(rows.len(), 1);
-}
-
-#[test]
-fn upsert_messages_skips_rows_with_empty_ids() {
- let (store, _tmp) = make_store();
-
- let bad = IngestMessage {
- message_id: "".to_string(),
- chat_id: "[email protected]".to_string(),
- sender: None,
- sender_jid: None,
- from_me: None,
- body: Some("will be skipped".to_string()),
- timestamp: Some(1_700_000_001),
- message_type: None,
- source: None,
- };
- let count = store.upsert_messages("acct1", &[bad]).unwrap();
- assert_eq!(count, 0, "message with empty message_id must be skipped");
-}
diff --git a/src/core/legacy_aliases.rs b/src/core/legacy_aliases.rs
index bbc08888a4..ac725bdb66 100644
--- a/src/core/legacy_aliases.rs
+++ b/src/core/legacy_aliases.rs
@@ -377,14 +377,12 @@ mod tests {
#[cfg(not(feature = "channels"))]
fn channels_method_compiled_out(method: &str) -> bool {
- // `channels` feature OFF ⇒ the channels + webview_apis +
- // webview_notifications + whatsapp_data controllers are unregistered
- // (#4801). NOTE: the in-app web chat (`openhuman.channel_*`) is NOT
- // gated (core product surface, #5002) — do not add that prefix here.
+ // `channels` feature OFF ⇒ the channels + webview_notifications
+ // controllers are unregistered (#4801). NOTE: the in-app web chat
+ // (`openhuman.channel_*`) is NOT gated (core product surface, #5002) —
+ // do not add that prefix here.
method.starts_with("openhuman.channels_")
- || method.starts_with("openhuman.webview_apis_")
|| method.starts_with("openhuman.webview_notifications_")
- || method.starts_with("openhuman.whatsapp_data_")
}
#[test]
diff --git a/src/openhuman/channels/mod.rs b/src/openhuman/channels/mod.rs
index 85d4a984e8..174bd3bea5 100644
--- a/src/openhuman/channels/mod.rs
+++ b/src/openhuman/channels/mod.rs
@@ -12,7 +12,7 @@
//!
//! Everything else (`providers`, `host`, `controllers`, `runtime`, `bus`,
//! `proactive`, `commands`, `context`, `routes`, `relay_runtime`,
-//! `whatsapp_data`, the provider re-exports,
+//! the provider re-exports,
//! `doctor_channels`, `start_channels`, the `build_system_prompt` re-export and
//! the `test_support` re-export) is `#[cfg(feature = "channels")]`.
//! Nothing INSIDE those submodules changes when the gate flips.
@@ -41,11 +41,6 @@ pub mod proactive;
pub mod providers;
#[cfg(feature = "channels")]
pub(crate) mod relay_runtime;
-/// Read-only WhatsApp chat/message store fed by the desktop scanner (formerly
-/// `openhuman::whatsapp_data`).
-#[cfg(feature = "channels")]
-pub mod whatsapp_data;
-
#[cfg(feature = "channels")]
mod commands;
#[cfg(feature = "channels")]
diff --git a/src/openhuman/channels/whatsapp_data/README.md b/src/openhuman/channels/whatsapp_data/README.md
deleted file mode 100644
index f4f5c7b6ef..0000000000
--- a/src/openhuman/channels/whatsapp_data/README.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# whatsapp_data (core: shared DTOs + agent tools)
-
-Local-only, structured WhatsApp Web data for the agent. **The SQLite store, the
-scanner ingest write path, and the list/search business logic live in the Tauri
-shell** (`app/src-tauri/src/whatsapp_data/`) — the core keeps only the shared
-serde DTOs and the three read-only agent query tools. **All data stays
-on-device — nothing is transmitted to any external service.**
-
-## Architecture (in-process bridge)
-
-The core runs in-process inside the Tauri shell (sidecar removed). The agent
-tools reach the shell-owned store over the **native request bus**
-(`core::event_bus::{register_native_global, request_native_global}`) — a typed,
-zero-serialization, in-process request/response registry keyed by a method
-string. No HTTP, no JSON-RPC controller, no WebSocket loopback.
-
-```
-agent tool (core) shell store (app/src-tauri)
- request_native_global(method, req) ──▶ register_native_global(method, handler)
- "whatsapp_data.list_chats" -> ops::list_chats(&store, req)
- "whatsapp_data.list_messages" -> ops::list_messages(&store, req)
- "whatsapp_data.search_messages" -> ops::search_messages(&store, req)
- scanner:
- "whatsapp_data.ingest" -> ops::ingest(&store, req) (90-day prune)
-```
-
-Both sides share **one** DTO definition (`types.rs`), so the native-request
-`TypeId` checks line up. Method-name constants live in `mod.rs` (`methods::*`).
-
-**Graceful degradation.** In a headless / CLI / docker build there is no shell,
-so no handler is registered. The tools then return an empty, well-formed result
-with a `"note": "WhatsApp data unavailable (desktop only)"` rather than erroring.
-
-## Key files (core)
-
-| File | Role |
-| --- | --- |
-| `mod.rs` | Module docstring + `methods::*` native-request keys; re-exports `tools` + `types`. |
-| `types.rs` | Shared serde DTOs: `WhatsAppChat`, `WhatsAppMessage`, ingest/list/search request + result structs. Consumed by both the core tools and the shell store. |
-| `tools.rs` | Re-exports the three tools + the degradation helpers (`UNAVAILABLE_NOTE`, `is_handler_absent`). |
-| `tools/list_chats.rs` | `WhatsAppDataListChatsTool` — dispatches `whatsapp_data.list_chats`. |
-| `tools/list_messages.rs` | `WhatsAppDataListMessagesTool` — dispatches `whatsapp_data.list_messages`. |
-| `tools/search_messages.rs` | `WhatsAppDataSearchMessagesTool` — dispatches `whatsapp_data.search_messages`. |
-
-## Shell side (`app/src-tauri/src/whatsapp_data/`)
-
-`store.rs` (SQLite persistence + corruption quarantine/rebuild), `ops.rs`
-(ingest + 90-day prune + list/search), `sqlite_retry.rs` (busy/corrupt
-detection + backoff), `global.rs` (process-global store singleton), and `mod.rs`
-(native-handler registration + `ensure_store` + the `whatsapp_data_list_chats` /
-`_list_messages` / `_search_messages` Tauri commands the frontend invokes). The
-DB lives at `<workspace_dir>/whatsapp_data/whatsapp_data.db` — the same
-workspace the core resolves, so it stays on the agent-write denylist
-(`security::policy` `WORKSPACE_INTERNAL_DIRS`).
diff --git a/src/openhuman/channels/whatsapp_data/mod.rs b/src/openhuman/channels/whatsapp_data/mod.rs
deleted file mode 100644
index 0bfb17155e..0000000000
--- a/src/openhuman/channels/whatsapp_data/mod.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-//! Structured WhatsApp Web data — shared DTOs + agent query tools.
-//!
-//! **Storage lives in the Tauri shell, not the core.** The SQLite store, the
-//! scanner-side ingest write path, and the list/search business logic were
-//! relocated to `app/src-tauri/src/whatsapp_data/` (desktop-only). The core
-//! keeps only:
-//!
-//! - [`types`] — the shared serde DTOs (chat / message rows, list / search /
-//! ingest request + response types). Both the core agent tools and the shell
-//! store reference this single definition so the two sides never drift.
-//! - [`tools`] — the three read-only agent tools. Their bodies dispatch over
-//! the in-process native request bus
-//! (`openhuman_core::core::bus::BUS.native().request`) keyed by
-//! `whatsapp_data.list_chats` / `.list_messages` / `.search_messages`. The
-//! shell registers the matching handlers at startup.
-//!
-//! When no shell handler is registered (headless / CLI / docker — no desktop),
-//! the tools degrade gracefully to an empty result with a "WhatsApp data
-//! unavailable (desktop only)" note rather than erroring.
-//!
-//! **Data locality**: all data remains on-device; it is never transmitted to
-//! any external service.
-
-pub mod tools;
-pub mod types;
-
-/// Native-request method names bridging the core agent tools to the shell store.
-///
-/// The shell registers a handler for each of these via
-/// `register_native_global`; the core tools dispatch to them via
-/// `request_native_global`. Kept here as the single source of truth so the two
-/// sides never disagree on the string key.
-pub mod methods {
- /// List chats — req [`super::types::ListChatsRequest`], resp `Vec<`[`super::types::WhatsAppChat`]`>`.
- pub const LIST_CHATS: &str = "whatsapp_data.list_chats";
- /// List messages — req [`super::types::ListMessagesRequest`], resp `Vec<`[`super::types::WhatsAppMessage`]`>`.
- pub const LIST_MESSAGES: &str = "whatsapp_data.list_messages";
- /// Search messages — req [`super::types::SearchMessagesRequest`], resp `Vec<`[`super::types::WhatsAppMessage`]`>`.
- pub const SEARCH_MESSAGES: &str = "whatsapp_data.search_messages";
- /// Ingest a scanner snapshot — req [`super::types::IngestRequest`], resp [`super::types::IngestResult`].
- pub const INGEST: &str = "whatsapp_data.ingest";
-}
diff --git a/src/openhuman/channels/whatsapp_data/tools.rs b/src/openhuman/channels/whatsapp_data/tools.rs
deleted file mode 100644
index be1a6174c7..0000000000
--- a/src/openhuman/channels/whatsapp_data/tools.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-//! LLM-callable wrappers for the WhatsApp data store (issue #1341).
-//!
-//! The store itself lives in the Tauri shell. Each tool dispatches its query
-//! over the in-process native request bus
-//! ([`crate::core::bus::BUS.native().request`]) to the shell-registered
-//! handler, unwraps the typed response, and emits a compact JSON object that
-//! includes a `"provider": "whatsapp"` provenance tag so replies can cite
-//! WhatsApp as the source.
-//!
-//! **Graceful degradation.** In a headless / CLI / docker build there is no
-//! desktop shell, so no handler is registered. In that case the native
-//! dispatch returns [`NativeRequestError::NotInitialized`] or
-//! [`NativeRequestError::UnregisteredHandler`]; the tools treat that as
-//! "WhatsApp data unavailable (desktop only)" and return an empty, well-formed
-//! result rather than surfacing an error to the agent. A genuine handler-side
-//! failure ([`NativeRequestError::HandlerFailed`] / [`NativeRequestError::TypeMismatch`])
-//! still propagates as a tool error.
-//!
-//! The write-path `whatsapp_data.ingest` is intentionally NOT wrapped here —
-//! it is a scanner-only write path, dispatched by the Tauri shell scanner
-//! directly. Exposing it as an agent tool would reopen the read-only boundary
-//! this module exists to preserve.
-
-mod list_chats;
-mod list_messages;
-mod search_messages;
-
-pub use list_chats::WhatsAppDataListChatsTool;
-pub use list_messages::WhatsAppDataListMessagesTool;
-pub use search_messages::WhatsAppDataSearchMessagesTool;
-
-use tinybus::NativeRequestError;
-
-/// Note surfaced when the WhatsApp data store is unavailable because no desktop
-/// shell handler is registered (headless / CLI / docker builds).
-pub(crate) const UNAVAILABLE_NOTE: &str = "WhatsApp data unavailable (desktop only)";
-
-/// True when `err` means "no shell handler is wired" — which maps to graceful
-/// degradation (an empty result) rather than a tool error.
-///
-/// The old bus also had an `Init` case for "the registry itself was never
-/// initialised". `tinybus::NativeRegistry` is created on first access, so that
-/// state no longer exists: an absent handler is the only way to be absent.
-pub(crate) fn is_handler_absent(err: &NativeRequestError) -> bool {
- matches!(err, NativeRequestError::UnregisteredHandler { .. })
-}
diff --git a/src/openhuman/channels/whatsapp_data/tools/list_chats.rs b/src/openhuman/channels/whatsapp_data/tools/list_chats.rs
deleted file mode 100644
index bf00a53a4f..0000000000
--- a/src/openhuman/channels/whatsapp_data/tools/list_chats.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-use crate::core::bus::BUS;
-use crate::openhuman::channels::whatsapp_data::methods;
-use crate::openhuman::channels::whatsapp_data::tools::{is_handler_absent, UNAVAILABLE_NOTE};
-use crate::openhuman::channels::whatsapp_data::types::{ListChatsRequest, WhatsAppChat};
-use crate::openhuman::tools::traits::{Tool, ToolResult};
-use async_trait::async_trait;
-use serde_json::json;
-
-pub struct WhatsAppDataListChatsTool;
-
-#[async_trait]
-impl Tool for WhatsAppDataListChatsTool {
- fn name(&self) -> &str {
- "whatsapp_data_list_chats"
- }
-
- fn description(&self) -> &str {
- "List WhatsApp chats stored locally on this device, sorted by \
- `last_message_ts` DESC (most recent activity first). USE THIS for \
- intents about recent WhatsApp activity, identifying who the user \
- spoke to recently, or resolving a contact/group name to a `chat_id`. \
- Examples: 'who did I talk to on WhatsApp in the last 3 hours', \
- 'find my chat with Alice', 'which WhatsApp groups are active'. \
- Each chat carries `chat_id`, `display_name`, `is_group`, \
- `last_message_ts`, and `message_count`. After getting the chat \
- list, drive `whatsapp_data_list_messages` (with the `chat_id`, \
- optionally bounded by `since_ts`) for the message contents. \
- Returns provider provenance so replies can cite WhatsApp."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "account_id": {
- "type": "string",
- "description": "Optional WhatsApp account JID. Omit to span every connected WhatsApp account."
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "description": "Maximum chats to return (default 50)."
- },
- "offset": {
- "type": "integer",
- "minimum": 0,
- "description": "Pagination offset (default 0)."
- }
- }
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- log::debug!("[tool][whatsapp_data] list_chats invoked");
- let req: ListChatsRequest = serde_json::from_value(args).map_err(|e| {
- log::debug!("[tool][whatsapp_data] list_chats invalid_args error={e}");
- anyhow::anyhow!("invalid arguments for whatsapp_data_list_chats: {e}")
- })?;
- log::debug!(
- "[tool][whatsapp_data] list_chats args has_account={} limit={:?} offset={:?}",
- req.account_id.is_some(),
- req.limit,
- req.offset,
- );
- let chats: Vec<WhatsAppChat> = match BUS.native().request(methods::LIST_CHATS, req).await {
- Ok(chats) => chats,
- Err(e) if is_handler_absent(&e) => {
- // Headless / CLI / docker: no desktop shell handler is
- // registered. Degrade gracefully to an empty result.
- log::debug!("[tool][whatsapp_data] list_chats handler_absent — degrading ({e})");
- let body = serde_json::to_string(&json!({
- "provider": "whatsapp",
- "count": 0,
- "chats": [],
- "note": UNAVAILABLE_NOTE,
- }))?;
- return Ok(ToolResult::success(body));
- }
- Err(e) => {
- log::warn!("[tool][whatsapp_data] list_chats bridge_error error={e}");
- return Err(anyhow::anyhow!("whatsapp_data_list_chats: {e}"));
- }
- };
- log::debug!(
- "[tool][whatsapp_data] list_chats returning count={}",
- chats.len()
- );
- let body = serde_json::to_string(&json!({
- "provider": "whatsapp",
- "count": chats.len(),
- "chats": chats,
- }))?;
- Ok(ToolResult::success(body))
- }
-
- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {
- true
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::openhuman::tools::traits::{PermissionLevel, ToolScope};
-
- #[test]
- fn metadata_advertises_whatsapp() {
- let tool = WhatsAppDataListChatsTool;
- assert_eq!(tool.name(), "whatsapp_data_list_chats");
- assert!(tool.description().contains("WhatsApp"));
- assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);
- assert_eq!(tool.scope(), ToolScope::All);
- assert!(tool.is_concurrency_safe(&serde_json::Value::Null));
- }
-
- #[test]
- fn parameters_schema_is_object_with_optional_fields() {
- let schema = WhatsAppDataListChatsTool.parameters_schema();
- assert_eq!(schema["type"], "object");
- let props = &schema["properties"];
- for key in ["account_id", "limit", "offset"] {
- assert!(props.get(key).is_some(), "missing property {key}");
- }
- // No `required` array — every parameter is optional.
- assert!(schema.get("required").is_none());
- }
-
- #[tokio::test]
- async fn execute_rejects_invalid_args() {
- let tool = WhatsAppDataListChatsTool;
- let err = tool
- .execute(json!({ "limit": "not-a-number" }))
- .await
- .expect_err("expected invalid-args error");
- assert!(err.to_string().contains("whatsapp_data_list_chats"));
- }
-
- #[tokio::test]
- async fn execute_degrades_gracefully_without_shell_handler() {
- // No shell handler registered in-crate → the native dispatch reports
- // the handler absent and the tool returns an empty, well-formed result
- // carrying the desktop-only note rather than erroring.
- let tool = WhatsAppDataListChatsTool;
- let result = tool
- .execute(json!({}))
- .await
- .expect("degradation must succeed, not error");
- let body: serde_json::Value =
- serde_json::from_str(&result.text()).expect("tool body is JSON");
- assert_eq!(body["provider"], "whatsapp");
- assert_eq!(body["count"], 0);
- assert_eq!(body["note"], UNAVAILABLE_NOTE);
- }
-}
diff --git a/src/openhuman/channels/whatsapp_data/tools/list_messages.rs b/src/openhuman/channels/whatsapp_data/tools/list_messages.rs
deleted file mode 100644
index 204352efde..0000000000
--- a/src/openhuman/channels/whatsapp_data/tools/list_messages.rs
+++ /dev/null
@@ -1,168 +0,0 @@
-use crate::core::bus::BUS;
-use crate::openhuman::channels::whatsapp_data::methods;
-use crate::openhuman::channels::whatsapp_data::tools::{is_handler_absent, UNAVAILABLE_NOTE};
-use crate::openhuman::channels::whatsapp_data::types::{ListMessagesRequest, WhatsAppMessage};
-use crate::openhuman::tools::traits::{Tool, ToolResult};
-use async_trait::async_trait;
-use serde_json::json;
-
-pub struct WhatsAppDataListMessagesTool;
-
-#[async_trait]
-impl Tool for WhatsAppDataListMessagesTool {
- fn name(&self) -> &str {
- "whatsapp_data_list_messages"
- }
-
- fn description(&self) -> &str {
- "Return WhatsApp messages for one chat, ordered oldest-first within \
- the requested time window. USE THIS for any WhatsApp request scoped \
- to a specific chat — summarisation, action-item extraction, \
- quoting, or 'show me the last N messages with <person>'. ALSO use \
- this (paired with `since_ts` from `current_time` minus N hours) for \
- time-window reads like 'what did <person> message me in the last 3 \
- hours' AFTER resolving the chat via `whatsapp_data_list_chats`. The \
- `chat_id` arg is required — get it from `whatsapp_data_list_chats` \
- (or `whatsapp_data_search_messages`); optionally bound the range \
- with `since_ts` / `until_ts` (Unix seconds). Do NOT use \
- `whatsapp_data_search_messages` for time-only queries — that tool \
- is keyword-based, not time-based. Returns provider provenance so \
- replies can cite WhatsApp."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "chat_id": {
- "type": "string",
- "description": "WhatsApp chat JID, e.g. `[email protected]` for a contact or `<id>@g.us` for a group. Required."
- },
- "account_id": {
- "type": "string",
- "description": "Optional WhatsApp account JID. Omit to span every connected account."
- },
- "since_ts": {
- "type": "integer",
- "description": "Lower bound (Unix seconds, inclusive) on message timestamp."
- },
- "until_ts": {
- "type": "integer",
- "description": "Upper bound (Unix seconds, inclusive) on message timestamp."
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "description": "Maximum messages to return (default 100)."
- },
- "offset": {
- "type": "integer",
- "minimum": 0,
- "description": "Pagination offset (default 0)."
- }
- },
- "required": ["chat_id"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- log::debug!("[tool][whatsapp_data] list_messages invoked");
- let req: ListMessagesRequest = serde_json::from_value(args).map_err(|e| {
- log::debug!("[tool][whatsapp_data] list_messages invalid_args error={e}");
- anyhow::anyhow!("invalid arguments for whatsapp_data_list_messages: {e}")
- })?;
- log::debug!(
- "[tool][whatsapp_data] list_messages args has_account={} has_chat=true limit={:?} offset={:?} has_since={} has_until={}",
- req.account_id.is_some(),
- req.limit,
- req.offset,
- req.since_ts.is_some(),
- req.until_ts.is_some(),
- );
- let messages: Vec<WhatsAppMessage> =
- match BUS.native().request(methods::LIST_MESSAGES, req).await {
- Ok(messages) => messages,
- Err(e) if is_handler_absent(&e) => {
- log::debug!(
- "[tool][whatsapp_data] list_messages handler_absent — degrading ({e})"
- );
- let body = serde_json::to_string(&json!({
- "provider": "whatsapp",
- "count": 0,
- "messages": [],
- "note": UNAVAILABLE_NOTE,
- }))?;
- return Ok(ToolResult::success(body));
- }
- Err(e) => {
- log::warn!("[tool][whatsapp_data] list_messages bridge_error error={e}");
- return Err(anyhow::anyhow!("whatsapp_data_list_messages: {e}"));
- }
- };
- log::debug!(
- "[tool][whatsapp_data] list_messages returning count={}",
- messages.len()
- );
- let body = serde_json::to_string(&json!({
- "provider": "whatsapp",
- "count": messages.len(),
- "messages": messages,
- }))?;
- Ok(ToolResult::success(body))
- }
-
- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {
- true
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::openhuman::tools::traits::{PermissionLevel, ToolScope};
-
- #[test]
- fn metadata_advertises_whatsapp() {
- let tool = WhatsAppDataListMessagesTool;
- assert_eq!(tool.name(), "whatsapp_data_list_messages");
- assert!(tool.description().contains("WhatsApp"));
- assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);
- assert_eq!(tool.scope(), ToolScope::All);
- assert!(tool.is_concurrency_safe(&serde_json::Value::Null));
- }
-
- #[test]
- fn parameters_schema_requires_chat_id() {
- let schema = WhatsAppDataListMessagesTool.parameters_schema();
- assert_eq!(schema["type"], "object");
- let required = schema["required"]
- .as_array()
- .expect("required array present");
- let names: Vec<&str> = required.iter().filter_map(|v| v.as_str()).collect();
- assert_eq!(names, vec!["chat_id"]);
- }
-
- #[tokio::test]
- async fn execute_rejects_missing_chat_id() {
- let tool = WhatsAppDataListMessagesTool;
- let err = tool
- .execute(json!({}))
- .await
- .expect_err("expected missing chat_id error");
- assert!(err.to_string().contains("whatsapp_data_list_messages"));
- }
-
- #[tokio::test]
- async fn execute_degrades_gracefully_without_shell_handler() {
- let tool = WhatsAppDataListMessagesTool;
- let result = tool
- .execute(json!({ "chat_id": "[email protected]" }))
- .await
- .expect("degradation must succeed, not error");
- let body: serde_json::Value =
- serde_json::from_str(&result.text()).expect("tool body is JSON");
- assert_eq!(body["provider"], "whatsapp");
- assert_eq!(body["count"], 0);
- assert_eq!(body["note"], UNAVAILABLE_NOTE);
- }
-}
diff --git a/src/openhuman/channels/whatsapp_data/tools/search_messages.rs b/src/openhuman/channels/whatsapp_data/tools/search_messages.rs
deleted file mode 100644
index a1e5435720..0000000000
--- a/src/openhuman/channels/whatsapp_data/tools/search_messages.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-use crate::core::bus::BUS;
-use crate::openhuman::channels::whatsapp_data::methods;
-use crate::openhuman::channels::whatsapp_data::tools::{is_handler_absent, UNAVAILABLE_NOTE};
-use crate::openhuman::channels::whatsapp_data::types::{SearchMessagesRequest, WhatsAppMessage};
-use crate::openhuman::tools::traits::{Tool, ToolResult};
-use async_trait::async_trait;
-use serde_json::json;
-
-pub struct WhatsAppDataSearchMessagesTool;
-
-#[async_trait]
-impl Tool for WhatsAppDataSearchMessagesTool {
- fn name(&self) -> &str {
- "whatsapp_data_search_messages"
- }
-
- fn description(&self) -> &str {
- "Case-insensitive substring search across stored WhatsApp messages, \
- newest-first. Matches BOTH the message body AND the sender name, so \
- a query of 'Alice' returns Alice's own messages even when the body \
- does not contain the word 'Alice'. USE THIS for keyword lookups \
- (specific words, phrases, project names, URLs in messages) and for \
- 'what did <person> say about <topic>' style intents. \
- Do NOT use this for time-window queries like 'what did <person> say \
- in the last 3 hours' — those go through `whatsapp_data_list_chats` \
- to resolve the chat, then `whatsapp_data_list_messages` with \
- `since_ts`. Optionally narrow with `chat_id` and/or `account_id`. \
- Returns provider provenance so replies can cite WhatsApp."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "minLength": 1,
- "description": "Substring to match against message bodies (case-insensitive). Required."
- },
- "chat_id": {
- "type": "string",
- "description": "Optional WhatsApp chat JID to scope the search."
- },
- "account_id": {
- "type": "string",
- "description": "Optional WhatsApp account JID. Omit to span every connected account."
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "description": "Maximum messages to return (default 20)."
- }
- },
- "required": ["query"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- log::debug!("[tool][whatsapp_data] search_messages invoked");
- let req: SearchMessagesRequest = serde_json::from_value(args).map_err(|e| {
- log::debug!("[tool][whatsapp_data] search_messages invalid_args error={e}");
- anyhow::anyhow!("invalid arguments for whatsapp_data_search_messages: {e}")
- })?;
- log::debug!(
- "[tool][whatsapp_data] search_messages args has_account={} has_chat={} limit={:?} query_len={}",
- req.account_id.is_some(),
- req.chat_id.is_some(),
- req.limit,
- req.query.len(),
- );
- let messages: Vec<WhatsAppMessage> =
- match BUS.native().request(methods::SEARCH_MESSAGES, req).await {
- Ok(messages) => messages,
- Err(e) if is_handler_absent(&e) => {
- log::debug!(
- "[tool][whatsapp_data] search_messages handler_absent — degrading ({e})"
- );
- let body = serde_json::to_string(&json!({
- "provider": "whatsapp",
- "count": 0,
- "messages": [],
- "note": UNAVAILABLE_NOTE,
- }))?;
- return Ok(ToolResult::success(body));
- }
- Err(e) => {
- log::warn!("[tool][whatsapp_data] search_messages bridge_error error={e}");
- return Err(anyhow::anyhow!("whatsapp_data_search_messages: {e}"));
- }
- };
- log::debug!(
- "[tool][whatsapp_data] search_messages returning count={}",
- messages.len()
- );
- let body = serde_json::to_string(&json!({
- "provider": "whatsapp",
- "count": messages.len(),
- "messages": messages,
- }))?;
- Ok(ToolResult::success(body))
- }
-
- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {
- true
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::openhuman::tools::traits::{PermissionLevel, ToolScope};
-
- #[test]
- fn metadata_advertises_whatsapp() {
- let tool = WhatsAppDataSearchMessagesTool;
- assert_eq!(tool.name(), "whatsapp_data_search_messages");
- assert!(tool.description().contains("WhatsApp"));
- assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);
- assert_eq!(tool.scope(), ToolScope::All);
- assert!(tool.is_concurrency_safe(&serde_json::Value::Null));
- }
-
- #[test]
- fn parameters_schema_requires_query() {
- let schema = WhatsAppDataSearchMessagesTool.parameters_schema();
- let required = schema["required"]
- .as_array()
- .expect("required array present");
- let names: Vec<&str> = required.iter().filter_map(|v| v.as_str()).collect();
- assert_eq!(names, vec!["query"]);
- }
-
- #[tokio::test]
- async fn execute_rejects_missing_query() {
- let tool = WhatsAppDataSearchMessagesTool;
- let err = tool
- .execute(json!({}))
- .await
- .expect_err("expected missing query error");
- assert!(err.to_string().contains("whatsapp_data_search_messages"));
- }
-
- #[tokio::test]
- async fn execute_degrades_gracefully_without_shell_handler() {
- let tool = WhatsAppDataSearchMessagesTool;
- let result = tool
- .execute(json!({ "query": "hello" }))
- .await
- .expect("degradation must succeed, not error");
- let body: serde_json::Value =
- serde_json::from_str(&result.text()).expect("tool body is JSON");
- assert_eq!(body["provider"], "whatsapp");
- assert_eq!(body["count"], 0);
- assert_eq!(body["note"], UNAVAILABLE_NOTE);
- }
-}
diff --git a/src/openhuman/channels/whatsapp_data/types.rs b/src/openhuman/channels/whatsapp_data/types.rs
deleted file mode 100644
index a8b5003966..0000000000
--- a/src/openhuman/channels/whatsapp_data/types.rs
+++ /dev/null
@@ -1,134 +0,0 @@
-//! Normalized WhatsApp data structures — local-only, never transmitted externally.
-//!
-//! These types represent the structured data extracted from WhatsApp Web via CDP and
-//! persisted in a local SQLite database. All data remains local; nothing is sent to
-//! any remote service.
-
-use std::collections::HashMap;
-
-use serde::{Deserialize, Serialize};
-
-/// A WhatsApp chat (conversation) record stored locally.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct WhatsAppChat {
- pub chat_id: String,
- /// Human-readable display name from WhatsApp contacts/group metadata.
- pub display_name: String,
- /// True if this chat is a group conversation.
- pub is_group: bool,
- /// The connected WhatsApp account identifier.
- pub account_id: String,
- /// Unix timestamp (seconds) of the most recent message stored.
- pub last_message_ts: i64,
- /// Number of messages stored for this chat.
- pub message_count: u32,
- /// Unix timestamp (seconds) when this record was last updated.
- pub updated_at: i64,
-}
-
-/// A single WhatsApp message record stored locally.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct WhatsAppMessage {
- /// WhatsApp message identifier (compound or bare form).
- pub message_id: String,
- /// JID of the chat this message belongs to.
- pub chat_id: String,
- /// Display name of the sender (stored as-is from WhatsApp).
- pub sender: String,
- /// JID of the sender, when available from IDB metadata.
- pub sender_jid: Option<String>,
- /// True if the message was sent by the account owner.
- pub from_me: bool,
- /// Decrypted message body text.
- pub body: String,
- /// Unix timestamp (seconds) of the message.
- pub timestamp: i64,
- /// WhatsApp message type (e.g. "chat", "image", "sticker").
- pub message_type: Option<String>,
- /// The connected WhatsApp account identifier.
- pub account_id: String,
- /// Data source: "cdp-dom" or "cdp-indexeddb".
- pub source: String,
-}
-
-/// Metadata about a single chat in an ingest payload.
-#[derive(Debug, Deserialize)]
-pub struct ChatMeta {
- /// Display name for the chat, if available.
- pub name: Option<String>,
-}
-
-/// A single message entry in an ingest payload.
-#[derive(Debug, Deserialize)]
-pub struct IngestMessage {
- pub message_id: String,
- pub chat_id: String,
- pub sender: Option<String>,
- pub sender_jid: Option<String>,
- pub from_me: Option<bool>,
- pub body: Option<String>,
- pub timestamp: Option<i64>,
- pub message_type: Option<String>,
- pub source: Option<String>,
-}
-
-/// Request payload for `openhuman.whatsapp_data_ingest`.
-#[derive(Debug, Deserialize)]
-pub struct IngestRequest {
- /// The WhatsApp account identifier (usually the phone JID).
- pub account_id: String,
- /// Map of chat JID → chat metadata (display name, etc.).
- pub chats: HashMap<String, ChatMeta>,
- /// Messages to upsert into the local store.
- pub messages: Vec<IngestMessage>,
-}
-
-/// Summary result returned after an ingest operation.
-#[derive(Debug, Serialize)]
-pub struct IngestResult {
- pub chats_upserted: usize,
- pub messages_upserted: usize,
- pub messages_pruned: u64,
-}
-
-/// Request payload for `openhuman.whatsapp_data_list_chats`.
-#[derive(Debug, Deserialize)]
-pub struct ListChatsRequest {
- /// Optional filter by account. When absent, all accounts are returned.
- pub account_id: Option<String>,
- /// Maximum number of results (default: 50).
- pub limit: Option<u32>,
- /// Pagination offset (default: 0).
- pub offset: Option<u32>,
-}
-
-/// Request payload for `openhuman.whatsapp_data_list_messages`.
-#[derive(Debug, Deserialize)]
-pub struct ListMessagesRequest {
- /// JID of the chat to retrieve messages for.
- pub chat_id: String,
- /// Optional filter by account. When absent, all accounts are searched.
- pub account_id: Option<String>,
- /// Only return messages at or after this Unix timestamp (seconds).
- pub since_ts: Option<i64>,
- /// Only return messages at or before this Unix timestamp (seconds).
- pub until_ts: Option<i64>,
- /// Maximum number of results (default: 100).
- pub limit: Option<u32>,
- /// Pagination offset (default: 0).
- pub offset: Option<u32>,
-}
-
-/// Request payload for `openhuman.whatsapp_data_search_messages`.
-#[derive(Debug, Deserialize)]
-pub struct SearchMessagesRequest {
- /// Full-text search query matched against message bodies (case-insensitive LIKE).
- pub query: String,
- /// Optional filter by chat JID.
- pub chat_id: Option<String>,
- /// Optional filter by account. When absent, all accounts are searched.
- pub account_id: Option<String>,
- /// Maximum number of results (default: 20).
- pub limit: Option<u32>,
-}
diff --git a/src/openhuman/security/policy/types.rs b/src/openhuman/security/policy/types.rs
index dd6c253d1d..73bb8ee69d 100644
--- a/src/openhuman/security/policy/types.rs
+++ b/src/openhuman/security/policy/types.rs
@@ -189,6 +189,10 @@ pub(super) const WORKSPACE_INTERNAL_DIRS: &[&str] = &[
"subconscious",
"vault",
"task_sources",
+ // The whatsapp_data store was removed along with the scanner that wrote it,
+ // but an upgraded profile can still hold `whatsapp_data/whatsapp_data.db`
+ // (chat and message history) from an older version. Keep the directory on
+ // the internal denylist so agents with workspace access cannot read it.
"whatsapp_data",
// The redirect_links domain was removed (#5051), but an upgraded profile can
// still hold a legacy `redirect_links/links.db` (stored URL history) written
diff --git a/src/openhuman/tools/mod.rs b/src/openhuman/tools/mod.rs
index 6e31da5668..db8fed9f02 100644
--- a/src/openhuman/tools/mod.rs
+++ b/src/openhuman/tools/mod.rs
@@ -19,8 +19,6 @@ pub use crate::openhuman::agent::artifacts::tools::*;
pub use crate::openhuman::agent::learning::tools::*;
pub use crate::openhuman::agent::orchestration::tools::*;
pub use crate::openhuman::agent::tools::*;
-#[cfg(feature = "channels")]
-pub use crate::openhuman::channels::whatsapp_data::tools::*;
pub use crate::openhuman::config::tools::*;
pub use crate::openhuman::config::workspace::tools::*;
pub use crate::openhuman::cron::tools::*;
diff --git a/src/openhuman/tools/ops.rs b/src/openhuman/tools/ops.rs
index e126b9a9fe..b19b7c13e0 100644
--- a/src/openhuman/tools/ops.rs
+++ b/src/openhuman/tools/ops.rs
@@ -480,16 +480,6 @@ pub fn all_tools_with_runtime(
// per-query recall). Written verbatim to user_pref_{general,situational};
// bypasses the inference/stability pipeline. Always registered.
Box::new(SavePreferenceTool::new(security.clone())),
- // WhatsApp data store — read-only agent surface (issue #1341). The
- // store lives in the Tauri shell; these tools reach it over the
- // in-process native request bus. The matching ingest write-path is
- // scanner-only (dispatched by the shell) and intentionally NOT a tool.
- #[cfg(feature = "channels")]
- Box::new(WhatsAppDataListChatsTool),
- #[cfg(feature = "channels")]
- Box::new(WhatsAppDataListMessagesTool),
- #[cfg(feature = "channels")]
- Box::new(WhatsAppDataSearchMessagesTool),
Box::new(ScheduleTool::new(security.clone(), root_config.clone())),
Box::new(ProxyConfigTool::new(config.clone(), security.clone())),
Box::new(UpdateCheckTool::new()),
@@ -1325,12 +1315,6 @@ fn tool_group(name: &str) -> crate::core::all::DomainGroup {
if name.starts_with("media_") {
return DomainGroup::Media;
}
- // Channels family agent tools: read-only WhatsApp data surface. Gated with
- // the other channel/webview domains; without this they fall to Platform and
- // stay callable when Channels is gated off (#4808 review).
- if name.starts_with("whatsapp_data_") {
- return DomainGroup::Channels;
- }
// Voice family: explicit audio_* podcast tools plus the defensive
// voice_/tts_/stt_ prefixes for any future tool.
if VOICE.contains(&name)