Skip to content

feat: Improve the dialogue interface and modify the dialogue - #7951

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@feat_modify_dialogue
Nov 16, 2026
Merged

shaohuzhang1 merged 1 commit into
v3from
pr@v3@feat_modify_dialogue

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: Improve the dialogue interface and modify the dialogue


// 通用发送能力,由消息列表或外部宿主(如工具调试结果抽屉)提供;内容项按自身场景组装参数。
export type SendMessage = (opts: SendMessageOptions) => void

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.

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 truncateApi rejects, 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 either await with a catch or intentionally let it bubble.
  • More importantly, truncating is a plain let (not reactive), so UI can't reflect "truncation in progress" to disable inputs. sendMessage silently no-ops while truncating, which is a silent failure for the user. Consider making it a ref and 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 in ChatMessage), you'd pick a non-assistant recordId. Safer: scan forward for the first ASSISTANT.

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, so answerIndex < 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 questionIndex heuristic assumes the previous element is the pairing question. Combined with issue [FEATURE]增加首次进入系统强制修改用户密码功能。 #3's alternation assumption, a mismatch would splice from the wrong place. Using getMessageRecordIds logic 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 getMessageRecordIds covering: 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]

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.

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 HistoricalConversationRecordSerializer

Move 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_id belongs to application_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_id and summary are both set to the same translated string — DRF/openapi operation_id should ideally be a stable ASCII identifier (e.g., "truncate_conversation_records"), not a translated phrase. Translated operation_ids can break generated SDKs across locales.
  • Same issue for tags=[_("Chat")] if already used elsewhere — fine, but operation_id is 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 truncate should 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.

@shaohuzhang1
shaohuzhang1 merged commit 404c489 into v3 Nov 16, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the pr@v3@feat_modify_dialogue branch November 16, 2026 12:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant