Skip to content

feat: Optimize the loading style of the conversation - #8293

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_loading
Dec 3, 2026
Merged

shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_loading

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: Optimize the loading style of the conversation


// 通用发送能力,由消息列表或外部宿主(如工具调试结果抽屉)提供;内容项按自身场景组装参数。
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's my review of the code changes:

Summary

The changes add a streamingMessage ref to track which message is currently being streamed, plus an injection key/helper so content items can know if their parent answer is actively streaming (to avoid a stale "running" indicator after completion).

Potential Issues

1. Race condition risk with currentStream = null in multiple places

In runStream, closeStream() is called first (which resets state and sets streamingMessage.value = null), then immediately streamLoading.value = true and streamingMessage.value = target. This looks fine sequentially, but if request() is slow and another runStream is invoked before the promise resolves, the earlier .then handler will overwrite currentStream — there's no guard that the resolved response still belongs to the current call. Consider capturing a token/id:

const token = ++streamToken
request().then((response) => {
  if (token !== streamToken) { /* abort or ignore */ }
  ...
})

This existed before your change but adding target makes it more consequential — streamingMessage.value = null in a stale .catch/onComplete could wrongly clear an active new stream.

2. streamingMessage set before response resolves

streamingMessage.value = target is set synchronously when runStream begins, before the request resolves. If request() throws or fails, streamingMessage is correctly reset in .catch, but content items will briefly render "running" during the request handshake. Likely acceptable, just confirm this matches the desired UX.

3. computed(() => streamingMessage.value) wrapper is redundant

streamingMessage: computed(() => streamingMessage.value),

Since streamingMessage is already a Readonly-ish shallowRef, wrapping it in a computed adds overhead without benefit. Consumers needing read-only can type it as Readonly<Ref<...>>. If you want to expose it immutably, prefer exposing the ref directly and relying on types, or use readonly where appropriate. Minor.

4. useMessageStreaming returns a static false ref when not provided

return inject(MESSAGE_STREAMING_KEY, ref(false))

The default ref(false) is created fresh per call — fine functionally, but allocating a new ref each call is slightly wasteful. A module-level constant const NEVER_STREAMING = ref(false) (or readonly(ref(false))) can be shared. Verify the consumer only needs truthiness and won't mutate it.

5. TypeScript typing of the provided value

MESSAGE_STREAMING_KEY expects Readonly<Ref<boolean>>, but the store exports streamingMessage: computed(...) typed as ComputedRef<ChatMessage | null>. There seems to be no wiring shown here — ensure that wherever MESSAGE_STREAMING_KEY is provided, it's derived properly:

provide(MESSAGE_STREAMING_KEY, computed(() => store.streamingMessage.value?.id === props.message.id))

Otherwise the name mismatch (streamingMessage is ChatMessage | null, while the key is boolean) may lead to confusion. Worth confirming the provider code exists and correct.

6. Cleanup guarantee on unmount

streamingMessage.value is reset in closeStream, onComplete, and .catch. Ensure the store also calls closeStream() on component unmount/dispose so streamingMessage doesn't remain dangling. Not shown in the diff — verify.

7. Comment says "与 streamLoading 同步复位" (reset in sync with streamLoading)

Double-check every place streamLoading.value = false occurs — the three shown spots are updated, but grep for others (e.g., abort paths, error boundaries). Any missed spot leaves streamingMessage stale.

Optimization Suggestions

  • Extract a helper like resetStreamState() to set currentStream = null; streamLoading.value = false; streamingMessage.value = null atomically in one place, reducing duplication across the aborted/failed/succeeded branches.
  • Consider deriving streamLoading from streamingMessage.value != null if they truly always move together — eliminates the duplicate-state bug class entirely.
  • Guard against stale promises with a sequence counter (point 1) — most impactful robustness fix.

Verdict

The intent and structure are sound, comments are helpful. The main real concern is the stale-promise race (issue #1), which pre-existed but is now amplified since streamingMessage will be cleared by an outdated completion. Fix that and extract the reset helper; the rest are minor cleanups.

@shaohuzhang1
shaohuzhang1 merged commit 036504a into v3 Dec 3, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the pr@v3@fix_loading branch December 3, 2026 10:33
<span class="-mx-1" :class="{ 'mk-dotting': content.status === 'RUNNING' && streaming }">
{{ content.status === 'RUNNING' ? t('chat.message.thinking') : t('chat.message.thinkingCompleted') }}
</span>
</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 of the diff

🔴 Potential bugs

  1. Boolean coercion of streaming in the template is unsafe.
    Old code read messageList?.streamLoading.value, which yields a real boolean.
    New code uses streaming directly. This only works if useMessageStreaming() returns a Ref<boolean>/ComputedRef<boolean> (auto-unwrapped in the template).

    • If it returns a composable object (e.g. { isStreaming, ... }) or a function, streaming is always truthy → mk-dotting animates unconditionally. This is the most likely regression.
    • Verify the return type, and if it isn't a pure boolean ref, use streaming.isStreaming / streaming() and consider !! or Boolean().
  2. Lost "optional context" tolerance.
    inject(MESSAGE_LIST_KEY, null) had a null default and messageList?. optional chaining, so the component worked outside a message list (unit tests, Storybook, standalone/SSR usage). If useMessageStreaming() calls inject without a default (or throws when no provider exists), this now breaks in those contexts. Check the composable's injection behavior.

  3. Semantics may have changed.
    Previously the animation depended on that message list instance's streamLoading. If useMessageStreaming() exposes a global/app-level streaming flag, then every RUNNING reasoning block across all messages would animate simultaneously. Confirm the composable's scope matches the old per-list scope.

  4. Circular-import risk.
    The component now imports from ../../message-list (likely a barrel file). If that barrel re-exports components that import this component, you can get a circular dependency or an undefined import at module-eval time. Prefer importing the composable from its concrete module (e.g. ../../message-list/use-message-streaming).

🟡 Redundancy / logic

  1. content.status === 'RUNNING' and streaming likely overlap.
    If streaming is true only while a message is running, the status check is redundant; if they can disagree (stale status vs. stream state, or a different message running), you get wrong UI. Consider one source of truth.

  2. Repeated template expression.
    content.status === 'RUNNING' appears twice (class binding + label text). Compute once in <script setup>:

    const isRunning = computed(() => props.content.status === 'RUNNING')
    const isThinkingStreaming = computed(() => isRunning.value && isStreaming.value)

    This also makes the boolean coercion explicit and testable.

  3. Naming.
    streaming reads like an action/store; isStreaming communicates a boolean. Helps prevent the bug in point 1.

🟢 Minor / style

  1. defineProps result not assigned. Fine in template, but if you compute the derived flags above you'll need const props = defineProps<...>(). Also consider extracting the inline prop type ({ content?: string | null; status?: string }) into a named interface for reuse and to make status a string-literal union instead of string.

  2. useTemplateRef<HTMLElement>('reasoningScrollRef') passed inline to useBottomFollow. Works, but storing it in a const improves readability and lets you reuse it (e.g., for a watch/nextTick scroll-to-bottom when expanding). Note it's HTMLElement while the ref presumably targets a scroll container — HTMLElement is fine, HTMLDivElement is tighter.

  3. No watcher on isExpanded / new content. If the panel can be expanded while content streams, verify useBottomFollow still responds to height changes (dependency array / ResizeObserver). Not caused by this diff, but worth confirming since the streaming source changed.

Suggested shape

const props = defineProps<{
  content: { content?: string | null; status?: 'RUNNING' | 'COMPLETED' | string }
}>()

const { isStreaming } = useMessageStreaming() // confirm actual API
const isRunning = computed(() => props.content.status === 'RUNNING')
const showDotting = computed(() => isRunning.value && Boolean(unref(isStreaming)))
<span class="-mx-1" :class="{ 'mk-dotting': showDotting }">

Bottom line: the refactor is fine if useMessageStreaming() returns a boolean ref, tolerates a missing provider, and is list-scoped rather than global. Verify those three things; otherwise the dotting indicator can become always-on or the component can fail outside a message-list context.

:loading="streaming && toolItem.status === 'RUNNING'"
:expanded="isToolExpanded(toolItem, index)"
@update:expanded="manualToolExpanded[toolKey(toolItem, index)] = $event"
@toggle="toggleTool(toolItem, index)"

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 patch is syntactically fine for Vue 3, but there are a few semantic and maintainability points to verify.

Potential issues

  1. Scope of useMessageStreaming()

    • Verify that useMessageStreaming() returns the streaming state for this specific message/answer, not a global “any message is streaming” flag.
    • If it is global, a completed tool group could still show running while another answer streams, or a valid running tool could be suppressed if the state is not yet updated.
    • The comment says “所属回答结束后” (after the owning answer ends), so the composable should be message-scoped.
  2. Stale RUNNING status becomes success

    if (streaming.value && childStatuses.includes('RUNNING')) return 'running'
    ...
    return childStatuses.length ? 'success' : ''

    When streaming ends but a tool status is still RUNNING, groupStatus falls through to 'success'. That avoids the spinner, but it may incorrectly display a successful group for an aborted/failed/incomplete stream.

    • Consider explicitly handling stale RUNNING:
      • Normalize tool statuses when streaming ends, or
      • Show an “unknown/incomplete” state instead of unconditional 'success'.
  3. Import path / circular dependency risk

    import { useMessageStreaming } from '../../../message-list'
    • Importing from a barrel/index module like message-list can create a circular dependency if that module indirectly imports this component.
    • Prefer importing directly from the composable file, and/or use the project alias, e.g. @/.../useMessageStreaming.
  4. Boolean prop type

    :loading="streaming && toolItem.status === 'RUNNING'"

    In templates, top-level refs are auto-unwrapped, so this is correct if streaming is a top-level Ref<boolean>. Do not change it to streaming.value in the template.

    • If streaming can be undefined, consider forcing a boolean:
      :loading="!!(streaming && toolItem.status === 'RUNNING')"
      or use a helper.

Optimization suggestion

Extract the repeated condition into a single helper to keep groupStatus and the template consistent:

const isToolRunning = (toolItem: ChatContent) =>
  streaming.value && toolItem.status === 'RUNNING'

Then:

const groupStatus = computed(() => {
  const childStatuses = toolItems.value.map((toolItem) => toolItem.status)

  if (toolItems.value.some(isToolRunning)) return 'running'
  if (childStatuses.some((s) => s === 'FAIL' || s === 'FAILURE')) return 'error'
  return childStatuses.length ? 'success' : ''
})
:loading="isToolRunning(toolItem)"

Minor notes

  • The .value usage inside computed is correct.
  • The template usage without .value is correct due to Vue ref auto-unwrapping.
  • Consider adding tests for:
    • streaming = true + tool RUNNING → spinner shown.
    • streaming = false + tool RUNNING → no spinner.
    • streaming = false + tool FAIL → error state.
    • Empty tool list → empty group status.

Main risk: using a possibly global streaming state and mapping stale RUNNING to success.

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