Skip to content

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

refactor(notifications): split notification store into focused modules

Steven Enamakelb631574a4de5
diff --git a/crates/openhuman-core/src/desktop/notifications/store.rs b/crates/openhuman-core/src/desktop/notifications/store.rs
index 8eb6bc5379..c7440eb44d 100644
--- a/crates/openhuman-core/src/desktop/notifications/store.rs
+++ b/crates/openhuman-core/src/desktop/notifications/store.rs
@@ -1,15 +1,12 @@
-//! SQLite persistence for `IntegrationNotification` records.
+//! Persistence for `IntegrationNotification` records.
//!
-//! With a storage backend configured ([`crate::storage`]) every function
-//! here is served from the document port instead (`store_documents.rs`).
-//!
-//! Uses a synchronous `rusqlite::Connection` opened per call, following the
-//! same `with_connection` pattern as the cron domain.
+//! Every function here is served from the document port
+//! (`store_documents.rs`), in the storage backend and the acting scope. The
+//! `notifications/notifications.db` older installs wrote is read once,
+//! read-only, by the storage importer (`store_import.rs`).
-use crate::storage::rusqlite;
-use anyhow::{Context, Result};
+use anyhow::Result;
use chrono::Utc;
-use rusqlite::{params, Connection};
use crate::config::Config;
@@ -17,134 +14,14 @@ use super::types::{
CoreNotificationEvent, IntegrationNotification, NotificationSettings, NotificationStatus,
};
-/// SQL schema applied on every `with_connection` call (idempotent).
-const SCHEMA: &str = "
-PRAGMA foreign_keys = ON;
-
-CREATE TABLE IF NOT EXISTS integration_notifications (
- id TEXT PRIMARY KEY,
- provider TEXT NOT NULL,
- account_id TEXT,
- title TEXT NOT NULL,
- body TEXT NOT NULL,
- raw_payload TEXT NOT NULL,
- importance_score REAL,
- triage_action TEXT,
- triage_reason TEXT,
- status TEXT NOT NULL DEFAULT 'unread',
- received_at TEXT NOT NULL,
- scored_at TEXT
-);
-CREATE INDEX IF NOT EXISTS idx_integration_notifications_provider
- ON integration_notifications(provider);
-CREATE INDEX IF NOT EXISTS idx_integration_notifications_status
- ON integration_notifications(status);
-CREATE INDEX IF NOT EXISTS idx_integration_notifications_dedup
- ON integration_notifications(provider, account_id, title, body, received_at);
-
-CREATE TABLE IF NOT EXISTS notification_settings (
- provider TEXT PRIMARY KEY,
- enabled INTEGER NOT NULL DEFAULT 1,
- importance_threshold REAL NOT NULL DEFAULT 0.0,
- route_to_orchestrator INTEGER NOT NULL DEFAULT 1
-);
-
--- #3805: core notification events (cron completions, webhook failures,
--- sub-agent results, triaged alerts, …) are broadcast over an in-memory
--- channel that drops the event when no client is connected. Persist them
--- here so a notification fired while the app is closed/minimised/disconnected
--- survives and is surfaced on the next app open. The full wire payload is
--- stored as JSON; `id` is the PK so re-publishes dedupe naturally.
-CREATE TABLE IF NOT EXISTS core_notifications (
- id TEXT PRIMARY KEY,
- payload TEXT NOT NULL,
- timestamp_ms INTEGER NOT NULL,
- read INTEGER NOT NULL DEFAULT 0,
- created_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_core_notifications_read
- ON core_notifications(read);
-CREATE INDEX IF NOT EXISTS idx_core_notifications_ts
- ON core_notifications(timestamp_ms);
-";
-
-/// Open (and migrate) the notifications DB, then call `f` with the live
-/// connection. Mirrors the `with_connection` helper in `cron/store.rs`.
-pub(super) fn db_path(config: &Config) -> std::path::PathBuf {
- config
- .workspace_dir
- .join("notifications")
- .join("notifications.db")
-}
-
-pub(super) fn with_connection<T>(
- config: &Config,
- f: impl FnOnce(&Connection) -> Result<T>,
-) -> Result<T> {
- let db_path = db_path(config);
-
- tracing::trace!(
- path = %db_path.display(),
- "[notifications::store] opening DB connection"
- );
-
- if let Some(parent) = db_path.parent() {
- std::fs::create_dir_all(parent).with_context(|| {
- format!(
- "[notifications::store] failed to create dir {}",
- parent.display()
- )
- })?;
- }
-
- let conn = Connection::open(&db_path).with_context(|| {
- format!(
- "[notifications::store] failed to open DB at {}",
- db_path.display()
- )
- })?;
-
- conn.execute_batch(SCHEMA)
- .context("[notifications::store] schema migration failed")?;
-
- tracing::trace!("[notifications::store] schema migration applied, running operation");
- f(&conn)
-}
-
// ─────────────────────────────────────────────────────────────────────────────
// Public API
// ─────────────────────────────────────────────────────────────────────────────
/// Persist a new notification to the store.
pub fn insert(config: &Config, n: &IntegrationNotification) -> Result<()> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.insert(n, false).map(|_| ());
- }
- with_connection(config, |conn| {
- conn.execute(
- "INSERT INTO integration_notifications
- (id, provider, account_id, title, body, raw_payload,
- importance_score, triage_action, triage_reason, status,
- received_at, scored_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
- params![
- n.id,
- n.provider,
- n.account_id,
- n.title,
- n.body,
- n.raw_payload.to_string(),
- n.importance_score,
- n.triage_action,
- n.triage_reason,
- n.status.as_str(),
- n.received_at.to_rfc3339(),
- n.scored_at.map(|t| t.to_rfc3339()),
- ],
- )
- .context("[notifications::store] insert failed")?;
- Ok(())
- })
+ let docs = super::store_documents::current(config)?;
+ docs.insert(n, false).map(|_| ())
}
// ─────────────────────────────────────────────────────────────────────────────
@@ -158,27 +35,8 @@ pub fn insert(config: &Config, n: &IntegrationNotification) -> Result<()> {
/// event is ignored (no duplicates). Returns `true` when a new row was written,
/// `false` when an event with the same id already existed.
pub fn insert_core_notification(config: &Config, event: &CoreNotificationEvent) -> Result<bool> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.insert_core_notification(docs.workspace(), event);
- }
- with_connection(config, |conn| {
- let payload = serde_json::to_string(event)
- .context("[notifications::store] serialize core notification failed")?;
- let affected = conn
- .execute(
- "INSERT OR IGNORE INTO core_notifications
- (id, payload, timestamp_ms, read, created_at)
- VALUES (?1, ?2, ?3, 0, ?4)",
- params![
- event.id,
- payload,
- event.timestamp_ms as i64,
- Utc::now().to_rfc3339(),
- ],
- )
- .context("[notifications::store] insert_core_notification failed")?;
- Ok(affected > 0)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.insert_core_notification(docs.workspace(), event)
}
/// Return persisted core notifications, newest first. When `only_unread` is
@@ -189,149 +47,29 @@ pub fn list_core_notifications(
only_unread: bool,
limit: usize,
) -> Result<Vec<CoreNotificationEvent>> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.list_core_notifications(docs.workspace(), only_unread, limit);
- }
- with_connection(config, |conn| {
- let sql = if only_unread {
- "SELECT payload FROM core_notifications WHERE read = 0
- ORDER BY timestamp_ms DESC LIMIT ?1"
- } else {
- "SELECT payload FROM core_notifications
- ORDER BY timestamp_ms DESC LIMIT ?1"
- };
- let mut stmt = conn
- .prepare(sql)
- .context("[notifications::store] prepare list_core_notifications failed")?;
- let rows = stmt
- .query_map(params![limit as i64], |row| row.get::<_, String>(0))
- .context("[notifications::store] query list_core_notifications failed")?;
-
- let mut out = Vec::new();
- for row in rows {
- let payload =
- row.context("[notifications::store] read core notification row failed")?;
- match serde_json::from_str::<CoreNotificationEvent>(&payload) {
- Ok(event) => out.push(event),
- // A single corrupt row must not break the whole sync-down.
- Err(err) => tracing::warn!(
- error = %err,
- "[notifications::store] skipping undeserializable core notification"
- ),
- }
- }
- Ok(out)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.list_core_notifications(docs.workspace(), only_unread, limit)
}
/// Mark a persisted core notification as read so it isn't re-surfaced on the
/// next sync-down. Returns `true` when a row was updated.
pub fn mark_core_notification_read(config: &Config, id: &str) -> Result<bool> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.mark_core_notification_read(docs.workspace(), id);
- }
- with_connection(config, |conn| {
- let affected = conn
- .execute(
- "UPDATE core_notifications SET read = 1 WHERE id = ?1",
- params![id],
- )
- .context("[notifications::store] mark_core_notification_read failed")?;
- Ok(affected > 0)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.mark_core_notification_read(docs.workspace(), id)
}
/// Count unread persisted core notifications.
pub fn unread_core_notification_count(config: &Config) -> Result<i64> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.unread_core_notification_count(docs.workspace());
- }
- with_connection(config, |conn| {
- let count: i64 = conn
- .query_row(
- "SELECT COUNT(*) FROM core_notifications WHERE read = 0",
- [],
- |row| row.get(0),
- )
- .context("[notifications::store] unread_core_notification_count failed")?;
- Ok(count)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.unread_core_notification_count(docs.workspace())
}
/// Atomically insert a notification unless a matching one arrived recently.
///
/// Returns `true` when inserted, `false` when skipped as duplicate.
pub fn insert_if_not_recent(config: &Config, n: &IntegrationNotification) -> Result<bool> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.insert(n, true);
- }
- with_connection(config, |conn| {
- conn.execute_batch("BEGIN IMMEDIATE")
- .context("[notifications::store] begin insert_if_not_recent tx failed")?;
-
- let result: Result<bool> = (|| {
- let count: i64 = match n.account_id.as_deref() {
- Some(aid) => conn.query_row(
- "SELECT COUNT(*) FROM integration_notifications
- WHERE provider = ?1 AND account_id = ?2
- AND title = ?3 AND body = ?4
- AND unixepoch(received_at) >= unixepoch('now', '-60 seconds')",
- params![&n.provider, aid, &n.title, &n.body],
- |row| row.get(0),
- ),
- None => conn.query_row(
- "SELECT COUNT(*) FROM integration_notifications
- WHERE provider = ?1 AND account_id IS NULL
- AND title = ?2 AND body = ?3
- AND unixepoch(received_at) >= unixepoch('now', '-60 seconds')",
- params![&n.provider, &n.title, &n.body],
- |row| row.get(0),
- ),
- }
- .context("[notifications::store] insert_if_not_recent dedup query failed")?;
-
- if count > 0 {
- return Ok(false);
- }
-
- conn.execute(
- "INSERT INTO integration_notifications
- (id, provider, account_id, title, body, raw_payload,
- importance_score, triage_action, triage_reason, status,
- received_at, scored_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
- params![
- n.id,
- n.provider,
- n.account_id,
- n.title,
- n.body,
- n.raw_payload.to_string(),
- n.importance_score,
- n.triage_action,
- n.triage_reason,
- n.status.as_str(),
- n.received_at.to_rfc3339(),
- n.scored_at.map(|t| t.to_rfc3339()),
- ],
- )
- .context("[notifications::store] insert_if_not_recent insert failed")?;
-
- Ok(true)
- })();
-
- if result.is_ok() {
- conn.execute_batch("COMMIT")
- .context("[notifications::store] commit insert_if_not_recent tx failed")?;
- } else if let Err(rollback_err) = conn.execute_batch("ROLLBACK") {
- tracing::warn!(
- error = %rollback_err,
- "[notifications::store] rollback insert_if_not_recent tx failed"
- );
- }
-
- result
- })
+ let docs = super::store_documents::current(config)?;
+ docs.insert(n, true)
}
/// List notifications with optional filtering.
@@ -342,46 +80,8 @@ pub fn list(
provider_filter: Option<&str>,
min_score: Option<f32>,
) -> Result<Vec<IntegrationNotification>> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.list(limit, offset, provider_filter, min_score);
- }
- with_connection(config, |conn| {
- // Build a dynamic query instead of relying on nullable-aware WHERE
- // logic so the SQL stays readable for future contributors.
- let mut sql = String::from(
- "SELECT id, provider, account_id, title, body, raw_payload,
- importance_score, triage_action, triage_reason, status,
- received_at, scored_at
- FROM integration_notifications
- WHERE 1=1",
- );
- if provider_filter.is_some() {
- sql.push_str(" AND provider = ?1");
- }
- if min_score.is_some() {
- if provider_filter.is_some() {
- sql.push_str(" AND (importance_score IS NULL OR importance_score >= ?2)");
- } else {
- sql.push_str(" AND (importance_score IS NULL OR importance_score >= ?1)");
- }
- }
- sql.push_str(" ORDER BY received_at DESC");
- sql.push_str(&format!(" LIMIT {limit} OFFSET {offset}"));
-
- let mut stmt = conn
- .prepare(&sql)
- .context("[notifications::store] prepare list failed")?;
-
- let rows = match (provider_filter, min_score) {
- (Some(p), Some(s)) => stmt.query(params![p, s]),
- (Some(p), None) => stmt.query(params![p]),
- (None, Some(s)) => stmt.query(params![s]),
- (None, None) => stmt.query([]),
- }
- .context("[notifications::store] list query failed")?;
-
- rows_to_notifications(rows)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.list(limit, offset, provider_filter, min_score)
}
/// Update triage scoring fields in-place.
@@ -392,87 +92,28 @@ pub fn update_triage(
action: &str,
reason: &str,
) -> Result<()> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.update_triage(id, score, action, reason).map(|found| {
- if !found {
- tracing::warn!(id = %id, action = %action, "[notifications::store] update_triage matched no rows");
- }
- });
- }
- with_connection(config, |conn| {
- let now = Utc::now().to_rfc3339();
- let updated = conn
- .execute(
- "UPDATE integration_notifications
- SET importance_score = ?1, triage_action = ?2, triage_reason = ?3, scored_at = ?4
- WHERE id = ?5",
- params![score, action, reason, now, id],
- )
- .context("[notifications::store] update_triage failed")?;
- if updated == 0 {
- // The row may have been deleted between ingest and scoring.
- // Surface it at warn level so orphaned triage runs don't fail
- // silently.
- tracing::warn!(
- id = %id,
- action = %action,
- "[notifications::store] update_triage matched no rows"
- );
- } else {
- tracing::debug!(
- id = %id,
- action = %action,
- score = score,
- "[notifications::store] update_triage applied"
- );
+ let docs = super::store_documents::current(config)?;
+ docs.update_triage(id, score, action, reason).map(|found| {
+ if !found {
+ tracing::warn!(id = %id, action = %action, "[notifications::store] update_triage matched no rows");
}
- Ok(())
})
}
/// Transition a notification from `unread` to `read`.
pub fn mark_read(config: &Config, id: &str) -> Result<()> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.set_status(id, NotificationStatus::Read).map(|found| {
- if !found {
- tracing::warn!(id = %id, "[notifications::store] mark_read matched no rows");
- }
- });
- }
- with_connection(config, |conn| {
- let updated = conn
- .execute(
- "UPDATE integration_notifications SET status = 'read' WHERE id = ?1",
- params![id],
- )
- .context("[notifications::store] mark_read failed")?;
- if updated == 0 {
- tracing::warn!(
- id = %id,
- "[notifications::store] mark_read matched no rows"
- );
- } else {
- tracing::debug!(id = %id, "[notifications::store] mark_read applied");
+ let docs = super::store_documents::current(config)?;
+ docs.set_status(id, NotificationStatus::Read).map(|found| {
+ if !found {
+ tracing::warn!(id = %id, "[notifications::store] mark_read matched no rows");
}
- Ok(())
})
}
/// Count unread notifications.
pub fn unread_count(config: &Config) -> Result<i64> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.unread_count();
- }
- with_connection(config, |conn| {
- let count: i64 = conn
- .query_row(
- "SELECT COUNT(*) FROM integration_notifications WHERE status = 'unread'",
- [],
- |row| row.get(0),
- )
- .context("[notifications::store] unread_count failed")?;
- Ok(count)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.unread_count()
}
/// Check whether a notification with identical content was received in the
@@ -484,232 +125,44 @@ pub fn exists_recent(
title: &str,
body: &str,
) -> Result<bool> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.exists_recent(provider, account_id, title, body);
- }
- with_connection(config, |conn| {
- let count: i64 = match account_id {
- Some(aid) => conn.query_row(
- "SELECT COUNT(*) FROM integration_notifications
- WHERE provider = ?1 AND account_id = ?2
- AND title = ?3 AND body = ?4
- AND unixepoch(received_at) >= unixepoch('now', '-60 seconds')",
- params![provider, aid, title, body],
- |row| row.get(0),
- ),
- None => conn.query_row(
- "SELECT COUNT(*) FROM integration_notifications
- WHERE provider = ?1 AND account_id IS NULL
- AND title = ?2 AND body = ?3
- AND unixepoch(received_at) >= unixepoch('now', '-60 seconds')",
- params![provider, title, body],
- |row| row.get(0),
- ),
- }
- .context("[notifications::store] exists_recent query failed")?;
- Ok(count > 0)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.exists_recent(provider, account_id, title, body)
}
/// Transition a notification status to 'dismissed'.
///
/// Returns `true` when at least one row matched and was updated.
pub fn mark_dismissed(config: &Config, id: &str) -> Result<bool> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.set_status(id, NotificationStatus::Dismissed);
- }
- with_connection(config, |conn| {
- let updated = conn
- .execute(
- "UPDATE integration_notifications SET status = 'dismissed' WHERE id = ?1",
- params![id],
- )
- .context("[notification_intel] mark_dismissed failed")?;
- let matched = updated > 0;
- if !matched {
- tracing::warn!(id = %id, "[notification_intel] mark_dismissed matched no rows");
- } else {
- tracing::debug!(id = %id, "[notification_intel] mark_dismissed applied");
- }
- Ok(matched)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.set_status(id, NotificationStatus::Dismissed)
}
/// Transition a notification status to 'acted'.
///
/// Returns `true` when at least one row matched and was updated.
pub fn mark_acted(config: &Config, id: &str) -> Result<bool> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.set_status(id, NotificationStatus::Acted);
- }
- with_connection(config, |conn| {
- let updated = conn
- .execute(
- "UPDATE integration_notifications SET status = 'acted' WHERE id = ?1",
- params![id],
- )
- .context("[notification_intel] mark_acted failed")?;
- let matched = updated > 0;
- if !matched {
- tracing::warn!(id = %id, "[notification_intel] mark_acted matched no rows");
- } else {
- tracing::debug!(id = %id, "[notification_intel] mark_acted applied");
- }
- Ok(matched)
- })
+ let docs = super::store_documents::current(config)?;
+ docs.set_status(id, NotificationStatus::Acted)
}
/// Return aggregate statistics for the notification intelligence pipeline.
pub fn stats(config: &Config) -> Result<super::types::NotificationStats> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.stats();
- }
- use std::collections::HashMap;
- with_connection(config, |conn| {
- let total: i64 = conn
- .query_row("SELECT COUNT(*) FROM integration_notifications", [], |r| {
- r.get(0)
- })
- .context("[notification_intel] stats total query failed")?;
-
- let unread: i64 = conn
- .query_row(
- "SELECT COUNT(*) FROM integration_notifications WHERE status = 'unread'",
- [],
- |r| r.get(0),
- )
- .context("[notification_intel] stats unread query failed")?;
-
- let unscored: i64 = conn
- .query_row(
- "SELECT COUNT(*) FROM integration_notifications WHERE importance_score IS NULL",
- [],
- |r| r.get(0),
- )
- .context("[notification_intel] stats unscored query failed")?;
-
- // Per-provider counts
- let mut by_provider = HashMap::new();
- {
- let mut stmt = conn
- .prepare(
- "SELECT provider, COUNT(*) FROM integration_notifications GROUP BY provider",
- )
- .context("[notification_intel] stats by_provider prepare failed")?;
- let rows = stmt
- .query_map([], |row| {
- Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
- })
- .context("[notification_intel] stats by_provider query failed")?;
- for row in rows {
- let (provider, count) =
- row.context("[notification_intel] stats by_provider row failed")?;
- by_provider.insert(provider, count);
- }
- }
-
- // Per-action counts (only where triage_action is set)
- let mut by_action = HashMap::new();
- {
- let mut stmt = conn
- .prepare(
- "SELECT triage_action, COUNT(*) FROM integration_notifications \
- WHERE triage_action IS NOT NULL GROUP BY triage_action",
- )
- .context("[notification_intel] stats by_action prepare failed")?;
- let rows = stmt
- .query_map([], |row| {
- Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
- })
- .context("[notification_intel] stats by_action query failed")?;
- for row in rows {
- let (action, count) =
- row.context("[notification_intel] stats by_action row failed")?;
- by_action.insert(action, count);
- }
- }
-
- tracing::debug!(
- total = total,
- unread = unread,
- unscored = unscored,
- "[notification_intel] stats query completed"
- );
-
- Ok(super::types::NotificationStats {
- total,
- unread,
- unscored,
- by_provider,
- by_action,
- })
- })
+ let docs = super::store_documents::current(config)?;
+ docs.stats()
}
/// Upsert provider-level notification settings.
pub fn upsert_settings(config: &Config, settings: &NotificationSettings) -> Result<()> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.upsert_settings(settings);
- }
- with_connection(config, |conn| {
- conn.execute(
- "INSERT INTO notification_settings (provider, enabled, importance_threshold, route_to_orchestrator)
- VALUES (?1, ?2, ?3, ?4)
- ON CONFLICT(provider) DO UPDATE SET
- enabled = excluded.enabled,
- importance_threshold = excluded.importance_threshold,
- route_to_orchestrator = excluded.route_to_orchestrator",
- params![
- settings.provider,
- if settings.enabled { 1 } else { 0 },
- settings.importance_threshold,
- if settings.route_to_orchestrator { 1 } else { 0 }
- ],
- )
- .context("[notifications::store] upsert_settings failed")?;
- Ok(())
- })
+ let docs = super::store_documents::current(config)?;
+ docs.upsert_settings(settings)
}
/// Read provider-level notification settings with defaults when missing.
pub fn get_settings(config: &Config, provider: &str) -> Result<NotificationSettings> {
- if let Some(docs) = super::store_documents::current(config)? {
- return docs.get_settings(provider);
- }
- with_connection(config, |conn| {
- let mut stmt = conn
- .prepare(
- "SELECT provider, enabled, importance_threshold, route_to_orchestrator
- FROM notification_settings
- WHERE provider = ?1",
- )
- .context("[notifications::store] prepare get_settings failed")?;
- let mut rows = stmt
- .query(params![provider])
- .context("[notifications::store] get_settings query failed")?;
- if let Some(row) = rows
- .next()
- .context("[notifications::store] get_settings row failed")?
- {
- return Ok(NotificationSettings {
- provider: row.get(0)?,
- enabled: row.get::<_, i64>(1)? != 0,
- importance_threshold: row.get(2)?,
- route_to_orchestrator: row.get::<_, i64>(3)? != 0,
- });
- }
- Ok(NotificationSettings {
- provider: provider.to_string(),
- ..NotificationSettings::default()
- })
- })
+ let docs = super::store_documents::current(config)?;
+ docs.get_settings(provider)
}
-#[path = "store_import.rs"]
-pub(super) mod import;
-mod store_rows;
-use store_rows::rows_to_notifications;
-
#[cfg(test)]
#[path = "store_tests.rs"]
mod store_tests;
diff --git a/crates/openhuman-core/src/desktop/notifications/store/store_rows.rs b/crates/openhuman-core/src/desktop/notifications/store/store_rows.rs
deleted file mode 100644
index ffc7a12aa8..0000000000
--- a/crates/openhuman-core/src/desktop/notifications/store/store_rows.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-//! Row conversion for the SQLite notification store.
-
-use crate::storage::rusqlite;
-use anyhow::{Context, Result};
-use chrono::{DateTime, Utc};
-
-use super::super::types::{IntegrationNotification, NotificationStatus};
-
-pub(super) fn rows_to_notifications(
- mut rows: rusqlite::Rows<'_>,
-) -> Result<Vec<IntegrationNotification>> {
- let mut out = Vec::new();
- while let Some(row) = rows
- .next()
- .context("[notifications::store] row iteration failed")?
- {
- out.push(row_to_notification(row)?);
- }
- Ok(out)
-}
-
-fn row_to_notification(row: &rusqlite::Row<'_>) -> Result<IntegrationNotification> {
- let raw_payload_str: String = row.get(5)?;
- let raw_payload: serde_json::Value = serde_json::from_str(&raw_payload_str)
- .unwrap_or(serde_json::Value::String(raw_payload_str));
-
- let status_str: String = row.get(9)?;
- let status = match status_str.as_str() {
- "read" => NotificationStatus::Read,
- "acted" => NotificationStatus::Acted,
- "dismissed" => NotificationStatus::Dismissed,
- _ => NotificationStatus::Unread,
- };
-
- let received_at_str: String = row.get(10)?;
- let received_at: DateTime<Utc> = received_at_str.parse().unwrap_or_else(|e| {
- tracing::warn!(
- raw = %received_at_str,
- error = %e,
- "[notifications::store] invalid received_at, using now"
- );
- Utc::now()
- });
-
- let scored_at_str: Option<String> = row.get(11)?;
- let scored_at: Option<DateTime<Utc>> = scored_at_str.and_then(|s| match s.parse() {
- Ok(t) => Some(t),
- Err(e) => {
- tracing::warn!(
- raw = %s,
- error = %e,
- "[notifications::store] invalid scored_at, treating as unscored"
- );
- None
- }
- });
-
- Ok(IntegrationNotification {
- id: row.get(0)?,
- provider: row.get(1)?,
- account_id: row.get(2)?,
- title: row.get(3)?,
- body: row.get(4)?,
- raw_payload,
- importance_score: row.get(6)?,
- triage_action: row.get(7)?,
- triage_reason: row.get(8)?,
- status,
- received_at,
- scored_at,
- })
-}
diff --git a/crates/openhuman-core/src/desktop/notifications/store_import.rs b/crates/openhuman-core/src/desktop/notifications/store_import.rs
index de455a2e14..90d1f07b2b 100644
--- a/crates/openhuman-core/src/desktop/notifications/store_import.rs
+++ b/crates/openhuman-core/src/desktop/notifications/store_import.rs
@@ -11,27 +11,114 @@
//! `core_notifications` rows carry no workspace, so they take the fixed
//! `LOCAL_WORKSPACE` key the per-workspace default file filters on (not the
//! directory path, which changes when the workspace is moved).
-//! (The content-dedup window needs no import: it lasts a minute.) The driver
-//! ([`crate::storage::local`]) writes the documents and then renames the
-//! tables to `_legacy_<name>`.
+//! (The content-dedup window needs no import: it lasts a minute.) The legacy
+//! file is only ever opened here, by the storage importer, on a scratch copy.
use crate::storage::rusqlite;
use anyhow::{Context, Result};
use rusqlite::Connection;
use serde_json::json;
-use super::super::store_documents::{
+use super::store_documents::{
core_id, to_doc, CORE, LOCAL_WORKSPACE, NOTIFICATIONS, SETTINGS,
};
use crate::config::Config;
use crate::storage::import::{table_exists, ImportDoc};
-/// The legacy tables this import retires.
-pub(crate) const TABLES: &[&str] = &[
- "integration_notifications",
- "notification_settings",
- "core_notifications",
-];
+/// SQL schema of the legacy database, applied on every `with_connection` call.
+const SCHEMA: &str = "
+PRAGMA foreign_keys = ON;
+
+CREATE TABLE IF NOT EXISTS integration_notifications (
+ id TEXT PRIMARY KEY,
+ provider TEXT NOT NULL,
+ account_id TEXT,
+ title TEXT NOT NULL,
+ body TEXT NOT NULL,
+ raw_payload TEXT NOT NULL,
+ importance_score REAL,
+ triage_action TEXT,
+ triage_reason TEXT,
+ status TEXT NOT NULL DEFAULT 'unread',
+ received_at TEXT NOT NULL,
+ scored_at TEXT
+);
+CREATE INDEX IF NOT EXISTS idx_integration_notifications_provider
+ ON integration_notifications(provider);
+CREATE INDEX IF NOT EXISTS idx_integration_notifications_status
+ ON integration_notifications(status);
+CREATE INDEX IF NOT EXISTS idx_integration_notifications_dedup
+ ON integration_notifications(provider, account_id, title, body, received_at);
+
+CREATE TABLE IF NOT EXISTS notification_settings (
+ provider TEXT PRIMARY KEY,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ importance_threshold REAL NOT NULL DEFAULT 0.0,
+ route_to_orchestrator INTEGER NOT NULL DEFAULT 1
+);
+
+-- #3805: core notification events (cron completions, webhook failures,
+-- sub-agent results, triaged alerts, …) are broadcast over an in-memory
+-- channel that drops the event when no client is connected. Persist them
+-- here so a notification fired while the app is closed/minimised/disconnected
+-- survives and is surfaced on the next app open. The full wire payload is
+-- stored as JSON; `id` is the PK so re-publishes dedupe naturally.
+CREATE TABLE IF NOT EXISTS core_notifications (
+ id TEXT PRIMARY KEY,
+ payload TEXT NOT NULL,
+ timestamp_ms INTEGER NOT NULL,
+ read INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_core_notifications_read
+ ON core_notifications(read);
+CREATE INDEX IF NOT EXISTS idx_core_notifications_ts
+ ON core_notifications(timestamp_ms);
+";
+
+/// Open (and migrate) the notifications DB, then call `f` with the live
+/// connection. Mirrors the `with_connection` helper in `cron/store.rs`.
+pub(crate) fn db_path(config: &Config) -> std::path::PathBuf {
+ config
+ .workspace_dir
+ .join("notifications")
+ .join("notifications.db")
+}
+
+pub(crate) fn with_connection<T>(
+ config: &Config,
+ f: impl FnOnce(&Connection) -> Result<T>,
+) -> Result<T> {
+ let db_path = db_path(config);
+
+ tracing::trace!(
+ path = %db_path.display(),
+ "[notifications::store] opening DB connection"
+ );
+
+ if let Some(parent) = db_path.parent() {
+ std::fs::create_dir_all(parent).with_context(|| {
+ format!(
+ "[notifications::store] failed to create dir {}",
+ parent.display()
+ )
+ })?;
+ }
+
+ let conn = Connection::open(&db_path).with_context(|| {
+ format!(
+ "[notifications::store] failed to open DB at {}",
+ db_path.display()
+ )
+ })?;
+
+ conn.execute_batch(SCHEMA)
+ .context("[notifications::store] schema migration failed")?;
+
+ tracing::trace!("[notifications::store] schema migration applied, running operation");
+ f(&conn)
+}
+
/// Reads every legacy row.
pub(crate) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
@@ -41,7 +128,7 @@ pub(crate) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
/// [`read`] with core notifications filed under `workspace` instead of the
/// fixed local key.
pub(crate) fn read_for(config: &Config, workspace: &str) -> Result<Vec<ImportDoc>> {
- super::with_connection(config, |conn| read_rows(conn, workspace))
+ with_connection(config, |conn| read_rows(conn, workspace))
}
fn read_rows(conn: &Connection, workspace: &str) -> Result<Vec<ImportDoc>> {