feat(chat): per-conversation delete (revive + block); memoize chat/badge render

Adds a per-conversation "delete" with two modes, and removes the per-frame
rescans of the chat history that shared these files.

Delete conversation (header trash icon → confirm dialog):
- Delete (revive-on-new-message): clears local history and tombstones the
  messages (new chat_deleted table, keyed dedup hashes) so the every-few-
  seconds memo re-scan can't re-import them; a genuinely NEW message (new
  txid) revives the thread.
- Delete & block: removes history WITHOUT a tombstone and records the cid as
  blocked (settings); ChatService::ingest drops that conversation's messages
  — old and future — until unblocked from the "Blocked" manager, which then
  re-imports the conversation from chain.
- Local-only (messages remain on-chain; the peer keeps their copy).
  deleteConversation() deletes the DB rows FIRST and only then mutates the
  store, so a failed write can't leave the two diverged.
Unit-tested (revive / tombstone-survives-reload / block / unblock) and
adversarially reviewed (store/DB divergence, half-open DB, revive-unread).

Performance (chat + badge hot paths, from the perf audit):
- ChatStore gains revision(); the Chat unread badge is now a single O(N)
  no-alloc pass cached on it (was O(conversations x messages) copy+sort every
  frame). The conversation list and open thread are memoized on revision()
  (+ show-hidden and AddressBook::revision() for peer-name resolution).
- AddressBook gains revision() so an in-place contact rename invalidates the
  chat memo (an edit keeps entries().size() constant).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-01 22:54:51 -05:00
co-authored by Claude Opus 4.8
parent a60a2f8e39
commit 0a042df8e0
15 changed files with 611 additions and 45 deletions
+82 -6
View File
@@ -89,6 +89,7 @@ bool ChatDatabase::unlockWithSecret(const std::string& secret)
lock();
return false;
}
loadTombstones();
return true;
}
@@ -97,11 +98,13 @@ void ChatDatabase::lock()
sodium_memzero(key_.data(), key_.size());
key_ready_ = false;
wallet_tag_.clear();
tombstones_.clear();
}
bool ChatDatabase::append(const ChatMessage& message)
{
if (!key_ready_ || !ensureOpen()) return false;
if (isTombstoned(message)) return false; // locally deleted — don't re-persist on a chain re-scan
std::vector<unsigned char> nonce;
std::vector<unsigned char> cipher;
@@ -193,13 +196,79 @@ std::vector<ChatMessage> ChatDatabase::load()
void ChatDatabase::clearWallet()
{
if (wallet_tag_.empty() || !ensureOpen()) return;
for (const char* sql : {"DELETE FROM chat_messages WHERE wallet_tag = ?",
"DELETE FROM chat_deleted WHERE wallet_tag = ?"}) {
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr) != SQLITE_OK) continue;
sqlite3_bind_text(stmt, 1, wallet_tag_.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
tombstones_.clear();
}
bool ChatDatabase::deleteMessages(const std::vector<ChatMessage>& messages, bool tombstone)
{
if (!key_ready_ || !ensureOpen()) return false;
if (messages.empty()) return true;
if (!exec("BEGIN")) return false;
bool ok = true;
for (const auto& m : messages) {
const std::string dedup = dedupHash(m.txid, m.payload_position);
sqlite3_stmt* del = nullptr;
if (sqlite3_prepare_v2(db_, "DELETE FROM chat_messages WHERE wallet_tag = ? AND dedup_hash = ?",
-1, &del, nullptr) == SQLITE_OK) {
sqlite3_bind_text(del, 1, wallet_tag_.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(del, 2, dedup.c_str(), -1, SQLITE_TRANSIENT);
if (sqlite3_step(del) != SQLITE_DONE) ok = false;
sqlite3_finalize(del);
} else {
ok = false;
}
if (tombstone) {
sqlite3_stmt* ins = nullptr;
if (sqlite3_prepare_v2(db_,
"INSERT OR IGNORE INTO chat_deleted (wallet_tag, dedup_hash) VALUES (?, ?)",
-1, &ins, nullptr) == SQLITE_OK) {
sqlite3_bind_text(ins, 1, wallet_tag_.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ins, 2, dedup.c_str(), -1, SQLITE_TRANSIENT);
if (sqlite3_step(ins) != SQLITE_DONE) ok = false;
sqlite3_finalize(ins);
} else {
ok = false;
}
}
}
if (!exec(ok ? "COMMIT" : "ROLLBACK")) ok = false;
// Only reflect the tombstones in the in-memory cache once they are durably committed.
if (ok && tombstone)
for (const auto& m : messages) tombstones_.insert(dedupHash(m.txid, m.payload_position));
return ok;
}
bool ChatDatabase::isTombstoned(const ChatMessage& message) const
{
if (!key_ready_ || tombstones_.empty()) return false;
return tombstones_.count(dedupHash(message.txid, message.payload_position)) > 0;
}
void ChatDatabase::loadTombstones()
{
tombstones_.clear();
if (!key_ready_ || !ensureOpen()) return;
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(db_, "DELETE FROM chat_messages WHERE wallet_tag = ?", -1, &stmt, nullptr)
!= SQLITE_OK) {
if (sqlite3_prepare_v2(db_, "SELECT dedup_hash FROM chat_deleted WHERE wallet_tag = ?",
-1, &stmt, nullptr) != SQLITE_OK) {
return;
}
sqlite3_bind_text(stmt, 1, wallet_tag_.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_step(stmt);
while (sqlite3_step(stmt) == SQLITE_ROW) {
const auto* h = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
if (h) tombstones_.insert(h);
}
sqlite3_finalize(stmt);
}
@@ -260,11 +329,18 @@ bool ChatDatabase::exec(const char* sql)
bool ChatDatabase::createSchema()
{
return exec("CREATE TABLE IF NOT EXISTS chat_messages ("
if (!exec("CREATE TABLE IF NOT EXISTS chat_messages ("
"wallet_tag TEXT NOT NULL, "
"dedup_hash TEXT NOT NULL, "
"nonce BLOB NOT NULL, "
"payload BLOB NOT NULL, "
"PRIMARY KEY (wallet_tag, dedup_hash))"))
return false;
// Tombstones for locally-deleted messages (dedup_hash only — the same keyed, non-revealing hash the
// message rows use). A chain re-scan checks this so a deleted message never re-imports.
return exec("CREATE TABLE IF NOT EXISTS chat_deleted ("
"wallet_tag TEXT NOT NULL, "
"dedup_hash TEXT NOT NULL, "
"nonce BLOB NOT NULL, "
"payload BLOB NOT NULL, "
"PRIMARY KEY (wallet_tag, dedup_hash))");
}
+14
View File
@@ -16,6 +16,7 @@
#include <array>
#include <cstddef>
#include <string>
#include <unordered_set>
#include <vector>
struct sqlite3;
@@ -54,8 +55,20 @@ public:
void clearWallet(); // delete the unlocked wallet's rows
// Per-conversation local delete. Removes the given messages' rows; when `tombstone` is true it also
// records their (txid,position) dedup keys so a chain re-scan never re-imports them — this backs the
// "delete, but a NEW message revives the thread" path. With `tombstone` false the rows are simply
// removed (used by "delete & block", where a settings-level cid block suppresses re-import until the
// user unblocks, at which point the history re-imports from chain). Atomic; no-op while locked.
bool deleteMessages(const std::vector<ChatMessage>& messages, bool tombstone);
// True if this message's (txid,position) was locally deleted with a tombstone. Checked against an
// in-memory cache loaded on unlock — O(1), no SQL. False while locked.
bool isTombstoned(const ChatMessage& message) const;
private:
bool ensureOpen();
void loadTombstones(); // populate tombstones_ from chat_deleted for the unlocked wallet
bool exec(const char* sql);
bool createSchema();
std::string dedupHash(const std::string& txid, std::size_t position) const;
@@ -74,6 +87,7 @@ private:
std::array<unsigned char, 32> key_{}; // AEAD storage key (seed-derived)
std::string wallet_tag_; // seed-derived row partition (a keyed hash, hex)
bool key_ready_ = false;
std::unordered_set<std::string> tombstones_; // dedup_hash cache of locally-deleted messages
};
} // namespace dragonx::chat
+29
View File
@@ -28,6 +28,10 @@ int ChatService::ingest(const std::vector<HushChatTransactionMetadata>& metadata
std::int64_t fallbackTimestamp,
std::vector<std::string>* newIncomingCids) {
if (!has_identity_) return 0;
// Persistence is attached but not unlocked (e.g. the DB failed to open with the seed): we can't
// consult tombstones, so ingesting now would resurface locally-deleted messages into the store.
// Skip until the DB is usable — chat is degraded anyway without its store.
if (db_ && !db_->hasKey()) return 0;
const std::string myPubKey = chatIdentityPublicKeyHex(identity_);
@@ -62,6 +66,13 @@ int ChatService::ingest(const std::vector<HushChatTransactionMetadata>& metadata
}
message.payload_position = meta.payload_position;
// Suppress locally-removed conversations before the (relatively costly) decrypt. A blocked cid
// is dropped outright (old + future messages) until unblocked; a tombstoned (txid,position) was
// deleted with "revive on new message", so only that exact message is skipped — a new message
// in the same conversation has a different txid and flows through normally.
if (blocked_pred_ && blocked_pred_(message.conversation_id)) continue;
if (db_ && db_->isTombstoned(message)) continue;
if (meta.type == HushChatHeaderType::ContactRequest) {
message.kind = ChatMessageKind::ContactRequest;
message.body = meta.payload_memo; // plaintext request text
@@ -92,10 +103,28 @@ int ChatService::ingest(const std::vector<HushChatTransactionMetadata>& metadata
void ChatService::loadFromDatabase() {
if (!db_) return;
for (const auto& message : db_->load()) {
// Never surface a blocked conversation, even if a prior "delete & block" failed to remove its
// rows (defense-in-depth): the ingest guard already drops live scans, this covers the reload path.
if (blocked_pred_ && blocked_pred_(message.conversation_id)) continue;
store_.append(message);
}
}
bool ChatService::deleteConversation(const std::string& conversationId, bool block) {
// Delete the persisted rows FIRST and only mutate the in-memory view if that succeeds. Doing it the
// other way round means a failed DB write (disk full / locked) would empty the store while the rows
// survive — and on the next reload the conversation silently reappears with no tombstone.
// Revive-on-new-message => tombstone the removed rows so a re-scan won't re-import them.
// Block => remove the rows without a tombstone; the caller's blocked predicate suppresses re-import
// until unblocked, at which point the conversation re-imports from chain.
if (db_) {
std::vector<ChatMessage> msgs = store_.conversation(conversationId); // snapshot (copy)
if (!db_->deleteMessages(msgs, /*tombstone=*/!block)) return false;
}
store_.eraseConversation(conversationId);
return true;
}
std::string ChatService::identityPublicKeyHex() const {
if (!has_identity_) return {};
return chatIdentityPublicKeyHex(identity_);
+15
View File
@@ -11,6 +11,7 @@
#include "chat_store.h"
#include <cstdint>
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>
@@ -55,6 +56,19 @@ public:
// the seed-derived key) into the in-memory store. No-op without an unlocked database.
void loadFromDatabase();
// Set a predicate returning true for a BLOCKED conversation id. ingest() drops those messages
// entirely (they are never stored or persisted) until the predicate stops returning true — this is
// how "delete & block" suppresses old and future messages. Typically wired to Settings::isChatBlocked.
void setBlockedPredicate(std::function<bool(const std::string&)> pred) { blocked_pred_ = std::move(pred); }
// Locally delete a conversation: remove its messages from the store and the database. When `block`
// is false, the removed messages are tombstoned so a chain re-scan won't re-import them, but a
// genuinely NEW message (new txid) revives the thread. When `block` is true, the rows are removed
// WITHOUT a tombstone (the caller also records the cid as blocked via the predicate above); unblocking
// later lets the conversation re-import from chain. Returns false (leaving the store untouched) if the
// persisted rows couldn't be removed, so the caller can avoid a store/DB divergence.
bool deleteConversation(const std::string& conversationId, bool block);
// --- Outgoing (compose) ---
// My chat public key (hex), or "" without an identity — goes in an outgoing header's "p".
std::string identityPublicKeyHex() const;
@@ -90,6 +104,7 @@ private:
bool has_identity_ = false;
ChatStore store_;
ChatDatabase* db_ = nullptr; // optional; not owned
std::function<bool(const std::string&)> blocked_pred_; // true => cid is blocked (drop its messages)
};
} // namespace dragonx::chat
+31
View File
@@ -13,6 +13,7 @@ std::string ChatStore::dedupKey(const ChatMessage& message) {
bool ChatStore::append(const ChatMessage& message) {
if (!seen_.insert(dedupKey(message)).second) return false;
messages_.push_back(message);
++revision_;
return true;
}
@@ -38,12 +39,24 @@ const ChatMessage* ChatStore::updateDelivery(const std::string& txid, ChatDelive
for (auto& message : messages_) {
if (message.txid == txid) {
message.delivery = delivery;
++revision_;
return &message;
}
}
return nullptr;
}
int ChatStore::countUnread(const std::function<bool(const std::string&)>& excluded,
const std::function<std::int64_t(const std::string&)>& seenFor) const {
int unread = 0;
for (const auto& m : messages_) {
if (m.direction != ChatDirection::Incoming) continue;
if (excluded && excluded(m.conversation_id)) continue;
if (m.timestamp > seenFor(m.conversation_id)) ++unread;
}
return unread;
}
std::vector<std::string> ChatStore::conversationIds() const {
std::vector<std::string> ids;
std::unordered_set<std::string> seenIds;
@@ -53,9 +66,27 @@ std::vector<std::string> ChatStore::conversationIds() const {
return ids;
}
std::vector<ChatMessage> ChatStore::eraseConversation(const std::string& conversationId) {
std::vector<ChatMessage> removed;
std::vector<ChatMessage> kept;
kept.reserve(messages_.size());
for (auto& m : messages_) {
if (m.conversation_id == conversationId) {
seen_.erase(dedupKey(m));
removed.push_back(std::move(m));
} else {
kept.push_back(std::move(m));
}
}
messages_.swap(kept);
if (!removed.empty()) ++revision_;
return removed;
}
void ChatStore::clear() {
messages_.clear();
seen_.clear();
++revision_;
}
} // namespace dragonx::chat
+19
View File
@@ -5,6 +5,8 @@
#include "chat_message.h"
#include <cstdint>
#include <functional>
#include <string>
#include <unordered_set>
#include <vector>
@@ -38,15 +40,32 @@ public:
return out;
}
// Remove every message in a conversation from the in-memory view and return the removed messages
// (so the caller can delete/tombstone their persisted rows). Re-appends are prevented by the ingest
// guard (blocked-cid predicate / DB tombstone), not here.
std::vector<ChatMessage> eraseConversation(const std::string& conversationId);
std::size_t size() const { return messages_.size(); }
bool empty() const { return messages_.empty(); }
void clear();
// Monotonic counter bumped on every mutation (append / updateDelivery change / eraseConversation /
// clear). Callers memoize expensive per-frame reads (conversation-list build, unread count) against it
// so they only rebuild when the store actually changed.
std::uint64_t revision() const { return revision_; }
// Count unread incoming messages in a SINGLE pass over the store: an incoming message counts when its
// cid is not `excluded` and its timestamp is newer than `seenFor(cid)`. Avoids the per-conversation
// copy+sort that conversation() does — the count doesn't need ordering.
int countUnread(const std::function<bool(const std::string&)>& excluded,
const std::function<std::int64_t(const std::string&)>& seenFor) const;
private:
static std::string dedupKey(const ChatMessage& message);
std::vector<ChatMessage> messages_;
std::unordered_set<std::string> seen_;
std::uint64_t revision_ = 0;
};
} // namespace dragonx::chat