Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions astrbot/core/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Standalone alias deletion

The issue asks for an official per-UMO alias deletion method, or an equivalent cascade option. The new method only cleans metadata through conversation deletion and retains aliases while any conversation references the UMO, so callers cannot independently delete an alias.

Prompt for AI agents
In `astrbot/core/db/__init__.py` at line 914:

**Standalone alias deletion**

The issue asks for an official per-UMO alias deletion method, or an equivalent cascade option. The new method only cleans metadata through conversation deletion and retains aliases while any conversation references the UMO, so callers cannot independently delete an alias.

From #10704:

Provide official per-UMO alias deletion or an equivalent cascade option.

"""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).
"""
...

Comment on lines +913 to +931

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Critical · Missing alias deletion API

The issue asks for an official delete_umo_alias(umo) -> bool method, or the stated cascade alternative. The change adds only delete_umo_metadata_if_unreferenced, which refuses to delete metadata while conversations exist and is only used by the dashboard cleanup flow, leaving the requested reusable API unavailable.

Prompt for AI agents
In `astrbot/core/db/__init__.py` at lines 897-915:

**Missing alias deletion API**

The issue asks for an official `delete_umo_alias(umo) -> bool` method, or the stated cascade alternative. The change adds only `delete_umo_metadata_if_unreferenced`, which refuses to delete metadata while conversations exist and is only used by the dashboard cleanup flow, leaving the requested reusable API unavailable.

From #10704:

Expose an official per-UMO alias deletion method (`delete_umo_alias(umo) -> bool`), or the accepted conversation-delete cascade alternative.

# ====
# UMO Sender Management
# ====
Expand Down
62 changes: 62 additions & 0 deletions astrbot/core/db/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
# ====
Expand Down
7 changes: 6 additions & 1 deletion astrbot/dashboard/api/conversations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
)
)

Expand Down
1 change: 1 addition & 0 deletions astrbot/dashboard/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@ class ConversationMessagesReplaceRequest(OpenModel):

class ConversationBatchDeleteRequest(BaseModel):
conversations: list[ConversationRef]
cleanup_metadata: bool = False


class ConversationExportRequest(BaseModel):
Expand Down
76 changes: 72 additions & 4 deletions astrbot/dashboard/services/conversation_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand All @@ -315,19 +336,66 @@ 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}")

message = f"成功删除 {deleted_count} 个对话"
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:
Expand Down
1 change: 1 addition & 0 deletions changelogs/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions dashboard/src/api/generated/openapi-v1/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,10 @@ export type ConfigRouteUpsertRequest = {

export type ConversationBatchDeleteRequest = {
conversations: Array<ConversationRef>;
/**
* Delete alias and sender metadata for the sessions when no other conversation still references them.
*/
cleanup_metadata?: boolean;
};

export type ConversationExportRequest = {
Expand Down Expand Up @@ -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;
};
};
Expand Down
4 changes: 2 additions & 2 deletions dashboard/src/api/v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1803,11 +1803,11 @@ export const conversationApi = {
}),
);
},
delete(userId: string, cid: string) {
delete(userId: string, cid: string, cleanupMetadata = false) {
return typed<any>(
openApiV1.deleteConversation({
path: { conversation_id: cid },
query: { user_id: userId },
query: { user_id: userId, cleanup_metadata: cleanupMetadata },
}),
);
},
Expand Down
36 changes: 33 additions & 3 deletions dashboard/src/components/ConfirmDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@
<v-dialog v-model="isOpen" max-width="400">
<v-card>
<v-card-title class="text-h3 pa-4 pb-0 pl-6">{{ title }}</v-card-title>
<v-card-text>{{ message }}</v-card-text>
<v-card-text>
{{ message }}
<v-checkbox
v-if="checkboxOptions"
v-model="checkboxChecked"
:label="checkboxOptions.label"
:hint="checkboxOptions.hint"
persistent-hint
density="compact"
class="mt-2"
></v-checkbox>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="gray" variant="text" @click="handleCancel">{{ t('core.common.dialog.cancelButton') }}</v-btn>
Expand All @@ -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) => {
Expand All @@ -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`
Expand Down
8 changes: 6 additions & 2 deletions dashboard/src/i18n/locales/en-US/features/conversation.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,19 @@
"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",
"message": "Are you sure you want to delete the selected {count} conversations? This action cannot be undone, please proceed with caution!",
"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": {
Expand Down
8 changes: 6 additions & 2 deletions dashboard/src/i18n/locales/ja-JP/features/conversation.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,19 @@
"title": "削除の確認",
"message": "会話 {title} を削除してもよろしいですか?この操作は元に戻せません。",
"cancel": "キャンセル",
"confirm": "削除"
"confirm": "削除",
"cleanupMetadata": "セッションメタデータ(別名など)も削除する",
"cleanupMetadataHint": "他の会話が残っていない場合のみ削除します。デフォルトはオフです。"
},
"batchDelete": {
"title": "一括削除の確認",
"message": "選択した {count} 件の会話を削除してもよろしいですか?この操作は元に戻せません。",
"andMore": "ほか {count} 件",
"cancel": "キャンセル",
"confirm": "一括削除",
"warning": "警告:この操作は元に戻せません。"
"warning": "警告:この操作は元に戻せません。",
"cleanupMetadata": "会話が残っていないセッションメタデータも削除する(別名など)",
"cleanupMetadataHint": "他の会話が残っているセッションのメタデータは保持されます。"
}
},
"messages": {
Expand Down
Loading