From df31a8da7143dc995294c64e855704dd315beb18 Mon Sep 17 00:00:00 2001
From: Sebastião Guerra <sebastiao.luiz.guerra@gmail.com>
Date: Sun, 30 Aug 2026 12:07:38 -0300
Subject: KMail: clean up accounts when removing them
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Remove deleted accounts from the pending and active mail-check queues.

Disconnect an active mail check and balance the filter manager reference
before deleting the account, then continue processing any remaining checks.

Deleting the account also removes its periodic mail-check timer, preventing
a removed account from being checked again.

This fixes the account removal issue reported in TDE/tdepim#184.

Signed-off-by: Sebastião Guerra <sebastiao.luiz.guerra@gmail.com>
---
 kmail/accountmanager.cpp | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)

diff --git a/kmail/accountmanager.cpp b/kmail/accountmanager.cpp
index 8e4565c8..c4f0f715 100644
--- a/kmail/accountmanager.cpp
+++ b/kmail/accountmanager.cpp
@@ -327,10 +327,32 @@ KMAccount* AccountManager::next()
 //-----------------------------------------------------------------------------
 bool AccountManager::remove( KMAccount* acct )
 {
-  if( !acct )
+  if( !acct || mAcctList.find( acct ) == mAcctList.end() )
     return false;
+
+  // Stop automatic checks and remove any pending references before deleting
+  // the account. Otherwise queued or periodic checks may access it after the
+  // account has been removed from the manager.
+  acct->deinstallTimer();
+  mAcctTodo.remove( acct );
+
+  const bool wasChecking = mAcctChecking.find( acct ) != mAcctChecking.end();
+  if ( wasChecking ) {
+    disconnect( acct, TQ_SIGNAL( finishedCheck( bool, CheckStatus ) ),
+                this, TQ_SLOT( processNextCheck( bool ) ) );
+    mAcctChecking.remove( acct );
+    acct->setCheckingMail( false );
+  }
+
   mAcctList.remove( acct );
   emit accountRemoved( acct );
+  delete acct;
+
+  if ( wasChecking ) {
+    kmkernel->filterMgr()->deref();
+    processNextCheck( false );
+  }
+
   return true;
 }
 
-- 
cgit v1.2.3

