Repository navigation
feat: Improve the dialogue interface and modify the dialogue - #7951
Conversation
|
|
||
| // 通用发送能力,由消息列表或外部宿主(如工具调试结果抽屉)提供;内容项按自身场景组装参数。 | ||
| export type SendMessage = (opts: SendMessageOptions) => void | ||
|
|
There was a problem hiding this comment.
Here are the issues and suggestions:
1. Bug: truncating flag can leak / permanently block sends
const truncateFrom = async (chatRecordId: string) => {
const cid = getChatId()
if (!cid || truncating) return
truncating = true
try {
await truncateApi(cid, chatRecordId)
} finally {
truncating = false
}
...
}- If
truncateApirejects, the error propagates to the caller, but the message list is left untouched (correct per comment). However, callers should be aware it throws — verify all call sites eitherawaitwith acatchor intentionally let it bubble. - More importantly,
truncatingis a plainlet(not reactive), so UI can't reflect "truncation in progress" to disable inputs.sendMessagesilently no-ops while truncating, which is a silent failure for the user. Consider making it arefand surfacing it so the UI can disable controls, rather than silently dropping sends.
2. Race window between finally and post-cleanup
After try/finally, truncating is set back to false before the local messages.value.splice(...) runs. A concurrent sendMessage could slip in between and append messages that then get spliced away. Move truncating = false to after the splice (or keep it true until the end):
truncating = true
try {
await truncateApi(cid, chatRecordId)
if (cid !== getChatId()) return
const answerIndex = messages.value.findIndex((m) => m.recordId === chatRecordId)
if (answerIndex < 0) return
const questionIndex = messages.value[answerIndex - 1]?.role === 'USER' ? answerIndex - 1 : answerIndex
messages.value.splice(questionIndex)
} finally {
truncating = false
}Note: with this shape, an error from truncateApi still skips cleanup (good) but you must ensure finally is what resets the flag.
3. getMessageRecordIds semantic edge cases
export const getMessageRecordIds = (messages) =>
messages.map((message, index) =>
message.role === 'ASSISTANT' ? message.recordId : messages[index + 1]?.recordId)- For an ASSISTANT message the returned id is its own recordId; for a USER message it's the following assistant's recordId. This assumes strict USER/ASSISTANT alternation starting with USER. If a conversation ever starts with an ASSISTANT message, or has two consecutive users, the mapping is wrong. Consider documenting/asserting the invariant, or keying off the nearest following ASSISTANT regardless of position.
- If a user message is the last element, it returns
undefined— fine, but make sure consumers handle it (the comment says answered-not-yet → undefined, consistent). messages[index + 1]only looks one step ahead; if the next element isn't an assistant (e.g., system/tool messages exist inChatMessage), you'd pick a non-assistantrecordId. Safer: scan forward for the firstASSISTANT.
4. computed holds array references; downstream reactivity
messageRecordIds recomputes whenever messages.value changes. But splice/push on the array reference triggers recomputation — good. Just note getMessageRecordIds is exported and used standalone; it reads raw arrays, so any caller using it outside computed won't be reactive. That's acceptable but worth a doc note.
5. useMessageRecordId inject default allocation
return inject(MESSAGE_RECORD_ID_KEY, ref(undefined))The default ref(undefined) is created eagerly as an argument on every call, even when a provider exists. Minor, but you can hoist a module-level constant:
const EMPTY_RECORD_ID: Readonly<Ref<string | undefined>> = ref(undefined)
return inject(MESSAGE_RECORD_ID_KEY, EMPTY_RECORD_ID)(The default arg is only evaluated eagerly because it's passed by value, so hoisting avoids per-call allocation.)
6. Type of injection key vs provided value
MESSAGE_RECORD_ID_KEY: InjectionKey<Readonly<Ref<string | undefined>>> but messageRecordIds is ComputedRef<(string | undefined)[]> — the per-row value provided must be a single-element ref, so confirm the provider (in the template with provide) extracts one entry, not the whole computed array. If a component provides messageRecordIds directly it will be type-mismatched at runtime. Add a small helper or document the intended provider (e.g., provide(MESSAGE_RECORD_ID_KEY, computed(() => messageRecordIds.value[index]))).
7. truncateFrom uses findIndex on recordId
- Messages without
recordId(pending user message) won't match, soanswerIndex < 0→ silent no-op even though truncation succeeded on backend. Consider whether the UI should still update; add a log or return a result so callers can react. - The
questionIndexheuristic assumes the previous element is the pairing question. Combined with issue [FEATURE]增加首次进入系统强制修改用户密码功能。 #3's alternation assumption, a mismatch would splice from the wrong place. UsinggetMessageRecordIdslogic here would keep both sides consistent.
8. Missing truncating in returned store type
truncateFrom is exposed, but truncating state isn't. Either expose a reactive truncating ref (see #1) or explicitly exclude it from MessageListStore type. Ensure the interface MessageListStore declares messageRecordIds and truncateFrom with correct types — this patch adds them to the returned object but the diff doesn't show the interface updated. Verify it compiles.
9. Misc
- Consider adding a unit test for
getMessageRecordIdscovering: leading assistant, trailing unanswered user, and non-alternating sequences. - The Chinese comments are helpful; keep them, but ensure exported functions have JSDoc in the project's convention for the public API surface (
truncateFrom,useMessageRecordId).
|
|
||
| class Operate(APIView): | ||
| authentication_classes = [TokenAuth] | ||
|
|
There was a problem hiding this comment.
Here's my review of the code changes:
Issues & Potential Concerns
1. Serializer instantiated with data= but never .is_valid()-ed
HistoricalConversationRecordSerializer(
data={...}
).truncate(chat_record_id)This is misleading. data= signals DRF input validation, but validation is skipped and truncate uses the raw dict internally. Either:
- Pass validated data explicitly, or
- Add a docstring explaining
truncate()handles parsing internally, or - Refactor to a plain service/function instead of a serializer.
This can confuse future maintainers and hides potential input-validation gaps.
2. Import inside method body
from chat.serializers.chat_record import HistoricalConversationRecordSerializerMove this to module-level imports unless there's a circular-import reason. If there is one, add a comment explaining it.
3. No validation that request.user.id matches the chat owner / belongs to the workspace
The view relies entirely on @has_permissions, but the permission decorator checks workspace/application scope, not whether the specific chat_record_id belongs to that user/application. Consider validating:
- Record belongs to
chat_id chat_idbelongs toapplication_id/workspace_id
Otherwise an authorized user in the workspace could truncate records from a chat they don't own (potential IDOR).
4. Destructive operation — missing safeguards
- No confirmation flag / soft-delete / audit log mentioned.
operation_idandsummaryare both set to the same translated string — DRF/openapioperation_idshould ideally be a stable ASCII identifier (e.g.,"truncate_conversation_records"), not a translated phrase. Translatedoperation_ids can break generated SDKs across locales.- Same issue for
tags=[_("Chat")]if already used elsewhere — fine, butoperation_idis the real concern.
5. Hardcoded POST-only schema mismatch
@extend_schema(methods=["POST"], ...) but class only implements post(). Fine, just noting it must match — consider allowing APIView default detection.
6. Type hints incomplete
Method returns nothing annotated (-> Response). Add it for consistency.
7. chat_user_id naming vs .id
str(request.user.id) assumes user.id is the chat_user_id, not an auth user id. Double check this is correct in your domain model — mixing these is a common source of bugs.
8. Error handling missing at API layer
If truncate() raises (record not found, already truncated, DB error), does result.success(...) wrap properly? Ensure exceptions map to sensible HTTP codes, not blanket 200/500.
Minor / Style
- The trailing blank line before
class Operate— cosmetic. - Consider extracting permissions into a shared constant if reused.
- Batch/deleted records returned by
truncateshould probably include count (e.g.,{"deleted_count": N}) so clients can confirm what happened.
Suggested refactor sketch
from chat.serializers.chat_record import HistoricalConversationRecordSerializer # top-level
def post(self, request, workspace_id, application_id, chat_id, chat_record_id):
serializer = HistoricalConversationRecordSerializer(
data={
"application_id": application_id,
"chat_id": chat_id,
"chat_user_id": str(request.user.id),
"chat_record_id": chat_record_id, # pass explicitly
},
context={"request": request},
)
serializer.is_valid(raise_exception=True)
deleted = serializer.save() # or .truncate()
return result.success({"deleted_count": len(deleted)})And change operation_id=_("Truncate conversation records") → operation_id="truncate_conversation_records".
Summary: Functionally plausible, but risks around input validation, IDOR scope checks, destructive-op safety, and a misleading data= usage are worth addressing before merge.
feat: Improve the dialogue interface and modify the dialogue