fix(chat): insert timestamps as conversation flow dividers

Show a centered ChatGPT-style time marker between turns instead of
under every bubble, so thinking steps no longer sit on a dangling clock.
main
wizardchen 2026-08-24 18:28:53 +08:00 committed by lyingbug
parent 3842068d22
commit 1426ec77ac
10 changed files with 210 additions and 23 deletions

View File

@ -1,37 +1,47 @@
<template>
<time v-if="label" class="message-time" :class="alignClass" :datetime="datetime">{{ label }}</time>
<time v-if="label" class="conversation-time" :datetime="datetime">{{ label }}</time>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { formatMessageTimestamp, normalizeMessageCreatedAt } from '@/utils/messageTimestamp'
import { useI18n } from 'vue-i18n'
import { getConversationTimestampModel } from '@/utils/messageTimestamp'
const props = defineProps<{
value?: unknown
align?: 'start' | 'end'
}>()
const datetime = computed(() => normalizeMessageCreatedAt(props.value))
const label = computed(() => formatMessageTimestamp(props.value))
const alignClass = computed(() =>
props.align === 'end' ? 'message-time--end' : 'message-time--start',
)
const { t } = useI18n()
const model = computed(() => getConversationTimestampModel(props.value))
const datetime = computed(() => model.value?.datetime ?? '')
const label = computed(() => {
const next = model.value
if (!next) return ''
if (next.kind === 'today') return t('chat.conversationTime.today', { time: next.time })
if (next.kind === 'yesterday') return t('chat.conversationTime.yesterday', { time: next.time })
if (next.kind === 'thisYear') {
return t('chat.conversationTime.thisYear', { month: next.month, day: next.day, time: next.time })
}
return t('chat.conversationTime.otherYear', {
year: next.year,
month: next.month,
day: next.day,
time: next.time,
})
})
</script>
<style scoped lang="less">
.message-time {
margin-top: 4px;
color: var(--td-text-color-secondary);
.conversation-time {
display: block;
width: 100%;
padding: 4px 0 8px;
color: var(--td-text-color-placeholder);
font-size: 12px;
font-variant-numeric: tabular-nums;
line-height: 20px;
}
.message-time--start {
align-self: flex-start;
}
.message-time--end {
align-self: flex-end;
text-align: center;
user-select: none;
}
</style>

View File

@ -3047,6 +3047,12 @@ export default {
refreshSuggestedQuestions: 'More',
thinking: 'Thinking...',
thinkingAlt: 'Thinking in progress',
conversationTime: {
today: 'Today {time}',
yesterday: 'Yesterday {time}',
thisYear: '{month}/{day} {time}',
otherYear: '{month}/{day}/{year} {time}',
},
preparingAnswer: 'Preparing an answer…',
connectingModelAndGeneratingAnswer: 'Connecting to the model and generating an answer…',
modelStillResponding: 'The model is taking longer than usual, still waiting…',

View File

@ -3211,6 +3211,12 @@ export default {
refreshSuggestedQuestions: '다른 질문',
thinking: '생각 중...',
thinkingAlt: '생각 중',
conversationTime: {
today: '오늘 {time}',
yesterday: '어제 {time}',
thisYear: '{month}월 {day}일 {time}',
otherYear: '{year}년 {month}월 {day}일 {time}',
},
preparingAnswer: '답변을 준비하고 있습니다…',
connectingModelAndGeneratingAnswer: '모델에 연결하여 답변을 생성하고 있습니다…',
modelStillResponding: '모델 응답이 평소보다 오래 걸리고 있습니다. 계속 기다리는 중…',

View File

@ -3211,6 +3211,12 @@ export default {
refreshSuggestedQuestions: 'Ещё',
thinking: 'Думаю...',
thinkingAlt: 'Обдумывание...',
conversationTime: {
today: 'Сегодня {time}',
yesterday: 'Вчера {time}',
thisYear: '{day}.{month} {time}',
otherYear: '{day}.{month}.{year} {time}',
},
preparingAnswer: 'Подготовка ответа…',
connectingModelAndGeneratingAnswer: 'Подключение к модели и создание ответа…',
modelStillResponding: 'Модель отвечает дольше обычного, продолжаем ждать…',

View File

@ -3213,6 +3213,12 @@ export default {
refreshSuggestedQuestions: '换一批',
thinking: '思考中...',
thinkingAlt: '正在思考',
conversationTime: {
today: '今天 {time}',
yesterday: '昨天 {time}',
thisYear: '{month}月{day}日 {time}',
otherYear: '{year}年{month}月{day}日 {time}',
},
preparingAnswer: '正在准备回答…',
connectingModelAndGeneratingAnswer: '正在连接模型并生成回答…',
modelStillResponding: '模型响应较慢,仍在等待…',

View File

@ -5,7 +5,10 @@ import {
bindServerTurnTimestamps,
ensureMessageCreatedAt,
formatMessageTimestamp,
getConversationTimestampModel,
normalizeMessageCreatedAt,
shouldInsertConversationTimestamp,
shouldShowConversationTimestamp,
} from './messageTimestamp'
test('normalizeMessageCreatedAt accepts parseable timestamps and rejects junk', () => {
@ -130,3 +133,57 @@ test('formatMessageTimestamp hides empty and invalid timestamps', () => {
assert.equal(formatMessageTimestamp('not-a-date'), '')
assert.equal(formatMessageTimestamp(undefined), '')
})
test('getConversationTimestampModel classifies today yesterday and older dates', () => {
const now = new Date(2026, 7, 24, 18, 21, 0)
const today = getConversationTimestampModel(new Date(2026, 7, 24, 16, 5, 0).toISOString(), now)
const yesterday = getConversationTimestampModel(new Date(2026, 7, 23, 9, 8, 0).toISOString(), now)
const thisYear = getConversationTimestampModel(new Date(2026, 0, 2, 3, 4, 0).toISOString(), now)
const otherYear = getConversationTimestampModel(new Date(2025, 11, 31, 23, 59, 0).toISOString(), now)
assert.deepEqual(today, {
datetime: new Date(2026, 7, 24, 16, 5, 0).toISOString(),
kind: 'today',
time: '16:05',
year: 2026,
month: 8,
day: 24,
})
assert.equal(yesterday?.kind, 'yesterday')
assert.equal(yesterday?.time, '09:08')
assert.equal(thisYear?.kind, 'thisYear')
assert.equal(thisYear?.month, 1)
assert.equal(thisYear?.day, 2)
assert.equal(otherYear?.kind, 'otherYear')
assert.equal(otherYear?.year, 2025)
assert.equal(getConversationTimestampModel(''), null)
})
test('shouldInsertConversationTimestamp opens a new group on first message and long gaps', () => {
const firstUser = { role: 'user', created_at: new Date(2026, 7, 24, 16, 5, 0).toISOString() }
const assistantSameTurn = { role: 'assistant', created_at: new Date(2026, 7, 24, 16, 5, 20).toISOString() }
const nextUserSoon = { role: 'user', created_at: new Date(2026, 7, 24, 16, 8, 0).toISOString() }
const nextUserLater = { role: 'user', created_at: new Date(2026, 7, 24, 16, 12, 0).toISOString() }
const nextDay = { role: 'user', created_at: new Date(2026, 7, 25, 9, 0, 0).toISOString() }
assert.equal(shouldInsertConversationTimestamp(undefined, firstUser), true)
assert.equal(shouldInsertConversationTimestamp(firstUser, assistantSameTurn), false)
assert.equal(shouldInsertConversationTimestamp(assistantSameTurn, nextUserSoon), false)
assert.equal(shouldInsertConversationTimestamp(assistantSameTurn, nextUserLater), true)
assert.equal(shouldInsertConversationTimestamp(nextUserLater, nextDay), true)
assert.equal(shouldInsertConversationTimestamp(firstUser, { role: 'user', created_at: '' }), false)
})
test('shouldShowConversationTimestamp inserts before the user turn not the assistant reply', () => {
const messages = [
{ role: 'user', created_at: new Date(2026, 7, 24, 16, 5, 0).toISOString() },
{ role: 'assistant', created_at: new Date(2026, 7, 24, 16, 5, 20).toISOString() },
{ role: 'user', created_at: new Date(2026, 7, 24, 17, 0, 0).toISOString() },
{ role: 'assistant', created_at: new Date(2026, 7, 24, 17, 0, 30).toISOString() },
]
assert.equal(shouldShowConversationTimestamp(messages, 0), true)
assert.equal(shouldShowConversationTimestamp(messages, 1), false)
assert.equal(shouldShowConversationTimestamp(messages, 2), true)
assert.equal(shouldShowConversationTimestamp(messages, 3), false)
})

View File

@ -62,3 +62,85 @@ export function formatMessageTimestamp(value: unknown): string {
const pad = (part: number) => String(part).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
/** Insert a flow divider after this much idle time, or when the calendar day changes. */
export const CONVERSATION_TIMESTAMP_GAP_MS = 5 * 60 * 1000
export type ConversationTimestampKind = 'today' | 'yesterday' | 'thisYear' | 'otherYear'
export type ConversationTimestampModel = {
datetime: string
kind: ConversationTimestampKind
time: string
year: number
month: number
day: number
}
type ConversationTimestampMessage = {
role?: unknown
created_at?: unknown
}
function startOfLocalDay(date: Date): number {
return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
}
function formatClock(date: Date): string {
const pad = (part: number) => String(part).padStart(2, '0')
return `${pad(date.getHours())}:${pad(date.getMinutes())}`
}
export function getConversationTimestampKind(date: Date, now = new Date()): ConversationTimestampKind {
const day = startOfLocalDay(date)
const today = startOfLocalDay(now)
const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1).getTime()
if (day === today) return 'today'
if (day === yesterday) return 'yesterday'
if (date.getFullYear() === now.getFullYear()) return 'thisYear'
return 'otherYear'
}
export function getConversationTimestampModel(
value: unknown,
now = new Date(),
): ConversationTimestampModel | null {
const datetime = normalizeMessageCreatedAt(value)
if (!datetime) return null
const date = new Date(datetime)
return {
datetime,
kind: getConversationTimestampKind(date, now),
time: formatClock(date),
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
}
}
export function shouldInsertConversationTimestamp(
previous: ConversationTimestampMessage | undefined,
current: ConversationTimestampMessage | undefined,
gapMs = CONVERSATION_TIMESTAMP_GAP_MS,
): boolean {
if (!current || !normalizeMessageCreatedAt(current.created_at)) return false
if (current.role === 'assistant' && previous?.role === 'user') return false
const previousCreatedAt = normalizeMessageCreatedAt(previous?.created_at)
if (!previousCreatedAt) return true
const previousDate = new Date(previousCreatedAt)
const currentDate = new Date(current.created_at as string)
if (startOfLocalDay(previousDate) !== startOfLocalDay(currentDate)) return true
return currentDate.getTime() - previousDate.getTime() >= gapMs
}
export function shouldShowConversationTimestamp(
messages: ConversationTimestampMessage[],
index: number,
gapMs = CONVERSATION_TIMESTAMP_GAP_MS,
): boolean {
return shouldInsertConversationTimestamp(messages[index - 1], messages[index], gapMs)
}

View File

@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs'
const botMessage = readFileSync(new URL('./botmsg.vue', import.meta.url), 'utf8')
const agentStream = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
const chatView = readFileSync(new URL('../index.vue', import.meta.url), 'utf8')
const embedChat = readFileSync(new URL('../../embed/EmbedChatCore.vue', import.meta.url), 'utf8')
const sharedStyles = readFileSync(
new URL('../../../components/css/chat-message-shared.less', import.meta.url),
'utf8',
@ -36,6 +37,15 @@ test('follow-up loading is shown compactly inside both answer toolbars', () => {
assert.match(sharedStyles, /follow-up-toolbar-loading-leave-to/)
})
test('conversation timestamps insert into the message flow instead of each bubble', () => {
assert.match(chatView, /shouldShowConversationTimestamp\(messagesList, index\)/)
assert.match(embedChat, /shouldShowConversationTimestamp\(messagesList, index\)/)
assert.doesNotMatch(chatView, /align="end"/)
assert.doesNotMatch(chatView, /align="start"/)
assert.doesNotMatch(embedChat, /align="end"/)
assert.doesNotMatch(embedChat, /align="start"/)
})
test('follow-up suggestions wait until the answer is fully rendered', () => {
assert.match(
chatView,

View File

@ -75,13 +75,14 @@
-->
<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>
<MessageTimestamp :value="session.created_at" align="end" />
</div>
<div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)"
class="message-row">
@ -91,7 +92,6 @@
:follow-up-loading="Boolean(session.suggestionLoading && !session.suggestionSet?.questions?.length)"
@render-complete-change="(ready) => handleAnswerRenderComplete(session, ready)">
</botmsg>
<MessageTimestamp :value="session.created_at" align="start" />
<FollowUpSuggestions v-if="session.answerFullyRendered && !session.suggestionsDismissed"
:suggestion-set="session.suggestionSet"
:loading="session.suggestionLoading"
@ -151,6 +151,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 { shouldShowConversationTimestamp } from '@/utils/messageTimestamp';
import ChatHeader from '@/components/ChatHeader.vue';
import {
notifySessionMutation,

View File

@ -46,6 +46,10 @@
:key="(session.id as string) || `${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">
<EmbedUserMessage
:content="String(session.content || '')"
@ -56,7 +60,6 @@
:embed-channel-id="channelId"
:embed-token="token"
/>
<MessageTimestamp :value="session.created_at" align="end" />
</div>
<div v-if="session.role === 'assistant' && shouldRenderAssistantMessage(session)" class="message-row">
<EmbedBotMessage
@ -70,7 +73,6 @@
:embed-session-sig="sessionSig"
:embed-visitor-id="visitorId"
/>
<MessageTimestamp :value="session.created_at" align="start" />
<FollowUpSuggestions v-if="!session.suggestionsDismissed"
:suggestion-set="session.suggestionSet as any"
:loading="Boolean(session.suggestionLoading)"
@ -130,6 +132,7 @@ import { provideChatReferencesDrawer } from '@/composables/useChatReferencesDraw
import { useEmbedChatSession } from '@/composables/useEmbedChatSession'
import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue'
import MessageTimestamp from '@/components/chat/MessageTimestamp.vue'
import { shouldShowConversationTimestamp } from '@/utils/messageTimestamp'
import type { MessageSuggestionItem, MessageSuggestionSet } from '@/api/message-suggestion'
provideChatReferencesDrawer()