fix: deleting a folder with its chats leaves their sub-agent and timer conversations behind (#35055)

When a chat in a folder had handed work to a sub-agent or set a timer, deleting the folder with its contents removed the chat but kept the conversation that sub-agent or timer ran in. Admin analytics went on counting its messages and tokens, listed it as a session and returned its text. Deleting the folder now removes the stored conversations along with their chats, the same way deleting a single chat or all chats already removes them.

Fixes #35053
This commit is contained in:
Classic298 authored and GitHub committed 2026-11-25 13:13:06 +04:00
1 parent b0d5c67f76
commit 1fcfc8a5cd
1 file changed
+14 -7
+14 -7
View File
@@ -2981,7 +2981,18 @@ class ChatTable:
try:
async with get_async_db_context(db) as session:
chat_ids_stmt = select(Chat.id).filter_by(user_id=user_id, folder_id=folder_id)
folder_chat_ids_stmt = select(Chat.id).filter_by(user_id=user_id, folder_id=folder_id)
# Internal child chats sit outside the folder but go with their parent.
chat_ids_stmt = select(Chat.id).where(
Chat.user_id == user_id,
or_(
Chat.folder_id == folder_id,
and_(
Chat.meta['internal'].as_boolean().is_(True),
Chat.meta['parent_chat_id'].as_string().in_(folder_chat_ids_stmt),
),
),
)
await session.execute(
update(AutomationRun).filter(AutomationRun.chat_id.in_(chat_ids_stmt)).values(chat_id=None)
)
@@ -2994,12 +3005,8 @@ class ChatTable:
'chat', select(Chat.id).filter_by(user_id=user_id, folder_id=folder_id), db=session
)
)
await session.execute(
delete(ChatViewState).where(
ChatViewState.chat_id.in_(select(Chat.id).filter_by(user_id=user_id, folder_id=folder_id))
)
)
await session.execute(delete(Chat).filter_by(user_id=user_id, folder_id=folder_id))
await session.execute(delete(ChatViewState).where(ChatViewState.chat_id.in_(chat_ids_stmt)))
await session.execute(delete(Chat).where(Chat.id.in_(chat_ids_stmt)))
await session.commit()
await emit_changes(recipients)