Skip to content
Merged
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
4 changes: 4 additions & 0 deletions ui/src/api/chat/conversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ const getShareConversation = (shareId: string) => get<ChatShareDetail>(`/share/$
/** 将语音转换为文字。 */
const postSpeechToText = (applicationId: string, data: unknown) => post(`${getApplicationPath(applicationId)}/speech_to_text`, data)

/** 清空某个智能体的全部历史对话(当前对话用户)。 */
const clearConversations = (applicationId: string) => del(`${getApplicationPath(applicationId)}/chat/clear`)

export default {
putConversationFeedback,
getConversationOpen,
Expand All @@ -71,4 +74,5 @@ export default {
postShareConversation,
getShareConversation,
postSpeechToText,
clearConversations,
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The diff is syntactically fine and follows the existing API-module style. There are no obvious implementation bugs, but there are several things to verify/improve:

  1. Destructive operation risk

    • clearConversations deletes all chat history for the current user under the given agent.
    • Ensure this is protected by:
      • authentication and authorization checks on the server,
      • confirmation in the UI,
      • audit logging if history deletion is sensitive.
    • Make sure the backend validates that the current user actually owns/can access applicationId to avoid IDOR-style issues.
  2. Naming clarity

    • clearConversations is somewhat ambiguous. It clears the current user’s conversation history for one agent, so a clearer name could be:
      • clearChatHistory
      • clearConversationHistory
      • clearCurrentUserConversations
    • Update the JSDoc to make “current authenticated user only” explicit.
  3. HTTP method / endpoint contract

    • Confirm the backend really expects DELETE /.../chat/clear.
    • Some proxies/clients handle DELETE inconsistently, and some APIs use POST for bulk-clear operations. If del does not support a request body and the backend requires one, this will fail.
    • Confirm the expected response, especially if it returns 204 No Content. The API client should handle empty responses correctly.
  4. Return type

    • Consider adding an explicit return type, e.g. Promise<void> or whatever del returns, if the project follows that convention:
      const clearConversations = (applicationId: string): Promise<void> =>
        del(`${getApplicationPath(applicationId)}/chat/clear`)
    • This improves type safety and documents the expected behavior.
  5. UI/cache invalidation

    • After calling this API, invalidate/refetch conversation lists and reset any active chat state. Otherwise the UI may still show deleted conversations.
  6. Tests

    • Add tests for:
      • successful clearing,
      • error handling,
      • unauthorized access,
      • empty-history behavior,
      • UI cache/state reset after success.

Overall: the diff is safe code-wise, but the main concerns are the destructive nature of the endpoint, backend authorization, correct HTTP method/response handling, and cache/UI refresh after clearing.

Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface PortalConversationListDeps {
/** 分页获取某个智能体的历史会话,展开分组时刷新。 */
pageGroupConversations: (applicationId: string, page: number, size: number) => Promise<{ records?: Conversation[] } | null | undefined>
removeConversation: (applicationId: string, chatId: string) => Promise<unknown>
/** 清空某个智能体当前用户的全部历史会话。 */
clearApplicationConversations: (applicationId: string) => Promise<unknown>
/** 当前对话的智能体 ID;门户首页与全部智能体页为空。 */
currentApplicationId: Readonly<Ref<string>>
/** 当前是否处于全部智能体页。 */
Expand All @@ -45,7 +47,7 @@ const GROUP_CONVERSATION_LIMIT = 20
* 侧栏展示时以其为准,保证新建、重命名和删除即时生效;其他智能体使用分组接口返回的最近会话。
*/
export function createPortalConversationListStore(deps: PortalConversationListDeps) {
const { pageApplicationConversations, pageApplications, pageGroupConversations, removeConversation, currentApplicationId } = deps
const { pageApplicationConversations, pageApplications, pageGroupConversations, removeConversation, clearApplicationConversations, currentApplicationId } = deps

// 历史对话分组
const applicationGroups = ref<PortalApplicationGroup[]>([])
Expand Down Expand Up @@ -97,6 +99,17 @@ export function createPortalConversationListStore(deps: PortalConversationListDe
}
}

// 清空某一智能体的全部历史对话;onCleared 用于同步当前智能体会话列表 Store。
const clearGroupConversations = async (applicationId: string, onCleared: () => void) => {
await clearApplicationConversations(applicationId)
const group = applicationGroups.value.find((applicationGroup) => applicationGroup.id === applicationId)
if (group) {
group.conversations = []
group.count = 0
}
onCleared()
}

// 先查询全部分组和会话,再删除,避免边删除边翻页造成记录遗漏。
const clearConversations = async (onRemoved: (applicationId: string, chatId: string) => void) => {
const applicationIds = new Set<string>()
Expand Down Expand Up @@ -170,6 +183,7 @@ export function createPortalConversationListStore(deps: PortalConversationListDe
shareConversation: deps.shareConversation,
openApplicationList: deps.openApplicationList,
newConversation,
clearGroupConversations,
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Code Review

Issues / Potential Problems

  1. No error handling on clearApplicationConversations

    • If the API call rejects, onCleared() and local state updates never happen — that's actually correct, but the error propagates unhandled. Consider wrapping in try/catch to surface a user-facing error or log it, consistent with how removeConversation is (or isn't) handled elsewhere.
  2. Local state mutation only; no rollback

    • After a successful API call you mutate group.conversations = [] and group.count = 0. If the server later fails on the next refresh, the list will still show empty until a refetch. Acceptable if you trust the backend, but worth noting.
    • More importantly, other groups' data isn't touched — verify count is not derived (e.g., from a separate aggregate endpoint) that could become stale after clearing.
  3. onCleared callback contract is implicit

    • The signature (applicationId: string, onCleared: () => void) uses a positional callback. This is inconsistent with clearConversations(onRemoved) which takes one callback. Consider naming/signature consistency, or document clearly that onCleared must sync the current-application store. Also: should onCleared fire before or after the group state is reset? Ordering matters if the callee reads applicationGroups.
  4. Missing guard for empty/invalid applicationId

    • No validation that applicationId is non-empty. A stray call would hit the backend unnecessarily.
  5. Duplicate "clear" methods may confuse

    • You now have both clearConversations (all groups) and clearGroupConversations (single app). Their names are close but behavior differs significantly. Consider renaming to clearAllConversations vs clearConversationGroup, or add JSDoc clarifying scope.
  6. Possible race condition

    • If the user clears while pageGroupConversations is in-flight for the same group, the response could repopulate conversations after the clear. Consider a request token / generation counter per group, similar to cancellation patterns used elsewhere.
  7. count = 0 assumption

    • Assumes count semantically equals "current user's conversations". If count includes shared/other-user sessions, this becomes incorrect. Confirm the backend semantics of clearApplicationConversations matches what count reflects.
  8. Promise<unknown> return type

    • Returning unknown gives no type safety at the call site. If the API returns something useful (e.g., number cleared), type it. Otherwise, Promise<void> would be clearer.

Optimization Suggestions

  • Consider optimistic update pattern (clear UI first, rollback on failure) since this action is destructive and user-initiated — improves perceived latency.
  • Extract the group lookup into a small helper (findGroup(id)) to reduce repetition; you already do similar lookups elsewhere.
  • Add unit tests covering: successful clear, failed clear (state unchanged + no onCleared), in-flight refresh race.
  • Consider exposing clearGroupConversations result (boolean) so callers know whether anything was cleared.

Minor / Style

  • The added destructuring line is getting long; consider grouping deps or using deps.x directly for rarely-used ones.
  • Since you're adding to a public-ish store surface (clearGroupConversations in the returned object), ensure the corresponding PortalConversationListDeps doc and consumer wiring are updated (diff shows deps added — good).

Overall the change is small and coherent; main risks are error propagation, callback ordering contract, and race conditions with group refreshes.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,28 @@ const handleClearConversations = () => {
clearing.value = false
})
}

// 清空指定智能体的全部历史对话;若为当前智能体,同步清空会话列表并新建对话。
const clearGroupConversationLoading = ref(false)
const handleClearGroupConversations = (group: PortalApplicationGroup) => {
if (clearGroupConversationLoading.value) return
clearGroupConversationLoading.value = true
MsgConfirm('确认清空该智能体的全部历史对话?', '清空后无法恢复。', { confirmButtonText: '清空' })
.then(() =>
portalList.clearGroupConversations(group.id, () => {
if (group.id === currentApplicationId.value) {
conversations.value = []
switchShared(false)
newConversation()
}
}),
)
.then(() => MsgSuccess('清空成功'))
.catch(() => {})
.finally(() => {
clearGroupConversationLoading.value = false
})
}
</script>

<template>
Expand Down Expand Up @@ -174,9 +196,9 @@ const handleClearConversations = () => {
<span>新建对话</span>
</MkDropdownItem>
<!-- 删除智能体历史分组,待接入对应接口 -->
<MkDropdownItem divided disabled>
<MkDropdownItem divided @click="handleClearGroupConversations(group)">
<template #icon><MkIcon name="icon_delete-trash_outlined" /></template>
<span>删除</span>
<span>清空对话</span>
</MkDropdownItem>
</MkDropdownMenu>
</template>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Review findings

  1. Async flow may not actually wait for the clear operation

    .then(() =>
      portalList.clearGroupConversations(group.id, () => { ... }),
    )
    .then(() => MsgSuccess('清空成功'))

    If portalList.clearGroupConversations returns void instead of a Promise, the success message will be shown immediately, and the callback/UI reset may happen later or not at all. Ensure the store method returns a Promise that resolves only after the backend clear and callback have completed.

  2. .catch(() => {}) swallows real errors
    This hides both confirmation cancellation and actual API failures. Users will not know clearing failed. Distinguish cancellation from failure and show an error message for real failures.

  3. The loading flag is not reflected in the UI
    clearGroupConversationLoading only prevents re-entry. The menu item remains clickable, and the user gets no feedback while the request is running. Bind it to disabled or a loading state:

    <MkDropdownItem
      divided
      :disabled="clearGroupConversationLoading"
      @click="handleClearGroupConversations(group)"
    >
  4. Store accepts a UI callback, which couples store and view
    Prefer returning a Promise from the store and performing UI updates in the component. This is easier to test and less error-prone.

  5. Current-conversation reset may be incomplete
    conversations.value = [] only clears the list. If there are other related states, such as selected conversation ID, message list, pagination, search results, cached group conversation counts, or last-message metadata, they may become stale. Centralize the reset logic in a single function.

  6. Possible ID type mismatch
    group.id === currentApplicationId.value uses strict equality. If one is a number and the other a string, the condition will silently fail. Normalize types or verify both are always the same type.

  7. Stale comment
    The old comment still says “删除智能体历史分组”; the action is now “清空对话”. Update the comment to avoid confusion.

  8. Synchronous errors before the promise chain could leave loading stuck
    If MsgConfirm throws synchronously before returning a promise, .finally will not run. An async/await + try/finally structure is safer.

Suggested refactor

const clearGroupConversationLoading = ref(false)

const handleClearGroupConversations = async (group: PortalApplicationGroup) => {
  if (clearGroupConversationLoading.value) return

  clearGroupConversationLoading.value = true
  let confirmed = false

  try {
    await MsgConfirm(
      '确认清空该智能体的全部历史对话?',
      '清空后无法恢复。',
      { confirmButtonText: '清空', type: 'warning' },
    )

    confirmed = true

    // Prefer the store method to return Promise<void>.
    await portalList.clearGroupConversations(group.id)

    if (group.id === currentApplicationId.value) {
      resetCurrentConversationState() // clear list, selection, messages, pagination, etc.
      switchShared(false)
      newConversation()
    }

    MsgSuccess('清空成功')
  } catch (err) {
    // Do not show an error when the user simply cancels the confirmation.
    if (confirmed) {
      MsgError('清空失败,请稍后重试')
    }
  } finally {
    clearGroupConversationLoading.value = false
  }
}

Store change:

// Before: callback style, possibly returns void
clearGroupConversations(groupId: string, callback?: () => void)

// Better: return a promise and reject on failure
async clearGroupConversations(groupId: string): Promise<void> {
  await api.clearGroupConversations(groupId)
}

Minor suggestions

  • Rename clearGroupConversationLoading to isClearingGroupConversation for clarity.
  • Add a permission check if not every user should be allowed to clear all conversations.
  • Consider disabling the menu item when the group has no conversations.
  • Verify that switchShared(false) and newConversation() do not duplicate or contradict the reset logic, especially if either is asynchronous.

Expand Down
1 change: 1 addition & 0 deletions ui/src/conversation-panel/view/portal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export function createPortalConversation(options: PortalConversationOptions): Po
currentApplicationId,
isApplicationListActive,
openApplication,
clearApplicationConversations: (applicationId) => ConversationApi.clearConversations(applicationId),
// 跨智能体通过导航激活,等待路由驱动的消息加载结束后再全选分享。
shareConversation: async (applicationId, chatId) => {
if (bundle.msgs.loading.value) return false
Expand Down
Loading