diff --git a/astrbot/core/db/__init__.py b/astrbot/core/db/__init__.py index b9e7e095fa..60859c529a 100644 --- a/astrbot/core/db/__init__.py +++ b/astrbot/core/db/__init__.py @@ -910,6 +910,25 @@ async def get_umo_aliases(self, umos: list[str] | None = None) -> list[UmoAlias] """Get alias metadata, optionally restricted to the given UMO list.""" ... + @abc.abstractmethod + async def delete_umo_metadata_if_unreferenced(self, umo: str) -> dict: + """Delete alias and sender metadata for a UMO without conversations. + + The reference check and the deletions run as conditional statements in + a single transaction, so metadata is not deleted while a committed + conversation still references the UMO. + + Args: + umo: Unified message origin whose orphaned metadata should be deleted. + + Returns: + Mapping with ``alias_deleted`` (whether an alias row was removed), + ``senders_deleted`` (number of sender rows removed) and + ``retained`` (True when a conversation still references the UMO and + nothing was deleted). + """ + ... + # ==== # UMO Sender Management # ==== diff --git a/astrbot/core/db/sqlite.py b/astrbot/core/db/sqlite.py index edbbb3e7cd..7f42a41f19 100644 --- a/astrbot/core/db/sqlite.py +++ b/astrbot/core/db/sqlite.py @@ -2484,6 +2484,68 @@ async def get_umo_aliases(self, umos: list[str] | None = None) -> list[UmoAlias] result = await session.execute(query) return list(result.scalars().all()) + async def delete_umo_metadata_if_unreferenced(self, umo: str) -> dict: + """Delete alias and sender metadata for a UMO without conversations. + + Both deletions carry the NOT EXISTS guard in the statement itself, so + within a single process the check and the removal cannot interleave + with a concurrently committed conversation insert. + + Args: + umo: Unified message origin whose orphaned metadata should be deleted. + + Returns: + Mapping with ``alias_deleted``, ``senders_deleted`` and + ``retained`` (True when metadata still exists for the UMO but a + conversation references it, so nothing was deleted). + """ + referenced = select(ConversationV3.id).where( + col(ConversationV3.umo) == umo + ) + + async with self.get_db() as session: + session: AsyncSession + async with session.begin(): + alias_result = await session.execute( + delete(UmoAlias) + .where(col(UmoAlias.umo) == umo) + .where(~referenced.exists()) + ) + senders_result = await session.execute( + delete(UmoSender) + .where(col(UmoSender.umo) == umo) + .where(~referenced.exists()) + ) + alias_deleted = alias_result.rowcount > 0 + senders_deleted = int(senders_result.rowcount or 0) + retained = False + if not alias_deleted and not senders_deleted: + # Distinguish "kept because still referenced" from + # "there was nothing to clean up". + has_reference = bool( + (await session.execute(select(referenced.exists()))).scalar() + ) + if has_reference: + retained = await self._umo_metadata_exists(session, umo) + return { + "alias_deleted": alias_deleted, + "senders_deleted": senders_deleted, + "retained": retained, + } + + @staticmethod + async def _umo_metadata_exists(session: AsyncSession, umo: str) -> bool: + """Return whether any alias or sender row exists for the UMO.""" + alias_row = await session.execute( + select(UmoAlias.id).where(col(UmoAlias.umo) == umo).limit(1) + ) + if alias_row.first() is not None: + return True + sender_row = await session.execute( + select(UmoSender.id).where(col(UmoSender.umo) == umo).limit(1) + ) + return sender_row.first() is not None + # ==== # UMO Sender Management # ==== diff --git a/astrbot/dashboard/api/conversations.py b/astrbot/dashboard/api/conversations.py index f75003d457..9e31a1e06c 100644 --- a/astrbot/dashboard/api/conversations.py +++ b/astrbot/dashboard/api/conversations.py @@ -236,12 +236,17 @@ async def update_conversation( async def delete_conversation( conversation_id: str, user_id: str = Query(...), + cleanup_metadata: bool = Query(default=False), _auth: AuthContext = Depends(require_data_scope), service: ConversationService = Depends(get_service), ): return await _run( lambda: service.delete_conversation( - {"user_id": user_id, "cid": conversation_id} + { + "user_id": user_id, + "cid": conversation_id, + "cleanup_metadata": cleanup_metadata, + } ) ) diff --git a/astrbot/dashboard/schemas.py b/astrbot/dashboard/schemas.py index 747dbb7c2a..07e5969425 100644 --- a/astrbot/dashboard/schemas.py +++ b/astrbot/dashboard/schemas.py @@ -449,6 +449,7 @@ class ConversationMessagesReplaceRequest(OpenModel): class ConversationBatchDeleteRequest(BaseModel): conversations: list[ConversationRef] + cleanup_metadata: bool = False class ConversationExportRequest(BaseModel): diff --git a/astrbot/dashboard/services/conversation_service.py b/astrbot/dashboard/services/conversation_service.py index 117bc407c0..515e15143a 100644 --- a/astrbot/dashboard/services/conversation_service.py +++ b/astrbot/dashboard/services/conversation_service.py @@ -191,15 +191,33 @@ async def update_conversation(self, data: object) -> dict: async def delete_conversation(self, data: object) -> dict: payload = self._payload(data) + cleanup_metadata = bool(payload.get("cleanup_metadata", False)) if "conversations" in payload: - return await self._delete_conversations(payload.get("conversations", [])) + return await self._delete_conversations( + payload.get("conversations", []), + cleanup_metadata=cleanup_metadata, + ) user_id, cid = self._require_user_and_cid(payload) await self.conv_mgr.delete_conversation( unified_msg_origin=user_id, conversation_id=cid, ) - return {"message": "对话删除成功"} + result = {"message": "对话删除成功"} + if cleanup_metadata: + try: + result["metadata_cleanup"] = await self._cleanup_orphaned_metadata( + [user_id] + ) + except Exception as exc: + logger.warning(f"清理会话元数据失败: {exc!s}", exc_info=True) + result["metadata_cleanup"] = { + "deleted_aliases": 0, + "deleted_senders": 0, + "retained_umos": [], + "error": str(exc), + } + return result async def update_history(self, data: object) -> dict: payload = self._payload(data) @@ -291,12 +309,15 @@ async def export_conversations(self, data: object) -> ConversationExport: filename=f"astrbot_conversations_export_{timestamp}.jsonl", ) - async def _delete_conversations(self, conversations: object) -> dict: + async def _delete_conversations( + self, conversations: object, cleanup_metadata: bool = False + ) -> dict: if not isinstance(conversations, list) or not conversations: raise ConversationServiceError("批量删除时conversations参数不能为空") deleted_count = 0 failed_items = [] + deleted_umos: set[str] = set() for conv in conversations: if not isinstance(conv, dict): @@ -315,6 +336,7 @@ async def _delete_conversations(self, conversations: object) -> dict: conversation_id=cid, ) deleted_count += 1 + deleted_umos.add(user_id) except Exception as exc: failed_items.append(f"user_id:{user_id}, cid:{cid} - {exc!s}") @@ -322,12 +344,58 @@ async def _delete_conversations(self, conversations: object) -> dict: if failed_items: message += f",失败 {len(failed_items)} 个" - return { + result = { "message": message, "deleted_count": deleted_count, "failed_count": len(failed_items), "failed_items": failed_items, } + if cleanup_metadata: + try: + result["metadata_cleanup"] = await self._cleanup_orphaned_metadata( + sorted(deleted_umos) + ) + except Exception as exc: + logger.warning(f"清理会话元数据失败: {exc!s}", exc_info=True) + result["metadata_cleanup"] = { + "deleted_aliases": 0, + "deleted_senders": 0, + "retained_umos": [], + "error": str(exc), + } + return result + + async def _cleanup_orphaned_metadata(self, umos: list[str]) -> dict: + """Delete UMO alias and sender metadata left without any conversation. + + The deletion is conditional in the database layer, so a UMO that still + owns other conversations keeps its display names. + + Args: + umos: Unified message origins of the conversations just deleted. + + Returns: + Mapping with ``deleted_aliases``, ``deleted_senders`` and + ``retained_umos`` (UMOs kept because other conversations reference + them). + """ + deleted_aliases = 0 + deleted_senders = 0 + retained_umos: list[str] = [] + + for umo in dict.fromkeys(umos): + outcome = await self.db_helper.delete_umo_metadata_if_unreferenced(umo) + if outcome["alias_deleted"]: + deleted_aliases += 1 + deleted_senders += outcome["senders_deleted"] + if outcome["retained"]: + retained_umos.append(umo) + + return { + "deleted_aliases": deleted_aliases, + "deleted_senders": deleted_senders, + "retained_umos": retained_umos, + } @staticmethod def _webchat_session_id(user_id: str | None) -> str: diff --git a/changelogs/unreleased.md b/changelogs/unreleased.md index 7d59c95e0c..0dfb70625c 100644 --- a/changelogs/unreleased.md +++ b/changelogs/unreleased.md @@ -3,6 +3,7 @@ - QQ Official: failed image uploads no longer log base64 payloads, avoiding dashboard freezes from oversized log entries. Retry attempts decrease from five to three, with one summary warning. - Session waiters now wake their timeout task immediately when completed early, avoiding stale asyncio tasks for the remainder of the configured timeout. +- Add an optional cleanup checkbox to the single and batch conversation deletion dialogs in Data & Logs → Conversations. When selected, alias and sender metadata is removed only for sessions with no remaining conversations; off by default, and metadata is retained while other conversations still reference the session. Expose the same choice through `cleanup_metadata` on the delete APIs. - 「插件 → 管理行为 → 函数工具」现在只列出插件工具。Agent 运行时工具由配置文件的 AI 功能设置控制,MCP 工具可在「插件 → MCP」查看。 - Extensions → Handlers → Function Tools now lists plugin tools. Configure Agent runtime tools in the profile's AI capability settings and view MCP tools under Extensions → MCP Servers. diff --git a/dashboard/src/api/generated/openapi-v1/types.gen.ts b/dashboard/src/api/generated/openapi-v1/types.gen.ts index 2f6b53501a..d9e368f302 100644 --- a/dashboard/src/api/generated/openapi-v1/types.gen.ts +++ b/dashboard/src/api/generated/openapi-v1/types.gen.ts @@ -239,6 +239,10 @@ export type ConfigRouteUpsertRequest = { export type ConversationBatchDeleteRequest = { conversations: Array; + /** + * Delete alias and sender metadata for the sessions when no other conversation still references them. + */ + cleanup_metadata?: boolean; }; export type ConversationExportRequest = { @@ -3503,6 +3507,10 @@ export type DeleteConversationData = { conversation_id: string; }; query: { + /** + * Delete alias and sender metadata for the session when no other conversation still references it. + */ + cleanup_metadata?: boolean; user_id: string; }; }; diff --git a/dashboard/src/api/v1.ts b/dashboard/src/api/v1.ts index 8863c90400..c60fefde62 100644 --- a/dashboard/src/api/v1.ts +++ b/dashboard/src/api/v1.ts @@ -1803,11 +1803,11 @@ export const conversationApi = { }), ); }, - delete(userId: string, cid: string) { + delete(userId: string, cid: string, cleanupMetadata = false) { return typed( openApiV1.deleteConversation({ path: { conversation_id: cid }, - query: { user_id: userId }, + query: { user_id: userId, cleanup_metadata: cleanupMetadata }, }), ); }, diff --git a/dashboard/src/components/ConfirmDialog.vue b/dashboard/src/components/ConfirmDialog.vue index ab477b9e13..8fe5f09427 100644 --- a/dashboard/src/components/ConfirmDialog.vue +++ b/dashboard/src/components/ConfirmDialog.vue @@ -2,7 +2,18 @@ {{ title }} - {{ message }} + + {{ message }} + + {{ t('core.common.dialog.cancelButton') }} @@ -21,11 +32,15 @@ const { t } = useI18n(); const isOpen = ref(false); const title = ref(""); const message = ref(""); +const checkboxOptions = ref(null); +const checkboxChecked = ref(false); let resolvePromise = null; // ✅ 确保 Promise 句柄可用 const open = (options) => { title.value = options.title || t('core.common.dialog.confirmTitle'); message.value = options.message || t('core.common.dialog.confirmMessage'); + checkboxOptions.value = options.checkbox || null; + checkboxChecked.value = false; isOpen.value = true; return new Promise((resolve) => { @@ -35,12 +50,27 @@ const open = (options) => { const handleConfirm = () => { isOpen.value = false; - if (resolvePromise) resolvePromise(true); // ✅ 解析 Promise + if (resolvePromise) { + // With a checkbox the caller needs the checked state back as well. + resolvePromise( + checkboxOptions.value + ? { confirmed: true, checked: checkboxChecked.value } + : true + ); + resolvePromise = null; + } }; const handleCancel = () => { isOpen.value = false; - if (resolvePromise) resolvePromise(false); // ✅ 解析 Promise + if (resolvePromise) { + resolvePromise( + checkboxOptions.value + ? { confirmed: false, checked: false } + : false + ); + resolvePromise = null; + } }; defineExpose({ open }); // ✅ 确保 `confirmPlugin.ts` 可以访问 `open` diff --git a/dashboard/src/i18n/locales/en-US/features/conversation.json b/dashboard/src/i18n/locales/en-US/features/conversation.json index 49ec8547db..0b2b228a14 100644 --- a/dashboard/src/i18n/locales/en-US/features/conversation.json +++ b/dashboard/src/i18n/locales/en-US/features/conversation.json @@ -74,7 +74,9 @@ "title": "Confirm Delete", "message": "Are you sure you want to delete conversation {title}? This action cannot be undone.", "cancel": "Cancel", - "confirm": "Delete" + "confirm": "Delete", + "cleanupMetadata": "Also delete session metadata (aliases, etc.)", + "cleanupMetadataHint": "Only removes metadata when the session has no remaining conversations. Off by default." }, "batchDelete": { "title": "Batch Delete Confirmation", @@ -82,7 +84,9 @@ "andMore": "and {count} more", "cancel": "Cancel", "confirm": "Batch Delete", - "warning": "Warning: This action cannot be undone!" + "warning": "Warning: This action cannot be undone!", + "cleanupMetadata": "Also delete session metadata without remaining conversations (aliases, etc.)", + "cleanupMetadataHint": "Metadata is kept when the session still has other conversations." } }, "messages": { diff --git a/dashboard/src/i18n/locales/ja-JP/features/conversation.json b/dashboard/src/i18n/locales/ja-JP/features/conversation.json index 9d4c883011..181cf9b656 100644 --- a/dashboard/src/i18n/locales/ja-JP/features/conversation.json +++ b/dashboard/src/i18n/locales/ja-JP/features/conversation.json @@ -74,7 +74,9 @@ "title": "削除の確認", "message": "会話 {title} を削除してもよろしいですか?この操作は元に戻せません。", "cancel": "キャンセル", - "confirm": "削除" + "confirm": "削除", + "cleanupMetadata": "セッションメタデータ(別名など)も削除する", + "cleanupMetadataHint": "他の会話が残っていない場合のみ削除します。デフォルトはオフです。" }, "batchDelete": { "title": "一括削除の確認", @@ -82,7 +84,9 @@ "andMore": "ほか {count} 件", "cancel": "キャンセル", "confirm": "一括削除", - "warning": "警告:この操作は元に戻せません。" + "warning": "警告:この操作は元に戻せません。", + "cleanupMetadata": "会話が残っていないセッションメタデータも削除する(別名など)", + "cleanupMetadataHint": "他の会話が残っているセッションのメタデータは保持されます。" } }, "messages": { diff --git a/dashboard/src/i18n/locales/ru-RU/features/conversation.json b/dashboard/src/i18n/locales/ru-RU/features/conversation.json index fcb47ae8fc..43a68edbb5 100644 --- a/dashboard/src/i18n/locales/ru-RU/features/conversation.json +++ b/dashboard/src/i18n/locales/ru-RU/features/conversation.json @@ -74,7 +74,9 @@ "title": "Подтверждение удаления", "message": "Вы уверены, что хотите удалить диалог «{title}»? Это действие необратимо.", "cancel": "Отмена", - "confirm": "Удалить" + "confirm": "Удалить", + "cleanupMetadata": "Также удалить метаданные сессии (псевдонимы и т. п.)", + "cleanupMetadataHint": "Удаляются только если у сессии не осталось других диалогов. По умолчанию выключено." }, "batchDelete": { "title": "Массовое удаление", @@ -82,7 +84,9 @@ "andMore": "и еще {count}", "cancel": "Отмена", "confirm": "Удалить всё", - "warning": "Внимание: удаление нельзя будет отменить!" + "warning": "Внимание: удаление нельзя будет отменить!", + "cleanupMetadata": "Также удалить метаданные сессий без оставшихся диалогов (псевдонимы и т. п.)", + "cleanupMetadataHint": "Метаданные сохраняются, если у сессии остались другие диалоги." } }, "messages": { diff --git a/dashboard/src/i18n/locales/zh-CN/features/conversation.json b/dashboard/src/i18n/locales/zh-CN/features/conversation.json index 404a160508..67550d152d 100644 --- a/dashboard/src/i18n/locales/zh-CN/features/conversation.json +++ b/dashboard/src/i18n/locales/zh-CN/features/conversation.json @@ -74,7 +74,9 @@ "title": "确认删除", "message": "确定要删除对话 {title} 吗?此操作不可恢复。", "cancel": "取消", - "confirm": "删除" + "confirm": "删除", + "cleanupMetadata": "同时清理会话元数据(别名等)", + "cleanupMetadataHint": "仅当该会话已没有其他对话时才会清理,默认不勾选。" }, "batchDelete": { "title": "批量删除确认", @@ -82,7 +84,9 @@ "andMore": "等 {count} 个", "cancel": "取消", "confirm": "批量删除", - "warning": "警告:此操作不可撤销!" + "warning": "警告:此操作不可撤销!", + "cleanupMetadata": "同时清理无对话引用的会话元数据(别名等)", + "cleanupMetadataHint": "仅清理删除后已无任何对话的会话元数据,仍有其他对话的会话保留名称。" } }, "messages": { diff --git a/dashboard/src/plugins/confirmPlugin.ts b/dashboard/src/plugins/confirmPlugin.ts index 94e126e94e..f02589dcb4 100644 --- a/dashboard/src/plugins/confirmPlugin.ts +++ b/dashboard/src/plugins/confirmPlugin.ts @@ -11,7 +11,11 @@ export default { vNode.appContext = app._context; render(vNode, mountNode); - const confirm = (options: { title?: string; message?: string }) => { + const confirm = (options: { + title?: string; + message?: string; + checkbox?: { label: string; hint?: string }; + }) => { return new Promise((resolve) => { vNode.component?.exposed?.open(options).then(resolve); // ✅ 确保返回 `Promise` }); diff --git a/dashboard/src/utils/confirmDialog.ts b/dashboard/src/utils/confirmDialog.ts index 494f81e0e6..a0281b5dc8 100644 --- a/dashboard/src/utils/confirmDialog.ts +++ b/dashboard/src/utils/confirmDialog.ts @@ -1,11 +1,24 @@ import { inject } from 'vue' +export type ConfirmDialogCheckbox = { + label: string + hint?: string +} + +export type ConfirmDialogResult = { + confirmed: boolean + checked: boolean +} + export type ConfirmDialogOptions = { title?: string message?: string + checkbox?: ConfirmDialogCheckbox } -export type ConfirmDialogHandler = (options: ConfirmDialogOptions) => Promise +export type ConfirmDialogHandler = ( + options: ConfirmDialogOptions +) => Promise export type ConfirmDialogCandidate = ConfirmDialogHandler | null | undefined @@ -21,7 +34,8 @@ export async function askForConfirmation( if (confirmDialog) { try { - return await confirmDialog({ message }) + const result = await confirmDialog({ message }) + return typeof result === 'object' ? result.confirmed : result } catch { return false } @@ -29,3 +43,29 @@ export async function askForConfirmation( return window.confirm(message) } + +export async function askForConfirmationWithCheckbox( + message: string, + options: { + candidate?: ConfirmDialogCandidate + checkbox?: ConfirmDialogCheckbox + } = {} +): Promise { + const confirmDialog = options.candidate ?? undefined + + if (confirmDialog) { + try { + const result = await confirmDialog({ message, checkbox: options.checkbox }) + if (typeof result === 'object') { + return result + } + // Handler without checkbox support: treat it as a plain confirmation. + return { confirmed: result, checked: false } + } catch { + return { confirmed: false, checked: false } + } + } + + // Native confirm cannot render a checkbox; stay on the safe side. + return { confirmed: window.confirm(message), checked: false } +} diff --git a/dashboard/src/views/ConversationPage.vue b/dashboard/src/views/ConversationPage.vue index cac97657c2..3905a5bf1f 100644 --- a/dashboard/src/views/ConversationPage.vue +++ b/dashboard/src/views/ConversationPage.vue @@ -338,6 +338,10 @@

{{ tm('dialogs.delete.message', { title: selectedConversation?.title || tm('status.noTitle') }) }}

+ +
@@ -380,6 +384,11 @@ {{ tm('dialogs.batchDelete.warning') }} + + + @@ -470,6 +479,8 @@ export default { dialogEdit: false, dialogDelete: false, dialogBatchDelete: false, // 批量删除对话框 + dialogDeleteCleanup: false, // 同时清理无引用的会话元数据 + dialogBatchDeleteCleanup: false, // 选中的对话 selectedConversation: null, @@ -998,6 +1009,7 @@ export default { // 确认删除对话 confirmDeleteConversation(item) { this.selectedConversation = item; + this.dialogDeleteCleanup = false; this.dialogDelete = true; }, @@ -1007,7 +1019,8 @@ export default { try { const response = await conversationApi.delete( this.selectedConversation.user_id, - this.selectedConversation.cid + this.selectedConversation.cid, + this.dialogDeleteCleanup ); if (response.data.status === "ok") { @@ -1047,6 +1060,7 @@ export default { this.showErrorMessage(this.tm('messages.noItemSelected')); return; } + this.dialogBatchDeleteCleanup = false; this.dialogBatchDelete = true; }, @@ -1076,7 +1090,8 @@ export default { })); const response = await conversationApi.batchDelete({ - conversations: conversations + conversations: conversations, + cleanup_metadata: this.dialogBatchDeleteCleanup }); if (response.data.status === "ok") { diff --git a/dashboard/src/views/conversation/ConversationWorkspacePage.vue b/dashboard/src/views/conversation/ConversationWorkspacePage.vue index cfb89553d8..1c04f06c94 100644 --- a/dashboard/src/views/conversation/ConversationWorkspacePage.vue +++ b/dashboard/src/views/conversation/ConversationWorkspacePage.vue @@ -33,7 +33,7 @@ import { useI18n, useModuleI18n } from "@/i18n/composables"; import { useCustomizerStore } from "@/stores/customizer"; import { copyToClipboard } from "@/utils/clipboard"; import { - askForConfirmation as askForConfirmationDialog, + askForConfirmationWithCheckbox as askForConfirmationDialog, useConfirmDialog, } from "@/utils/confirmDialog"; import { getPlatformIcon } from "@/utils/platformUtils"; @@ -594,9 +594,16 @@ async function exportSelected() { async function deleteSelected() { if (!selectedItems.value.length) return; - const confirmed = await askForConfirmationDialog( + + const { confirmed, checked } = await askForConfirmationDialog( tm("dialogs.batchDelete.message", { count: selectedItems.value.length }), - confirmDialog, + { + candidate: confirmDialog, + checkbox: { + label: tm("dialogs.batchDelete.cleanupMetadata"), + hint: tm("dialogs.batchDelete.cleanupMetadataHint"), + }, + }, ); if (!confirmed) return; @@ -609,6 +616,7 @@ async function deleteSelected() { user_id: item.user_id, cid: item.cid, })), + cleanup_metadata: checked, }); if (response.data.status !== "ok") { throw new Error(response.data.message || tm("messages.batchDeleteError")); diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 0a77c3ac94..5d9b78e42b 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -6601,6 +6601,16 @@ "schema": { "type": "string" } + }, + { + "name": "cleanup_metadata", + "in": "query", + "required": false, + "description": "Delete alias and sender metadata for the session when no other conversation still references it.", + "schema": { + "type": "boolean", + "default": false + } } ], "responses": { @@ -8599,6 +8609,11 @@ "items": { "$ref": "#/components/schemas/ConversationRef" } + }, + "cleanup_metadata": { + "type": "boolean", + "default": false, + "description": "Delete alias and sender metadata for the sessions when no other conversation still references them." } }, "additionalProperties": false diff --git a/openspec/openapi-v1.yaml b/openspec/openapi-v1.yaml index 76a2203464..0578f73db8 100644 --- a/openspec/openapi-v1.yaml +++ b/openspec/openapi-v1.yaml @@ -4540,6 +4540,15 @@ paths: required: true schema: type: string + - name: cleanup_metadata + in: query + required: false + description: >- + Delete alias and sender metadata for the session when no other + conversation still references it. + schema: + type: boolean + default: false responses: "200": $ref: "#/components/responses/Ok" @@ -7000,6 +7009,12 @@ components: type: array items: $ref: "#/components/schemas/ConversationRef" + cleanup_metadata: + type: boolean + default: false + description: >- + Delete alias and sender metadata for the sessions when no other + conversation still references them. additionalProperties: false ConversationExportRequest: diff --git a/tests/unit/test_conversation_metadata_cleanup.py b/tests/unit/test_conversation_metadata_cleanup.py new file mode 100644 index 0000000000..0574651e14 --- /dev/null +++ b/tests/unit/test_conversation_metadata_cleanup.py @@ -0,0 +1,394 @@ +"""Tests for UMO metadata cleanup on conversation deletion.""" + +import asyncio +from types import SimpleNamespace + +import pytest + +from astrbot.dashboard.api import conversations as conversations_api +from astrbot.dashboard.schemas import ConversationBatchDeleteRequest +from astrbot.dashboard.services.conversation_service import ConversationService + +UMO = "qq:GroupMessage:1000" +UMO_OTHER = "qq:GroupMessage:2000" + + +async def seed_alias(db, umo: str = UMO) -> None: + await db.upsert_umo_alias( + umo=umo, + creator_sender_id="sender-1", + auto_name="Engineering Group", + user_alias="Backend Room", + ) + + +# ==== +# Database layer +# ==== + + +@pytest.mark.asyncio +async def test_metadata_cleanup_deletes_when_no_conversation_reference(temp_db): + await seed_alias(temp_db) + await temp_db.upsert_umo_sender(UMO, "sender-1", "Alice") + + outcome = await temp_db.delete_umo_metadata_if_unreferenced(UMO) + + assert outcome == { + "alias_deleted": True, + "senders_deleted": 1, + "retained": False, + } + assert await temp_db.get_umo_alias(UMO) is None + senders = await temp_db.get_umo_senders(sender_ids=["sender-1"]) + assert all(sender.umo != UMO for sender, _ in senders) + + +@pytest.mark.asyncio +async def test_metadata_cleanup_retains_when_other_conversation_exists(temp_db): + await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await seed_alias(temp_db) + await temp_db.upsert_umo_sender(UMO, "sender-1", "Alice") + + outcome = await temp_db.delete_umo_metadata_if_unreferenced(UMO) + + assert outcome == { + "alias_deleted": False, + "senders_deleted": 0, + "retained": True, + } + assert await temp_db.get_umo_alias(UMO) is not None + + +@pytest.mark.asyncio +async def test_metadata_cleanup_handles_missing_alias(temp_db): + outcome = await temp_db.delete_umo_metadata_if_unreferenced(UMO) + + assert outcome == { + "alias_deleted": False, + "senders_deleted": 0, + "retained": False, + } + + +@pytest.mark.asyncio +async def test_metadata_cleanup_only_touches_target_umo(temp_db): + await seed_alias(temp_db) + await seed_alias(temp_db, UMO_OTHER) + await temp_db.create_conversation(user_id=UMO_OTHER, platform_id="qq") + + outcome = await temp_db.delete_umo_metadata_if_unreferenced(UMO) + + assert outcome["alias_deleted"] is True + assert await temp_db.get_umo_alias(UMO) is None + assert await temp_db.get_umo_alias(UMO_OTHER) is not None + + +# ==== +# Service layer +# ==== + + +class FakeConversationManager: + """Minimal conversation manager that really deletes rows from temp_db.""" + + def __init__(self, db) -> None: + self.db = db + self.deleted: list[tuple[str, str]] = [] + + async def delete_conversation( + self, unified_msg_origin: str, conversation_id: str | None = None + ) -> None: + self.deleted.append((unified_msg_origin, conversation_id or "")) + await self.db.delete_conversation(cid=conversation_id) + + +def make_service(db): + manager = FakeConversationManager(db) + lifecycle = SimpleNamespace(conversation_manager=manager) + return ConversationService(db_helper=db, core_lifecycle=lifecycle), manager + + +@pytest.mark.asyncio +async def test_service_single_delete_removes_last_conversation_metadata(temp_db): + conversation = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await seed_alias(temp_db) + await temp_db.upsert_umo_sender(UMO, "sender-1", "Alice") + service, _ = make_service(temp_db) + + result = await service.delete_conversation( + { + "user_id": UMO, + "cid": conversation.conversation_id, + "cleanup_metadata": True, + } + ) + + assert result["metadata_cleanup"] == { + "deleted_aliases": 1, + "deleted_senders": 1, + "retained_umos": [], + } + assert await temp_db.get_umo_alias(UMO) is None + + +@pytest.mark.asyncio +async def test_service_single_delete_keeps_metadata_with_other_conversation(temp_db): + first = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await seed_alias(temp_db) + service, _ = make_service(temp_db) + + result = await service.delete_conversation( + { + "user_id": UMO, + "cid": first.conversation_id, + "cleanup_metadata": True, + } + ) + + assert result["metadata_cleanup"]["deleted_aliases"] == 0 + assert result["metadata_cleanup"]["retained_umos"] == [UMO] + assert await temp_db.get_umo_alias(UMO) is not None + + +@pytest.mark.asyncio +async def test_service_default_delete_keeps_metadata(temp_db): + conversation = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await seed_alias(temp_db) + service, _ = make_service(temp_db) + + result = await service.delete_conversation( + {"user_id": UMO, "cid": conversation.conversation_id} + ) + + assert "metadata_cleanup" not in result + assert await temp_db.get_umo_alias(UMO) is not None + + +@pytest.mark.asyncio +async def test_service_batch_delete_cleans_after_all_cids_removed(temp_db): + first = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + second = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await seed_alias(temp_db) + service, _ = make_service(temp_db) + + result = await service.delete_conversation( + { + "conversations": [ + {"user_id": UMO, "cid": first.conversation_id}, + {"user_id": UMO, "cid": second.conversation_id}, + ], + "cleanup_metadata": True, + } + ) + + assert result["deleted_count"] == 2 + assert result["metadata_cleanup"]["deleted_aliases"] == 1 + assert result["metadata_cleanup"]["retained_umos"] == [] + assert await temp_db.get_umo_alias(UMO) is None + + +@pytest.mark.asyncio +async def test_service_batch_delete_mixes_retained_and_cleaned_umos(temp_db): + keep_one = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await temp_db.create_conversation(user_id=UMO, platform_id="qq") + other = await temp_db.create_conversation(user_id=UMO_OTHER, platform_id="qq") + await seed_alias(temp_db) + await seed_alias(temp_db, UMO_OTHER) + service, _ = make_service(temp_db) + + result = await service.delete_conversation( + { + "conversations": [ + {"user_id": UMO, "cid": keep_one.conversation_id}, + {"user_id": UMO_OTHER, "cid": other.conversation_id}, + ], + "cleanup_metadata": True, + } + ) + + assert result["metadata_cleanup"]["deleted_aliases"] == 1 + assert result["metadata_cleanup"]["retained_umos"] == [UMO] + assert await temp_db.get_umo_alias(UMO) is not None + assert await temp_db.get_umo_alias(UMO_OTHER) is None + + +@pytest.mark.asyncio +async def test_service_cleanup_without_alias_does_not_fail(temp_db): + conversation = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + service, _ = make_service(temp_db) + + result = await service.delete_conversation( + { + "user_id": UMO, + "cid": conversation.conversation_id, + "cleanup_metadata": True, + } + ) + + assert result["metadata_cleanup"] == { + "deleted_aliases": 0, + "deleted_senders": 0, + "retained_umos": [], + } + + +@pytest.mark.asyncio +async def test_metadata_cleanup_retained_flag_requires_existing_metadata(temp_db): + await temp_db.create_conversation(user_id=UMO, platform_id="qq") + + outcome = await temp_db.delete_umo_metadata_if_unreferenced(UMO) + + assert outcome == { + "alias_deleted": False, + "senders_deleted": 0, + "retained": False, + } + + +class FailingCleanupDB: + """Delegates to a real database but fails the metadata cleanup call.""" + + def __init__(self, db) -> None: + self._db = db + + def __getattr__(self, name): + return getattr(self._db, name) + + async def delete_umo_metadata_if_unreferenced(self, umo: str) -> dict: + raise RuntimeError("database is locked") + + +@pytest.mark.asyncio +async def test_service_cleanup_error_does_not_fail_deletion(temp_db): + conversation = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await seed_alias(temp_db) + service, _ = make_service(FailingCleanupDB(temp_db)) + + result = await service.delete_conversation( + { + "user_id": UMO, + "cid": conversation.conversation_id, + "cleanup_metadata": True, + } + ) + + assert result["message"] == "对话删除成功" + assert result["metadata_cleanup"]["error"] == "database is locked" + assert result["metadata_cleanup"]["deleted_aliases"] == 0 + + +@pytest.mark.asyncio +async def test_service_batch_cleanup_only_covers_successful_deletions(temp_db): + conversation = await temp_db.create_conversation(user_id=UMO, platform_id="qq") + await seed_alias(temp_db) + await seed_alias(temp_db, UMO_OTHER) + service, _ = make_service(temp_db) + + result = await service.delete_conversation( + { + "conversations": [ + {"user_id": UMO, "cid": conversation.conversation_id}, + "broken-item", + {"user_id": UMO_OTHER, "cid": "missing-cid"}, + ], + "cleanup_metadata": True, + } + ) + + assert result["deleted_count"] == 2 + assert result["failed_count"] == 1 + assert await temp_db.get_umo_alias(UMO) is None + assert await temp_db.get_umo_alias(UMO_OTHER) is None + + +@pytest.mark.asyncio +async def test_concurrent_conversation_creation_and_cleanup_do_not_error(temp_db): + """Cleanup racing new conversations must not raise lock/consistency errors.""" + await seed_alias(temp_db) + + async def create(): + await temp_db.create_conversation(user_id=UMO, platform_id="qq") + + async def cleanup(): + await temp_db.delete_umo_metadata_if_unreferenced(UMO) + + results = await asyncio.gather( + *[create() for _ in range(10)], + *[cleanup() for _ in range(10)], + return_exceptions=True, + ) + + assert not [result for result in results if isinstance(result, Exception)] + + conversations = await temp_db.get_conversations(user_id=UMO) + if conversations: + # A committed conversation must keep the alias metadata it references. + assert await temp_db.get_umo_alias(UMO) is not None + + +# ==== +# API layer parameter passing +# ==== + + +class RecordingService: + def __init__(self) -> None: + self.payload: dict | None = None + + async def delete_conversation(self, payload: dict) -> dict: + self.payload = payload + return {"message": "ok"} + + +@pytest.mark.asyncio +async def test_api_single_delete_forwards_cleanup_flag(): + service = RecordingService() + + await conversations_api.delete_conversation( + conversation_id="cid-1", + user_id=UMO, + cleanup_metadata=True, + _auth=None, + service=service, + ) + + assert service.payload == { + "user_id": UMO, + "cid": "cid-1", + "cleanup_metadata": True, + } + + +@pytest.mark.asyncio +async def test_api_single_delete_defaults_cleanup_flag_to_false(): + service = RecordingService() + + await conversations_api.delete_conversation( + conversation_id="cid-1", + user_id=UMO, + cleanup_metadata=False, + _auth=None, + service=service, + ) + + assert service.payload["cleanup_metadata"] is False + + +@pytest.mark.asyncio +async def test_api_batch_delete_forwards_cleanup_flag(): + service = RecordingService() + + await conversations_api.batch_delete_conversations( + payload=ConversationBatchDeleteRequest( + conversations=[{"user_id": UMO, "cid": "cid-1"}], + cleanup_metadata=True, + ), + _auth=None, + service=service, + ) + + assert service.payload is not None + assert service.payload["cleanup_metadata"] is True + assert service.payload["conversations"] == [{"user_id": UMO, "cid": "cid-1"}]