feat(chat): add a question outline for long overflowing sessions (#2839)

* feat(chat): add a question outline for long overflowing sessions

When the thread overflows, show a centered tick rail of loaded user questions on the right. Hover opens the list; click jumps to that message. Pure frontend, no API change.

* feat(chat): move question outline left with mountain hover and Q&A preview

Put the tick rail on the left inner edge. Hover grows nearby ticks like a mountain and shows a following card with that turn's question plus an answer preview.

* fix(chat): allow offsetTop on minimap tick mapping input

The type-check CI failed because tests pass measured items with offsetTop into mapQuestionTicks, which only accepted { id }.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
main
nullptr-error 2026-08-27 16:18:05 +08:00 committed by GitHub
parent 989907fe6e
commit 1f86e3e369
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 1170 additions and 38 deletions

View File

@ -0,0 +1,86 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
const component = readFileSync(new URL('./ChatQuestionMinimap.vue', import.meta.url), 'utf8')
const composable = readFileSync(new URL('../../composables/useChatQuestionMinimap.ts', import.meta.url), 'utf8')
test('does not render the rail until the thread overflows', () => {
assert.match(component, /v-if="visible"/)
})
test('opens a following Q&A card to the right of the left-side rail', () => {
assert.match(component, /question-minimap__panel/)
assert.match(component, /question-minimap__bridge/)
assert.match(component, /question-minimap__question/)
assert.match(component, /question-minimap__answer/)
assert.match(component, /CLOSE_DELAY_MS = 150/)
assert.match(component, /left: `\$\{RAIL_INSET_PX\}px`/)
assert.match(component, /top: `\$\{peakYPx\}px`/)
assert.doesNotMatch(component, /flex-direction: row-reverse/)
assert.doesNotMatch(component, /right: `\$\{scrollbarGutterPx \+ RAIL_INSET_PX\}px`/)
})
test('grows nearby ticks into a mountain under the pointer', () => {
assert.match(component, /tickMountainScale/)
assert.match(component, /nearestTickId/)
assert.match(component, /scaleX\(/)
assert.match(component, /handleRailPointerMove/)
})
test('centers the rail and panel in the thread instead of stretching top to bottom', () => {
assert.match(component, /top: 50%/)
assert.match(component, /transform: translateY\(-50%\)/)
assert.match(component, /height: `\$\{trackHeight\}px`/)
assert.doesNotMatch(component, /inset-block: 0/)
assert.doesNotMatch(component, /align-self: flex-start/)
assert.doesNotMatch(component, /height: min\(360px, 50%\)/)
assert.match(composable, /questionMinimapTrackHeight\(measured\.length, el\.clientHeight\)/)
})
test('jumps through data-message-id via the jump event', () => {
assert.match(component, /emit\('jump'/)
assert.match(component, /anchoredIds/)
})
test('uses chat question minimap i18n keys', () => {
assert.match(component, /chat\.questionMinimapTitle/)
assert.match(component, /chat\.questionMinimapAriaLabel/)
assert.match(component, /chat\.questionMinimapAttachmentPlaceholder/)
assert.match(component, /chat\.questionMinimapAnswerPending/)
})
test('wraps the overlay in navigation without overriding the rail button role', () => {
assert.match(component, /<nav[\s\S]*:aria-label="t\('chat\.questionMinimapAriaLabel'\)"/)
assert.doesNotMatch(component, /class="question-minimap__rail"[\s\S]{0,160}role="navigation"/)
assert.match(component, /aria-haspopup="dialog"/)
assert.match(component, /:aria-expanded="panelOpen"/)
})
test('keeps scroll-driven active question changes from clobbering keyboard navigation', () => {
assert.doesNotMatch(component, /watch\(activeId/)
})
test('does not draw a second scrollbar thumb next to the native scrollbar', () => {
assert.doesNotMatch(component, /question-minimap__viewport/)
assert.match(component, /RAIL_INSET_PX = 16/)
assert.match(component, /scrollbar-width: none/)
})
test('does not paint the first question green on hover-open', () => {
assert.match(component, /keyboardIndex\.value = -1/)
assert.doesNotMatch(component, /question-minimap__row--active/)
assert.doesNotMatch(component, /question-minimap__row:hover,\s*\.question-minimap__row--active/)
})
test('highlights the matching tick for the peaked question', () => {
assert.match(component, /peakId/)
assert.match(component, /tick\.id === peakId/)
})
test('uses only approved TDesign tokens in minimap styles', () => {
assert.doesNotMatch(component, /--td-brand-color-light/)
assert.doesNotMatch(component, /--td-border-level-2-color/)
assert.doesNotMatch(component, /--td-shadow-2/)
assert.doesNotMatch(component, /--td-text-color-primary/)
})

View File

@ -0,0 +1,392 @@
<template>
<nav
v-if="visible"
ref="rootRef"
class="question-minimap"
:style="{ left: `${RAIL_INSET_PX}px`, height: `${trackHeight}px` }"
:aria-label="t('chat.questionMinimapAriaLabel')"
@mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave"
>
<button
class="question-minimap__rail"
type="button"
tabindex="0"
:aria-label="t('chat.questionMinimapAriaLabel')"
aria-haspopup="dialog"
:aria-expanded="panelOpen"
@click="handleRailClick"
@keydown="handleRailKeydown"
@pointermove="handleRailPointerMove"
>
<span
v-for="tick in ticks"
:key="tick.id"
class="question-minimap__tick"
:class="{ 'question-minimap__tick--active': tick.id === peakId }"
:style="{
top: `${tick.yPx}px`,
transform: `translateY(-50%) scaleX(${tickMountainScale(tick.yPx, mountainPointerY)})`,
}"
/>
</button>
<div
v-if="panelOpen"
class="question-minimap__bridge"
aria-hidden="true"
/>
<section
v-if="panelOpen && peakTurn"
class="question-minimap__panel"
role="dialog"
:aria-label="t('chat.questionMinimapTitle')"
:style="{ top: `${peakYPx}px` }"
@click="handleQuestionClick(peakTurn.id)"
>
<p class="question-minimap__question" :title="questionText(peakTurn)">
{{ questionText(peakTurn) }}
</p>
<p class="question-minimap__answer">
{{ answerText(peakTurn) }}
</p>
</section>
</nav>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, toRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useChatQuestionMinimap } from '@/composables/useChatQuestionMinimap'
import {
answerPreviewText,
nearestTickId,
questionDisplayText,
tickMountainScale,
type ChatMessageLike,
type UserQuestion,
} from '@/utils/chatQuestionMinimap'
const CLOSE_DELAY_MS = 150
const RAIL_INSET_PX = 16
const props = defineProps<{
scrollContainer: HTMLElement | null
messages: ChatMessageLike[]
}>()
const emit = defineEmits<{
(event: 'jump', messageId: string): void
}>()
const { t } = useI18n()
const rootRef = ref<HTMLElement | null>(null)
const hoverOpen = ref(false)
const pinnedOpen = ref(false)
const hoveredId = ref<string | null>(null)
const pointerY = ref<number | null>(null)
const keyboardIndex = ref(-1)
const isCoarsePointer = ref(false)
const {
visible,
questions,
ticks,
activeId,
anchoredIds,
trackHeight,
} = useChatQuestionMinimap({
scrollContainer: toRef(props, 'scrollContainer'),
messages: toRef(props, 'messages'),
})
const panelOpen = computed(() => hoverOpen.value || pinnedOpen.value)
const anchoredQuestions = computed(() => (
questions.value.filter((question) => anchoredIds.value.has(question.id))
))
const peakId = computed(() => {
if (keyboardIndex.value >= 0) {
return questions.value[keyboardIndex.value]?.id ?? null
}
return hoveredId.value
})
const peakTurn = computed(() => (
questions.value.find((question) => question.id === peakId.value) ?? null
))
const peakYPx = computed(() => {
const tick = ticks.value.find((item) => item.id === peakId.value)
return tick?.yPx ?? 0
})
const mountainPointerY = computed(() => {
if (keyboardIndex.value >= 0) return peakYPx.value
return pointerY.value
})
let closeTimer: number | null = null
const questionText = (question: UserQuestion) => (
questionDisplayText(question.content, t('chat.questionMinimapAttachmentPlaceholder'))
)
const answerText = (question: UserQuestion) => (
answerPreviewText(question.answerContent, t('chat.questionMinimapAnswerPending'))
)
const clearCloseTimer = () => {
if (closeTimer === null) return
window.clearTimeout(closeTimer)
closeTimer = null
}
const openPanel = () => {
clearCloseTimer()
hoverOpen.value = true
keyboardIndex.value = -1
}
const closePanel = () => {
clearCloseTimer()
hoverOpen.value = false
pinnedOpen.value = false
hoveredId.value = null
pointerY.value = null
keyboardIndex.value = -1
}
const scheduleClose = () => {
clearCloseTimer()
closeTimer = window.setTimeout(() => {
hoverOpen.value = false
hoveredId.value = null
pointerY.value = null
closeTimer = null
}, CLOSE_DELAY_MS)
}
const syncKeyboardIndexToActive = () => {
const index = questions.value.findIndex((question) => question.id === activeId.value)
keyboardIndex.value = index >= 0 && anchoredIds.value.has(questions.value[index].id) ? index : -1
}
const handleMouseEnter = () => {
if (isCoarsePointer.value) return
openPanel()
}
const handleMouseLeave = () => {
if (isCoarsePointer.value) return
scheduleClose()
}
const handleRailPointerMove = (event: PointerEvent) => {
if (isCoarsePointer.value) return
const target = event.currentTarget as HTMLElement
pointerY.value = event.clientY - target.getBoundingClientRect().top
hoveredId.value = nearestTickId(ticks.value, pointerY.value)
}
const handleRailClick = () => {
if (!isCoarsePointer.value) {
const id = peakId.value
if (id) handleQuestionClick(id)
return
}
clearCloseTimer()
pinnedOpen.value = !pinnedOpen.value
hoverOpen.value = false
if (pinnedOpen.value) {
hoveredId.value = activeId.value ?? questions.value[0]?.id ?? null
}
}
const handleQuestionClick = (id: string) => {
if (!anchoredIds.value.has(id)) return
closePanel()
emit('jump', id)
}
const moveKeyboard = (direction: 1 | -1) => {
const anchored = anchoredQuestions.value
if (anchored.length === 0) return
const wasOpen = panelOpen.value
clearCloseTimer()
hoverOpen.value = true
if (!wasOpen) {
syncKeyboardIndexToActive()
}
const currentQuestion = questions.value[keyboardIndex.value]
const currentAnchoredIndex = currentQuestion
? anchored.findIndex((question) => question.id === currentQuestion.id)
: -1
const activeAnchoredIndex = anchored.findIndex((question) => question.id === activeId.value)
const startIndex = currentAnchoredIndex >= 0 ? currentAnchoredIndex : activeAnchoredIndex
const nextAnchoredIndex = Math.min(
anchored.length - 1,
Math.max(0, (startIndex >= 0 ? startIndex : 0) + direction),
)
const nextQuestion = anchored[nextAnchoredIndex]
keyboardIndex.value = questions.value.findIndex((question) => question.id === nextQuestion.id)
}
const jumpKeyboardQuestion = () => {
const question = peakTurn.value
if (!question || !anchoredIds.value.has(question.id)) return
closePanel()
emit('jump', question.id)
}
const handleRailKeydown = (event: KeyboardEvent) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
event.preventDefault()
moveKeyboard(1)
return
}
if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
event.preventDefault()
moveKeyboard(-1)
return
}
if (event.key === 'Enter') {
event.preventDefault()
jumpKeyboardQuestion()
return
}
if (event.key === 'Escape') {
event.preventDefault()
closePanel()
}
}
const handleDocumentPointerDown = (event: PointerEvent) => {
if (!isCoarsePointer.value || !panelOpen.value) return
const target = event.target as Node | null
if (target && rootRef.value?.contains(target)) return
closePanel()
}
onMounted(() => {
isCoarsePointer.value = window.matchMedia('(pointer: coarse)').matches
document.addEventListener('pointerdown', handleDocumentPointerDown)
})
onBeforeUnmount(() => {
clearCloseTimer()
document.removeEventListener('pointerdown', handleDocumentPointerDown)
})
</script>
<style scoped lang="less">
.question-minimap {
position: absolute;
top: 50%;
left: 0;
z-index: 11;
display: flex;
align-items: stretch;
transform: translateY(-50%);
pointer-events: none;
}
.question-minimap__rail,
.question-minimap__bridge,
.question-minimap__panel {
pointer-events: auto;
}
.question-minimap__rail {
position: relative;
width: 28px;
height: 100%;
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
}
.question-minimap__rail:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
}
.question-minimap__tick {
position: absolute;
left: 2px;
width: 8px;
height: 2px;
border-radius: 1px;
background: var(--td-text-color-secondary);
opacity: 0.55;
transform: translateY(-50%);
transform-origin: left center;
transition: transform 120ms ease-out, background 120ms ease-out, opacity 120ms ease-out;
}
.question-minimap__tick--active {
background: var(--td-brand-color);
opacity: 1;
}
.question-minimap__bridge {
width: 8px;
}
.question-minimap__panel {
position: absolute;
left: 36px;
width: 240px;
max-height: min(360px, 50vh);
padding: 8px 10px;
overflow: hidden;
scrollbar-width: none;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-container);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transform: translateY(-50%);
cursor: pointer;
}
.question-minimap__panel::-webkit-scrollbar {
display: none;
}
.question-minimap__question,
.question-minimap__answer {
margin: 0;
color: var(--td-text-color-secondary);
font: inherit;
}
.question-minimap__question {
overflow: hidden;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.question-minimap__answer {
display: -webkit-box;
margin-top: 4px;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
opacity: 0.75;
}
@media (prefers-reduced-motion: reduce) {
.question-minimap__tick {
transition: none;
}
}
</style>

View File

@ -0,0 +1,186 @@
import {
computed,
onBeforeUnmount,
onMounted,
ref,
toValue,
watch,
type ComputedRef,
type Ref,
} from 'vue'
import {
activeQuestionId,
collectUserQuestions,
isChatOverflowing,
mapQuestionTicks,
offsetFromScrollContent,
questionMinimapTrackHeight,
shouldShowQuestionMinimap,
viewportBand,
type ChatMessageLike,
type QuestionTick,
type UserQuestion,
type ViewportBand,
} from '@/utils/chatQuestionMinimap'
export function useChatQuestionMinimap(options: {
scrollContainer: Ref<HTMLElement | null>
messages: ChatMessageLike[] | Ref<ChatMessageLike[]>
}): {
visible: ComputedRef<boolean>
questions: ComputedRef<UserQuestion[]>
ticks: Ref<QuestionTick[]>
viewport: Ref<ViewportBand>
activeId: Ref<string | null>
anchoredIds: Ref<Set<string>>
scrollbarGutterPx: Ref<number>
trackHeight: Ref<number>
} {
const questions = computed(() => collectUserQuestions(toValue(options.messages)))
const overflowing = ref(false)
const ticks = ref<QuestionTick[]>([])
const viewport = ref<ViewportBand>({ topPx: 0, heightPx: 0 })
const activeId = ref<string | null>(null)
const anchoredIds = ref<Set<string>>(new Set())
const scrollbarGutterPx = ref(0)
const trackHeight = ref(0)
const visible = computed(() => (
shouldShowQuestionMinimap(overflowing.value, questions.value.length)
))
let resizeObserver: ResizeObserver | null = null
let observedContainer: HTMLElement | null = null
let observedContent: Element | null = null
let frameId: number | null = null
const reset = () => {
overflowing.value = false
ticks.value = []
viewport.value = { topPx: 0, heightPx: 0 }
activeId.value = null
anchoredIds.value = new Set()
scrollbarGutterPx.value = 0
trackHeight.value = 0
}
const disconnectObserver = () => {
resizeObserver?.disconnect()
resizeObserver = null
observedContainer = null
observedContent = null
}
const measureNow = () => {
const el = options.scrollContainer.value
if (!el) {
reset()
return
}
overflowing.value = isChatOverflowing(el.scrollHeight, el.clientHeight)
const anchors = Array.from(el.querySelectorAll<HTMLElement>('[data-message-id]'))
const anchorByMessageId = new Map<string, HTMLElement>()
for (const anchor of anchors) {
const messageId = anchor.dataset.messageId
if (messageId) anchorByMessageId.set(messageId, anchor)
}
const containerTop = el.getBoundingClientRect().top
scrollbarGutterPx.value = Math.max(0, el.offsetWidth - el.clientWidth)
const measured = questions.value.flatMap((question) => {
const anchor = anchorByMessageId.get(question.id)
if (!anchor) return []
return [{
id: question.id,
offsetTop: offsetFromScrollContent(
anchor.getBoundingClientRect().top,
containerTop,
el.scrollTop,
),
}]
})
trackHeight.value = questionMinimapTrackHeight(measured.length, el.clientHeight)
ticks.value = mapQuestionTicks(measured, trackHeight.value)
viewport.value = viewportBand(el.scrollTop, el.clientHeight, el.scrollHeight, trackHeight.value)
activeId.value = activeQuestionId(measured, el.scrollTop)
anchoredIds.value = new Set(measured.map((item) => item.id))
}
const scheduleMeasure = () => {
if (frameId !== null) return
frameId = window.requestAnimationFrame(() => {
frameId = null
measureNow()
})
}
const observeCurrentContainer = () => {
const el = options.scrollContainer.value
if (!el || typeof ResizeObserver === 'undefined') return
const content = el.firstElementChild
if (resizeObserver && observedContainer === el && observedContent === content) return
disconnectObserver()
resizeObserver = new ResizeObserver(scheduleMeasure)
resizeObserver.observe(el)
if (content) resizeObserver.observe(content)
observedContainer = el
observedContent = content
}
const bind = () => {
const el = options.scrollContainer.value
if (!el) {
disconnectObserver()
reset()
return
}
el.addEventListener('scroll', scheduleMeasure, { passive: true })
window.addEventListener('resize', scheduleMeasure)
observeCurrentContainer()
scheduleMeasure()
}
const unbind = (el: HTMLElement | null) => {
el?.removeEventListener('scroll', scheduleMeasure)
window.removeEventListener('resize', scheduleMeasure)
disconnectObserver()
}
watch(options.scrollContainer, (el, previousEl) => {
unbind(previousEl)
if (el) bind()
else reset()
}, { flush: 'post' })
watch(questions, () => {
observeCurrentContainer()
scheduleMeasure()
}, { flush: 'post' })
onMounted(bind)
onBeforeUnmount(() => {
unbind(options.scrollContainer.value)
if (frameId !== null) {
window.cancelAnimationFrame(frameId)
frameId = null
}
})
return {
visible,
questions,
ticks,
viewport,
activeId,
anchoredIds,
scrollbarGutterPx,
trackHeight,
}
}

View File

@ -3235,6 +3235,10 @@ export default {
referencesDrawerDocsSection: 'Documents',
referencesDrawerToolsSection: 'Tools',
referencesDrawerEmpty: 'No sources available',
questionMinimapTitle: 'Questions',
questionMinimapAriaLabel: 'Question outline',
questionMinimapAttachmentPlaceholder: '(Attachment)',
questionMinimapAnswerPending: 'Generating',
referenceChunkCount: '{count} chunk(s)',
fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.',
requestInfoTitle: 'Request info',

View File

@ -3252,6 +3252,10 @@ export default {
referencesDrawerDocsSection: '지식베이스 문서',
referencesDrawerToolsSection: '도구',
referencesDrawerEmpty: '참고 출처가 없습니다',
questionMinimapTitle: '질문',
questionMinimapAriaLabel: '질문 목차',
questionMinimapAttachmentPlaceholder: '(첨부)',
questionMinimapAnswerPending: '생성 중',
referenceChunkCount: '{count}개 청크',
fallbackHint: '지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.',
requestInfoTitle: 'Request info',

View File

@ -3252,6 +3252,10 @@ export default {
referencesDrawerDocsSection: 'Документы базы знаний',
referencesDrawerToolsSection: 'Инструменты',
referencesDrawerEmpty: 'Источники отсутствуют',
questionMinimapTitle: 'Вопросы',
questionMinimapAriaLabel: 'Содержание вопросов',
questionMinimapAttachmentPlaceholder: '(Вложение)',
questionMinimapAnswerPending: 'Генерация',
referenceChunkCount: '{count} фрагмент(ов)',
fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.',
requestInfoTitle: 'Request info',

View File

@ -3254,6 +3254,10 @@ export default {
referencesDrawerDocsSection: '知识库文档',
referencesDrawerToolsSection: '工具',
referencesDrawerEmpty: '暂无参考来源',
questionMinimapTitle: '提问',
questionMinimapAriaLabel: '提问目录',
questionMinimapAttachmentPlaceholder: '(附件)',
questionMinimapAnswerPending: '生成中',
referenceChunkCount: '{count}个片段',
fallbackHint: '未从知识库中检索到相关内容,以上为模型直接回答',
requestInfoTitle: '请求信息',

View File

@ -0,0 +1,166 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
ACTIVE_QUESTION_TOP_OFFSET_PX,
QUESTION_MINIMAP_TRACK_MAX_PX,
QUESTION_TICK_GAP_PX,
QUESTION_TICK_MOUNTAIN_GAIN,
activeQuestionId,
answerPreviewText,
collectUserQuestions,
isChatOverflowing,
mapQuestionTicks,
nearestTickId,
offsetFromScrollContent,
questionDisplayText,
questionMinimapTrackHeight,
shouldShowQuestionMinimap,
tickMountainScale,
viewportBand,
} from './chatQuestionMinimap.ts'
test('isChatOverflowing is false when content fits or matches the viewport', () => {
assert.equal(isChatOverflowing(800, 800), false)
assert.equal(isChatOverflowing(799, 800), false)
assert.equal(isChatOverflowing(801, 800), true)
})
test('questionMinimapTrackHeight packs ticks with a small gap instead of filling the rail', () => {
assert.equal(questionMinimapTrackHeight(1, 800), QUESTION_TICK_GAP_PX)
assert.equal(questionMinimapTrackHeight(3, 800), 2 * QUESTION_TICK_GAP_PX)
assert.equal(questionMinimapTrackHeight(0, 800), 0)
assert.equal(questionMinimapTrackHeight(3, 0), 0)
})
test('questionMinimapTrackHeight still caps a long cluster to the centered rail', () => {
assert.equal(questionMinimapTrackHeight(100, 800), QUESTION_MINIMAP_TRACK_MAX_PX)
assert.equal(questionMinimapTrackHeight(100, 400), 200)
})
test('shouldShowQuestionMinimap requires overflow and at least one question', () => {
assert.equal(shouldShowQuestionMinimap(true, 1), true)
assert.equal(shouldShowQuestionMinimap(true, 0), false)
assert.equal(shouldShowQuestionMinimap(false, 4), false)
})
test('collectUserQuestions keeps loaded user turns with ids, in list order', () => {
const questions = collectUserQuestions([
{ role: 'assistant', id: 'a1', content: 'hi' },
{ role: 'user', content: 'no id yet' },
{ role: 'user', id: 'u1', content: 'first', images: [{}] },
{ role: 'assistant', id: 'a2', content: 'answer one' },
{ role: 'user', id: 'u2', content: ' ', attachments: [{}] },
])
assert.deepEqual(
questions.map((q) => ({ id: q.id, hasAttachments: q.hasAttachments, answerContent: q.answerContent })),
[
{ id: 'u1', hasAttachments: true, answerContent: 'answer one' },
{ id: 'u2', hasAttachments: true, answerContent: '' },
],
)
})
test('answerPreviewText strips markdown and uses the pending placeholder when empty', () => {
assert.equal(
answerPreviewText('## Hello\n**world** and [link](https://x)', '生成中'),
'Hello world and link',
)
assert.equal(answerPreviewText(' ', '生成中'), '生成中')
assert.equal(answerPreviewText(undefined, '生成中'), '生成中')
})
test('tickMountainScale is 1 without a pointer and peaks at the hovered tick', () => {
assert.equal(tickMountainScale(100, null), 1)
assert.equal(tickMountainScale(100, 100), 1 + QUESTION_TICK_MOUNTAIN_GAIN)
assert.ok(tickMountainScale(100, 100) > tickMountainScale(135, 100))
assert.ok(tickMountainScale(135, 100) > tickMountainScale(200, 100))
})
test('nearestTickId picks the closest tick to the pointer', () => {
const ticks = [
{ id: 'u1', yPx: 10 },
{ id: 'u2', yPx: 45 },
{ id: 'u3', yPx: 80 },
]
assert.equal(nearestTickId(ticks, 12), 'u1')
assert.equal(nearestTickId(ticks, 50), 'u2')
assert.equal(nearestTickId([], 10), null)
})
test('questionDisplayText uses trimmed content, else the placeholder', () => {
assert.equal(questionDisplayText(' hello\nworld ', '(附件)'), 'hello world')
assert.equal(questionDisplayText(' ', '(附件)'), '(附件)')
assert.equal(questionDisplayText(undefined, '(附件)'), '(附件)')
})
test('offsetFromScrollContent is viewport-relative plus scrollTop', () => {
assert.equal(offsetFromScrollContent(120, 40, 80), 160)
})
test('mapQuestionTicks clusters ticks in the center with a compact equal gap', () => {
const ticks = mapQuestionTicks(
[
{ id: 'u1' },
{ id: 'u2' },
{ id: 'u3' },
],
200,
)
assert.equal(ticks[1].yPx - ticks[0].yPx, QUESTION_TICK_GAP_PX)
assert.equal(ticks[2].yPx - ticks[1].yPx, QUESTION_TICK_GAP_PX)
assert.equal((ticks[0].yPx + ticks[2].yPx) / 2, 100)
})
test('mapQuestionTicks ignores message offsets and keeps equal gaps', () => {
const ticks = mapQuestionTicks(
[
{ id: 'u1', offsetTop: 0 },
{ id: 'u2', offsetTop: 2 },
],
200,
)
assert.equal(ticks[1].yPx - ticks[0].yPx, QUESTION_TICK_GAP_PX)
assert.equal((ticks[0].yPx + ticks[1].yPx) / 2, 100)
})
test('mapQuestionTicks still fits many ticks inside a short rail', () => {
const ticks = mapQuestionTicks(
[
{ id: 'a' },
{ id: 'b' },
{ id: 'c' },
{ id: 'd' },
],
20,
)
assert.equal(ticks.length, 4)
assert.ok(ticks[0].yPx >= 0)
assert.ok(ticks[3].yPx <= 20)
const gap = ticks[1].yPx - ticks[0].yPx
for (let i = 1; i < ticks.length; i++) {
assert.ok(Math.abs(ticks[i].yPx - ticks[i - 1].yPx - gap) < 1e-9)
}
})
test('viewportBand maps the visible window onto the track with a 16px floor', () => {
const band = viewportBand(250, 250, 1000, 200)
assert.equal(band.topPx, 50)
assert.equal(band.heightPx, 50)
const tiny = viewportBand(0, 10, 1000, 200)
assert.equal(tiny.topPx, 0)
assert.equal(tiny.heightPx, 16)
})
test('activeQuestionId picks the last question at or above the top offset', () => {
const items = [
{ id: 'u1', offsetTop: 0 },
{ id: 'u2', offsetTop: 400 },
{ id: 'u3', offsetTop: 800 },
]
assert.equal(activeQuestionId(items, 0), 'u1')
assert.equal(activeQuestionId(items, 400 - ACTIVE_QUESTION_TOP_OFFSET_PX), 'u2')
assert.equal(activeQuestionId(items, 900), 'u3')
assert.equal(activeQuestionId([], 0), null)
})

View File

@ -0,0 +1,224 @@
export const QUESTION_TICK_RADIUS_PX = 3
export const QUESTION_TICK_GAP_PX = 35
export const QUESTION_TICK_MOUNTAIN_GAIN = 2.2
export const ACTIVE_QUESTION_TOP_OFFSET_PX = 72
export const VIEWPORT_BAND_MIN_HEIGHT_PX = 16
export const QUESTION_MINIMAP_TRACK_MAX_PX = 360
export const QUESTION_MINIMAP_TRACK_RATIO = 0.5
export function questionMinimapTrackHeight(
questionCount: number,
clientHeight: number,
): number {
if (questionCount <= 0 || clientHeight <= 0) return 0
const maxHeight = Math.min(
QUESTION_MINIMAP_TRACK_MAX_PX,
clientHeight * QUESTION_MINIMAP_TRACK_RATIO,
)
const naturalHeight = questionCount === 1
? QUESTION_TICK_GAP_PX
: (questionCount - 1) * QUESTION_TICK_GAP_PX
return Math.min(naturalHeight, maxHeight)
}
export type ChatMessageLike = {
id?: string
role?: string
content?: string
images?: unknown[]
attachments?: unknown[]
}
export type UserQuestion = {
id: string
content: string
hasAttachments: boolean
answerContent: string
}
export type QuestionTick = {
id: string
yRatio: number
yPx: number
}
export type ViewportBand = {
topPx: number
heightPx: number
}
export function isChatOverflowing(scrollHeight: number, clientHeight: number): boolean {
return scrollHeight > clientHeight
}
export function shouldShowQuestionMinimap(overflowing: boolean, questionCount: number): boolean {
return overflowing && questionCount >= 1
}
export function collectUserQuestions(messages: ChatMessageLike[]): UserQuestion[] {
const questions: UserQuestion[] = []
for (let index = 0; index < messages.length; index++) {
const message = messages[index]
if (message.role !== 'user' || !message.id) continue
let answerContent = ''
for (let next = index + 1; next < messages.length; next++) {
const following = messages[next]
if (following.role === 'user') break
if (following.role === 'assistant') {
answerContent = following.content ?? ''
break
}
}
questions.push({
id: message.id,
content: message.content ?? '',
hasAttachments:
(message.images?.length ?? 0) > 0 || (message.attachments?.length ?? 0) > 0,
answerContent,
})
}
return questions
}
export function questionDisplayText(
content: string | undefined,
attachmentPlaceholder: string,
): string {
const normalized = (content ?? '').replace(/\s+/g, ' ').trim()
return normalized.length > 0 ? normalized : attachmentPlaceholder
}
export function answerPreviewText(
content: string | undefined,
pendingPlaceholder: string,
): string {
const normalized = (content ?? '')
.replace(/```[\s\S]*?```/g, ' ')
.replace(/`([^`]+)`/g, '$1')
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
.replace(/[#>*_~-]+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
return normalized.length > 0 ? normalized : pendingPlaceholder
}
export function tickMountainScale(tickY: number, pointerY: number | null): number {
if (pointerY === null) return 1
const dy = tickY - pointerY
const sigma = QUESTION_TICK_GAP_PX
return 1 + QUESTION_TICK_MOUNTAIN_GAIN * Math.exp(-0.5 * (dy / sigma) ** 2)
}
export function nearestTickId(
ticks: Array<{ id: string; yPx: number }>,
pointerY: number,
): string | null {
if (ticks.length === 0) return null
let bestId = ticks[0].id
let bestDist = Math.abs(ticks[0].yPx - pointerY)
for (let index = 1; index < ticks.length; index++) {
const dist = Math.abs(ticks[index].yPx - pointerY)
if (dist < bestDist) {
bestDist = dist
bestId = ticks[index].id
}
}
return bestId
}
export function offsetFromScrollContent(
anchorTop: number,
containerTop: number,
scrollTop: number,
): number {
return anchorTop - containerTop + scrollTop
}
export function mapQuestionTicks(
items: Array<{ id: string; offsetTop?: number }>,
trackHeight: number,
): QuestionTick[] {
const n = items.length
if (n === 0 || trackHeight <= 0) {
return []
}
if (n === 1) {
return [{
id: items[0].id,
yRatio: 0.5,
yPx: trackHeight / 2,
}]
}
const preferredSpan = (n - 1) * QUESTION_TICK_GAP_PX
const minY = Math.min(QUESTION_TICK_RADIUS_PX, trackHeight / 2)
const maxY = Math.max(minY, trackHeight - minY)
const available = maxY - minY
const span = preferredSpan <= trackHeight ? preferredSpan : available
const start = (trackHeight - span) / 2
return items.map((item, index) => {
const yRatio = index / (n - 1)
return {
id: item.id,
yRatio,
yPx: start + yRatio * span,
}
})
}
export function viewportBand(
scrollTop: number,
clientHeight: number,
scrollHeight: number,
trackHeight: number,
minHeightPx: number = VIEWPORT_BAND_MIN_HEIGHT_PX,
): ViewportBand {
if (scrollHeight <= 0 || trackHeight <= 0) {
return { topPx: 0, heightPx: minHeightPx }
}
let topPx = (scrollTop / scrollHeight) * trackHeight
let heightPx = Math.max(minHeightPx, (clientHeight / scrollHeight) * trackHeight)
heightPx = Math.min(heightPx, trackHeight)
if (topPx + heightPx > trackHeight) {
topPx = trackHeight - heightPx
}
topPx = Math.max(0, topPx)
if (topPx + heightPx > trackHeight) {
heightPx = trackHeight - topPx
}
return { topPx, heightPx }
}
export function activeQuestionId(
items: Array<{ id: string; offsetTop: number }>,
scrollTop: number,
topOffsetPx: number = ACTIVE_QUESTION_TOP_OFFSET_PX,
): string | null {
if (items.length === 0) {
return null
}
const threshold = scrollTop + topOffsetPx
let activeId: string | null = null
for (const item of items) {
if (item.offsetTop <= threshold) {
activeId = item.id
}
}
return activeId ?? items[0].id
}

View File

@ -5,8 +5,9 @@
'has-references-panel': referencesDrawerVisible,
}">
<ChatHeader v-if="!embeddedMode" :session="currentSession" :has-references-panel="referencesDrawerVisible" />
<div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll">
<div class="msg_list" :class="{ 'is-embedded': embeddedMode }">
<div class="chat_thread">
<div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll">
<div class="msg_list" :class="{ 'is-embedded': embeddedMode }">
<!-- 消息列表骨架屏 -->
<div v-if="historyLoading && messagesList.length === 0" class="msg-skeleton-list">
<div class="msg-skeleton msg-skeleton-user">
@ -73,40 +74,49 @@
这是历史加载时白屏 + layout shift 蔓延到 session 列表的根因。
仅对极少数尚未拿到 id 的本地占位消息 fallback 到 role+created_at+index。
-->
<div v-for="(session, index) in messagesList"
:key="session.id || `${session.role}-${session.created_at}-${index}`" class="msg-item-wrapper">
<MessageTimestamp v-if="shouldShowConversationTimestamp(messagesList, index)"
:value="session.created_at" />
<div v-for="(session, index) in messagesList"
:key="session.id || `${session.role}-${session.created_at}-${index}`" class="msg-item-wrapper">
<MessageTimestamp v-if="shouldShowConversationTimestamp(messagesList, index)"
:value="session.created_at" />
<div v-if="session.role == 'user'" class="message-row">
<usermsg :content="session.content" :mentioned_items="session.mentioned_items"
:images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode"
:session-id="session_id">
</usermsg>
<div v-if="session.role == 'user'" class="message-row"
:data-message-id="session.id || undefined"
:class="{ 'is-minimap-target': session.id && session.id === minimapTargetId }">
<usermsg :content="session.content" :mentioned_items="session.mentioned_items"
:images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode"
:session-id="session_id">
</usermsg>
</div>
<div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)"
class="message-row">
<botmsg :content="session.content" :session="session" :session-id="session_id"
:user-query="getUserQuery(index)" @scroll-bottom="scrollToBottom"
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"
:follow-up-loading="Boolean(session.suggestionLoading && !session.suggestionSet?.questions?.length)"
@render-complete-change="(ready) => handleAnswerRenderComplete(session, ready)">
</botmsg>
<FollowUpSuggestions v-if="session.answerFullyRendered && !session.suggestionsDismissed"
:suggestion-set="session.suggestionSet"
:loading="session.suggestionLoading"
:allow-regenerate="session.suggestionSet?.allow_regenerate"
@select="(item) => handleFollowUpSelect(session, item)"
@regenerate="loadFollowUpSuggestions(session, true, true)"
@impression="(set) => recordSuggestionEvent(session, set, 'impression')"
@dismiss="(set) => dismissSuggestions(session, set)" />
</div>
</div>
<div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)"
class="message-row">
<botmsg :content="session.content" :session="session" :session-id="session_id"
:user-query="getUserQuery(index)" @scroll-bottom="scrollToBottom"
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"
:follow-up-loading="Boolean(session.suggestionLoading && !session.suggestionSet?.questions?.length)"
@render-complete-change="(ready) => handleAnswerRenderComplete(session, ready)">
</botmsg>
<FollowUpSuggestions v-if="session.answerFullyRendered && !session.suggestionsDismissed"
:suggestion-set="session.suggestionSet"
:loading="session.suggestionLoading"
:allow-regenerate="session.suggestionSet?.allow_regenerate"
@select="(item) => handleFollowUpSelect(session, item)"
@regenerate="loadFollowUpSuggestions(session, true, true)"
@impression="(set) => recordSuggestionEvent(session, set, 'impression')"
@dismiss="(set) => dismissSuggestions(session, set)" />
<div v-if="showGlobalTypingIndicator" class="chat-global-wait" role="status"
:aria-label="t('chat.thinkingAlt')">
<span class="chat-global-wait__spinner" aria-hidden="true"></span>
</div>
</div>
<div v-if="showGlobalTypingIndicator" class="chat-global-wait" role="status"
:aria-label="t('chat.thinkingAlt')">
<span class="chat-global-wait__spinner" aria-hidden="true"></span>
</div>
</div>
<ChatQuestionMinimap
v-if="!embeddedMode"
:scroll-container="scrollContainer"
:messages="messagesList"
@jump="jumpToQuestion"
/>
</div>
<transition name="scroll-btn-fade">
<div v-show="userHasScrolledUp" class="scroll-to-bottom-btn" @click="onClickScrollToBottom">
@ -151,6 +161,7 @@ import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue';
import ChatAttachmentPreviewDrawer from '@/components/ChatAttachmentPreviewDrawer.vue';
import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue';
import MessageTimestamp from '@/components/chat/MessageTimestamp.vue';
import ChatQuestionMinimap from '@/components/chat/ChatQuestionMinimap.vue';
import { shouldShowConversationTimestamp } from '@/utils/messageTimestamp';
import ChatHeader from '@/components/ChatHeader.vue';
import {
@ -267,6 +278,8 @@ let fullContent = ref('')
const scrollContainer = ref(null)
const userHasScrolledUp = ref(false)
const SCROLL_BOTTOM_THRESHOLD = 80
const minimapTargetId = ref('')
let minimapFlashTimer = null
const isNearBottom = () => {
if (!scrollContainer.value) return true;
@ -274,6 +287,34 @@ const isNearBottom = () => {
return scrollHeight - scrollTop - clientHeight < SCROLL_BOTTOM_THRESHOLD;
}
const clearMinimapFlash = () => {
if (minimapFlashTimer) {
clearTimeout(minimapFlashTimer)
minimapFlashTimer = null
}
minimapTargetId.value = ''
}
const jumpToQuestion = (id) => {
const root = scrollContainer.value
if (!root || !id) return
const el = root.querySelector(`[data-message-id="${CSS.escape(id)}"]`)
if (!el) return
const offset = el.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop
const nearEnd = root.scrollHeight - offset < root.clientHeight + SCROLL_BOTTOM_THRESHOLD
userHasScrolledUp.value = !nearEnd
el.scrollIntoView({ block: 'start', behavior: 'smooth' })
minimapTargetId.value = id
if (minimapFlashTimer) clearTimeout(minimapFlashTimer)
minimapFlashTimer = setTimeout(() => {
minimapTargetId.value = ''
minimapFlashTimer = null
}, 1200)
}
const handleKBEditorSuccess = (kbId) => {
navigateToKnowledgeBaseList(kbId)
}
@ -1004,12 +1045,14 @@ const clearData = () => {
referencesDrawer.close();
isReplying.value = false;
fullContent.value = '';
clearMinimapFlash();
// Stop any IM-reply recovery poll for the session we're leaving/switching.
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
isImRecovering.value = false;
}
onUnmounted(() => {
window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);
clearMinimapFlash();
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
});
onBeforeRouteLeave((to, from, next) => {
@ -1034,8 +1077,8 @@ onBeforeRouteUpdate((to, from, next) => {
flex: 1;
// The parent .platform-route-outlet is a flex column with min-height:0
// and overflow:hidden — we also need min-height:0 here so that our
// own flex:1 child (.chat_scroll_box) can shrink below its content
// height and scroll instead of pushing .input-container out of view.
// own flex:1 child (.chat_thread) can shrink below its content
// height and keep the input container in view.
min-height: 0;
position: relative;
display: flex;
@ -1102,13 +1145,18 @@ onBeforeRouteUpdate((to, from, next) => {
}
}
.chat_thread {
position: relative;
flex: 1;
min-height: 0;
width: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
.chat_scroll_box {
flex: 1;
// Without min-height: 0, a flex-column child defaults to min-height: auto
// and expands to fit all inner content. When there are many messages,
// that pushes .input-container out of the viewport. Clamping min-height
// to 0 lets overflow-y: auto take effect so the messages scroll inside
// this box instead of stretching it.
min-height: 0;
width: 100%;
padding-top: 8px;
@ -1257,6 +1305,10 @@ onBeforeRouteUpdate((to, from, next) => {
display: flex;
flex-direction: column;
width: 100%;
&.is-minimap-target {
animation: minimap-target-flash 1.2s ease;
}
}
.botanswer_laoding_gif {
@ -1289,6 +1341,16 @@ onBeforeRouteUpdate((to, from, next) => {
}
}
@keyframes minimap-target-flash {
0% {
background: color-mix(in srgb, var(--td-brand-color) 18%, transparent);
}
100% {
background: transparent;
}
}
@media (prefers-reduced-motion: reduce) {
.chat-global-wait__spinner {
animation: none;