Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(chat): polish rewind confirm and mark sessions with unread replies (#4247)

lyingbuge51dee8297e1
diff --git a/frontend/src/components/SessionSidebarRow.vue b/frontend/src/components/SessionSidebarRow.vue
index 4761c1d87..76d811add 100644
--- a/frontend/src/components/SessionSidebarRow.vue
+++ b/frontend/src/components/SessionSidebarRow.vue
@@ -5,6 +5,7 @@
batchMode && selectedIds.includes(item.id) ? 'submenu_item_selected' : '',
batchMode ? 'submenu_item_batch' : '',
menuOpen ? 'submenu_item--menu-open' : '',
+ showUnread ? 'submenu_item--unread' : '',
]" @mouseenter="emit('hover-in')" @mouseleave="emit('hover-out')"
@click="batchMode ? emit('toggle-select') : emit('navigate')">
<t-checkbox v-if="batchMode" class="batch-checkbox" :checked="selectedIds.includes(item.id)" @click.stop
@@ -19,11 +20,17 @@
<span v-if="apiOwnerTag" class="session-owner-tag" :class="`session-owner-tag--${apiOwnerTag.kind}`"
:title="apiOwnerTag.full">{{ apiOwnerTag.label }}</span>
</span>
- <span v-if="running" class="session-running-indicator" role="status" :aria-label="t('menu.sessionInProgress')"
- :title="t('menu.sessionInProgress')"><span class="session-running-indicator__spinner" aria-hidden="true" /></span>
- <div v-if="!batchMode || item.parent_session_id" class="session-row-menu-wrap"
- :class="{ 'session-row-menu-wrap--fork': item.parent_session_id }" @click.stop>
- <span v-if="item.parent_session_id" class="session-fork-indicator" role="img" aria-label="由其他会话分叉而来">
+ <div v-if="!batchMode || hasBadge" class="session-row-menu-wrap"
+ :class="{ 'session-row-menu-wrap--badge': hasBadge }" @click.stop>
+ <span v-if="running" class="session-row-badge session-running-indicator" role="status"
+ :aria-label="t('menu.sessionInProgress')" :title="t('menu.sessionInProgress')">
+ <span class="session-running-indicator__spinner" aria-hidden="true" />
+ </span>
+ <span v-else-if="showUnread" class="session-row-badge session-unread-indicator" role="status"
+ :aria-label="t('menu.sessionUnread')" :title="t('menu.sessionUnread')">
+ <span class="session-unread-indicator__dot" aria-hidden="true" />
+ </span>
+ <span v-else-if="item.parent_session_id" class="session-row-badge session-fork-indicator" role="img" aria-label="由其他会话分叉而来">
<t-icon name="git-branch" class="submenu_fork_icon" />
</span>
<t-popup v-if="!batchMode" v-model:visible="menuOpen" :overlay-class-name="menuOverlayClass" trigger="click" destroy-on-close
@@ -89,6 +96,7 @@ const props = defineProps<{
selectedIds: string[]
menuOptions: SessionMenuOption[]
running?: boolean
+ unread?: boolean
/** 渠道文件夹下的会话(样式与聊天区会话共用文案列对齐) */
nested?: boolean
}>()
@@ -112,6 +120,9 @@ const titleInputRef = ref<HTMLInputElement | null>(null)
const titleTextRef = ref<HTMLElement | null>(null)
useSessionTitleMotion(titleTextRef, () => props.item.id, () => props.item.title)
+const showUnread = computed(() => Boolean(props.unread) && !props.running && props.activePath !== props.item.path)
+const hasBadge = computed(() => Boolean(props.running || showUnread.value || props.item.parent_session_id))
+
const menuOverlayClass = computed(() => (
menuMode.value === 'menu'
? 'card-more session-action-menu-popup'
@@ -214,13 +225,6 @@ const confirmDangerAction = (): void => {
}
.session-running-indicator {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- flex: 0 0 16px;
- width: 16px;
- height: 16px;
- margin-left: 4px;
color: var(--td-brand-color);
}
@@ -241,6 +245,18 @@ const confirmDangerAction = (): void => {
}
}
+.session-unread-indicator__dot {
+ display: block;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--td-brand-color);
+}
+
+.submenu_item--unread .submenu_title-text {
+ font-weight: 500;
+}
+
.session-row-menu-wrap {
position: relative;
flex: 0 0 0;
@@ -250,7 +266,9 @@ const confirmDangerAction = (): void => {
pointer-events: none;
}
-.session-row-menu-wrap--fork {
+// A status badge (running / unread / fork) and the "more" button share one
+// 24px slot, so hovering swaps them in place instead of reflowing the title.
+.session-row-menu-wrap--badge {
flex-basis: 24px;
width: 24px;
height: 24px;
@@ -260,19 +278,20 @@ const confirmDangerAction = (): void => {
.menu-more-wrap { opacity: 0; }
}
-.submenu_item_batch .session-row-menu-wrap--fork { pointer-events: none; }
+.submenu_item_batch .session-row-menu-wrap--badge { pointer-events: none; }
-.session-fork-indicator {
+.session-row-badge {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
-
- .submenu_fork_icon { font-size: var(--app-text-sm); }
+ transition: opacity var(--app-motion-base) ease;
}
+.session-fork-indicator .submenu_fork_icon { font-size: var(--app-text-sm); }
+
.submenu_item:hover,
.submenu_item:focus-within,
.submenu_item--menu-open {
@@ -286,8 +305,8 @@ const confirmDangerAction = (): void => {
.submenu_item:not(.submenu_item_batch) {
&:hover, &:focus-within, &.submenu_item--menu-open {
- .session-fork-indicator { opacity: 0; }
- .session-row-menu-wrap--fork .menu-more-wrap { opacity: 1; }
+ .session-row-badge { opacity: 0; }
+ .session-row-menu-wrap--badge .menu-more-wrap { opacity: 1; }
}
}
@@ -300,7 +319,20 @@ const confirmDangerAction = (): void => {
}
.submenu_item:not(.submenu_item_batch) {
.session-fork-indicator { display: none; }
- .session-row-menu-wrap--fork .menu-more-wrap { opacity: 1; }
+ .session-row-menu-wrap--badge .menu-more-wrap { opacity: 1; }
+ }
+ // The "more" button never hides on touch, so the badge sits beside it.
+ .session-row-menu-wrap--badge {
+ display: flex;
+ align-items: center;
+ flex-basis: auto;
+ width: auto;
+ }
+ .session-row-badge:not(.session-fork-indicator) {
+ position: static;
+ flex: 0 0 16px;
+ height: 24px;
+ opacity: 1 !important;
}
}
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index cc4871555..b76f9d8ec 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -163,6 +163,7 @@
<div class="session-list-row__body">
<SessionSidebarRow :item="subitem" :batch-mode="batchMode"
:running="Boolean(sessionActivityEntries[subitem.id])"
+ :unread="Boolean(sessionUnread[subitem.id])"
:active-path="currentSecondpath" :selected-ids="batchSelectedIds"
:menu-options="buildSessionMenuOptions(subitem)"
@navigate="gotopage(subitem.path)"
@@ -310,7 +311,7 @@ const platformLogo = (p: string): string => (p ? PLATFORM_LOGO[p] || '' : '');
const { t } = useI18n();
const usemenuStore = useMenuStore();
const sessionActivity = useSessionActivityStore();
-const { entries: sessionActivityEntries } = storeToRefs(sessionActivity);
+const { entries: sessionActivityEntries, unread: sessionUnread } = storeToRefs(sessionActivity);
let sessionActivityTimer: ReturnType<typeof setInterval> | undefined;
const authStore = useAuthStore();
const deploymentCapabilities = useDeploymentCapabilitiesStore();
@@ -1033,7 +1034,7 @@ const loadSessionOriginMeta = async () => {
const handleSessionMutation = (event: Event) => {
const detail = (event as CustomEvent<SessionMutationDetail>).detail;
if (!detail?.sessionId) return;
- if (detail.removed || detail.messagesCleared) sessionActivity.update(detail.sessionId, false);
+ if (detail.removed || detail.messagesCleared) sessionActivity.dismiss(detail.sessionId);
if (detail.patch) {
updateSessionInBuckets(detail.sessionId, {
...detail.patch,
@@ -1050,6 +1051,8 @@ const handleSessionMutation = (event: Event) => {
};
onMounted(async () => {
+ sessionActivity.restore();
+ void sessionActivity.refresh();
sessionActivityTimer = setInterval(() => { void sessionActivity.refresh(); }, 5000);
const routeName = typeof route.name === 'string' ? route.name : (route.name ? String(route.name) : '')
currentpath.value = routeName;
@@ -1730,11 +1733,6 @@ const resizeSidebar = (delta: number, keyboard: boolean) => {
overflow: hidden;
}
- .session-running-indicator {
- flex: 0 0 16px;
- flex-shrink: 0;
- }
-
.submenu_title-text {
flex: 1 1 auto;
min-width: 0;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index f292cec8d..e38964545 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -324,6 +324,7 @@ export default {
},
menu: {
sessionInProgress: 'Conversation in progress',
+ sessionUnread: 'New reply',
knowledgeBase: 'Knowledge Base',
agents: 'Agents',
artifacts: 'Artifacts',
@@ -4087,6 +4088,7 @@ export default {
truncatedHint: 'This answer was cut off at the per-response output limit. Above is what the model produced before the cut.',
rewind: {
tooltip: 'Rewind to here',
+ confirmTitle: 'Rewind to here?',
confirmBody: 'Later messages will be deleted. Rewinding from a question also removes that question and puts it back in the input. The workspace rolls back when a checkpoint is available. This cannot be undone.',
confirmButton: 'Rewind',
cancelButton: 'Cancel',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index abd35651f..e12f6c7a1 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -324,6 +324,7 @@ export default {
},
menu: {
sessionInProgress: '会話中',
+ sessionUnread: '新しい回答',
knowledgeBase: 'ナレッジベース',
agents: 'エージェント',
artifacts: '成果物',
@@ -4087,6 +4088,7 @@ export default {
truncatedHint: 'モデルの1回あたりの出力上限で回答が途中で打ち切られました。上記は打ち切り前に生成された内容です。',
rewind: {
tooltip: 'ここに巻き戻す',
+ confirmTitle: 'ここに巻き戻しますか?',
confirmBody: 'これより後の会話を削除します。質問から巻き戻すとその質問自体も消え、入力欄に戻します。チェックポイントがあればワークスペースも戻します。この操作は元に戻せません。',
confirmButton: '巻き戻す',
cancelButton: 'キャンセル',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index fbaa46967..12f3c76db 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -3995,6 +3995,7 @@ export default {
truncatedHint: '모델의 응답당 출력 한도에서 답변이 잘렸습니다. 위 내용은 잘리기 전까지 생성된 부분입니다.',
rewind: {
tooltip: '여기로 되돌리기',
+ confirmTitle: '여기로 되돌릴까요?',
confirmBody: '이 메시지 이후의 대화를 삭제합니다. 질문에서 되돌리면 해당 질문도 지워지고 입력창에 다시 채워집니다. 체크포인트가 있으면 작업 영역도 되돌립니다. 이 작업은 취소할 수 없습니다.',
confirmButton: '되돌리기',
cancelButton: '취소',
@@ -7835,6 +7836,7 @@ export default {
},
menu: {
sessionInProgress: '대화 진행 중',
+ sessionUnread: '새 답변',
knowledgeBase: '지식베이스',
agents: '에이전트',
artifacts: '산출물',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 3222f77f9..e7de097e4 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -3995,6 +3995,7 @@ export default {
truncatedHint: 'Ответ обрезан на лимите вывода модели за один ответ. Выше — то, что было создано до обрыва.',
rewind: {
tooltip: 'Откатить сюда',
+ confirmTitle: 'Откатить сюда?',
confirmBody: 'Сообщения после этой точки будут удалены. Откат от вопроса также убирает сам вопрос и возвращает его во ввод. Рабочая область откатится, если есть контрольная точка. Отменить действие нельзя.',
confirmButton: 'Откатить',
cancelButton: 'Отмена',
@@ -7835,6 +7836,7 @@ export default {
},
menu: {
sessionInProgress: 'Диалог выполняется',
+ sessionUnread: 'Новый ответ',
knowledgeBase: 'База знаний',
agents: 'Агенты',
artifacts: 'Артефакты',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 69a1618a3..b7f29e7b7 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -3997,7 +3997,8 @@ export default {
truncatedHint: '回答在模型单次输出上限处被截断,以上为截断前已生成的内容',
rewind: {
tooltip: '回滚到这里',
- confirmBody: '将删除此条之后的对话。从用户消息回滚时会删掉该问题本身,并填回输入框。若有可用检查点,工作区会一并回退。此操作不可撤销。',
+ confirmTitle: '回滚到这里?',
+ confirmBody: '此条之后的对话将被删除;从提问回滚时,该问题会填回输入框。有检查点时工作区也会一并回退,操作不可撤销。',
confirmButton: '回滚',
cancelButton: '取消',
success: '已回滚',
@@ -7837,6 +7838,7 @@ export default {
},
menu: {
sessionInProgress: '会话进行中',
+ sessionUnread: '有新回复',
knowledgeBase: '知识库',
agents: '智能体',
artifacts: '产物',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index c88c91311..c5ea3b747 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -3997,7 +3997,8 @@ export default {
truncatedHint: '回答在模型單次輸出上限處被截斷,以上為截斷前已生成的內容',
rewind: {
tooltip: '回滾到這裡',
- confirmBody: '將刪除此條之後的對話。從使用者訊息回滾時會刪掉該問題本身,並填回輸入框。若有可用檢查點,工作區會一併回退。此操作不可復原。',
+ confirmTitle: '回滾到這裡?',
+ confirmBody: '此條之後的對話將被刪除;從提問回滾時,該問題會填回輸入框。有檢查點時工作區也會一併回退,操作不可復原。',
confirmButton: '回滾',
cancelButton: '取消',
success: '已回滾',
@@ -7837,6 +7838,7 @@ export default {
},
menu: {
sessionInProgress: '會話進行中',
+ sessionUnread: '有新回覆',
knowledgeBase: '知識庫',
agents: '智慧代理',
artifacts: '產物',
diff --git a/frontend/src/stores/sessionActivity.ts b/frontend/src/stores/sessionActivity.ts
index b992873cf..e2a23b1d9 100644
--- a/frontend/src/stores/sessionActivity.ts
+++ b/frontend/src/stores/sessionActivity.ts
@@ -2,15 +2,73 @@ import { reactive, watch } from 'vue'
import { defineStore } from 'pinia'
import { getMessageList } from '@/api/chat/index'
import { useAuthStore } from './auth'
-import { createSessionActivityState, type SessionActivity } from './sessionActivityState'
+import {
+ createSessionActivityState,
+ restoreSessionActivity,
+ serializeSessionActivity,
+ type SessionActivity,
+} from './sessionActivityState'
+
+const STORAGE_PREFIX = 'weknora:session-activity'
export const useSessionActivityStore = defineStore('sessionActivity', () => {
const entries = reactive<Record<string, SessionActivity>>({})
+ const unread = reactive<Record<string, true>>({})
const activity = createSessionActivityState(entries, async sessionId => {
const result = await getMessageList({ session_id: sessionId, limit: 20, created_at: '' })
return result.data || []
- })
+ }, unread)
const auth = useAuthStore()
- watch(() => [auth.user?.id, auth.effectiveTenantId], activity.clear, { flush: 'sync' })
- return { entries, ...activity }
+
+ const storageKey = () => {
+ const userId = auth.user?.id
+ return userId ? `${STORAGE_PREFIX}:${userId}:${auth.effectiveTenantId ?? ''}` : ''
+ }
+
+ // clear() only resets memory (unmount, account switch); writes happen after
+ // real transitions so an unmount cannot wipe what the next mount restores.
+ function persist() {
+ const key = storageKey()
+ if (!key) return
+ try {
+ localStorage.setItem(key, serializeSessionActivity(entries, unread))
+ } catch {
+ // Storage full or disabled: the in-memory markers still work.
+ }
+ }
+
+ function restore() {
+ const key = storageKey()
+ if (!key) return
+ try {
+ restoreSessionActivity(localStorage.getItem(key), entries, unread)
+ } catch {
+ // Storage disabled.
+ }
+ }
+
+ const persisting = <A extends unknown[], R>(fn: (...args: A) => R) => (...args: A): R => {
+ const result = fn(...args)
+ if (result instanceof Promise) void result.finally(persist)
+ else persist()
+ return result
+ }
+
+ watch(() => [auth.user?.id, auth.effectiveTenantId], () => {
+ activity.clear()
+ restore()
+ }, { flush: 'sync' })
+ restore()
+
+ return {
+ entries,
+ unread,
+ update: persisting(activity.update),
+ detach: persisting(activity.detach),
+ setViewing: persisting(activity.setViewing),
+ dismiss: persisting(activity.dismiss),
+ refresh: persisting(activity.refresh),
+ clear: activity.clear,
+ restore,
+ }
})
diff --git a/frontend/src/stores/sessionActivityState.test.ts b/frontend/src/stores/sessionActivityState.test.ts
index 666ce089c..a127fb80a 100644
--- a/frontend/src/stores/sessionActivityState.test.ts
+++ b/frontend/src/stores/sessionActivityState.test.ts
@@ -1,7 +1,12 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { reactive } from 'vue'
-import { createSessionActivityState, type SessionActivity } from './sessionActivityState.ts'
+import {
+ createSessionActivityState,
+ restoreSessionActivity,
+ serializeSessionActivity,
+ type SessionActivity,
+} from './sessionActivityState.ts'
test('tracks multiple sessions and keeps detached replies until completion', async () => {
const entries = reactive<Record<string, SessionActivity>>({})
@@ -67,6 +72,96 @@ test('transient failures preserve the marker and repeated failures clear it', as
assert.equal(entries.a, undefined)
})
+test('a detached reply that finishes off-screen stays unread until the session is opened', async () => {
+ const entries = reactive<Record<string, SessionActivity>>({})
+ const unread = reactive<Record<string, true>>({})
+ const state = createSessionActivityState(entries, async () => [
+ { id: 'reply', role: 'assistant', is_completed: true },
+ ], unread)
+ state.update('a', true, 'reply')
+ state.detach('a')
+ state.setViewing('b')
+ await state.refresh()
+ assert.equal(entries.a, undefined)
+ assert.equal(unread.a, true)
+ state.setViewing('a')
+ assert.equal(unread.a, undefined)
+})
+
+test('no unread marker for the session in view, a vanished reply, or a new turn', async () => {
+ const entries = reactive<Record<string, SessionActivity>>({})
+ const unread = reactive<Record<string, true>>({})
+ let messages: any[] = [{ id: 'reply', role: 'assistant', is_completed: true }]
+ const state = createSessionActivityState(entries, async () => messages, unread)
+ state.update('a', true, 'reply')
+ state.detach('a')
+ state.setViewing('a')
+ await state.refresh()
+ assert.equal(unread.a, undefined, 'already looking at it')
+
+ state.setViewing('')
+ state.update('b', true, 'gone')
+ state.detach('b')
+ messages = []
+ await state.refresh()
+ assert.equal(unread.b, undefined, 'a reply that disappeared is not news')
+
+ unread.c = true
+ state.update('c', true, 'next')
+ assert.equal(unread.c, undefined, 'a new turn supersedes the old unread')
+ unread.d = true
+ state.clear()
+ assert.deepEqual(Object.keys(unread), [])
+})
+
+test('a reload restores unread markers and resumes polling every running turn as detached', async () => {
+ const saved = serializeSessionActivity(
+ {
+ live: { messageId: 'r1', detached: false, failures: 0 },
+ away: { messageId: 'r2', detached: true, failures: 2 },
+ },
+ { done: true },
+ )
+ const entries = reactive<Record<string, SessionActivity>>({})
+ const unread = reactive<Record<string, true>>({})
+ restoreSessionActivity(saved, entries, unread)
+ assert.deepEqual({ ...entries }, {
+ live: { messageId: 'r1', detached: true, failures: 0 },
+ away: { messageId: 'r2', detached: true, failures: 0 },
+ })
+ assert.deepEqual(Object.keys(unread), ['done'])
+
+ const state = createSessionActivityState(entries, async id => [
+ { id: id === 'live' ? 'r1' : 'r2', role: 'assistant', is_completed: true },
+ ], unread)
+ await state.refresh()
+ assert.deepEqual(Object.keys(unread).sort(), ['away', 'done', 'live'])
+})
+
+test('restoring ignores corrupt storage and never overrides a live entry', () => {
+ const entries = reactive<Record<string, SessionActivity>>({
+ a: { messageId: 'new', detached: false, failures: 0 },
+ })
+ const unread = reactive<Record<string, true>>({})
+ restoreSessionActivity('{not json', entries, unread)
+ restoreSessionActivity(null, entries, unread)
+ restoreSessionActivity(JSON.stringify({ running: { a: 'old' }, unread: [1, '', 'b'] }), entries, unread)
+ assert.equal(entries.a.messageId, 'new')
+ assert.equal(entries.a.detached, false)
+ assert.deepEqual(Object.keys(unread), ['b'])
+})
+
+test('dismissing a removed session drops both markers', () => {
+ const entries = reactive<Record<string, SessionActivity>>({})
+ const unread = reactive<Record<string, true>>({ a: true })
+ const state = createSessionActivityState(entries, async () => [], unread)
+ state.update('a', true, 'r')
+ unread.a = true
+ state.dismiss('a')
+ assert.equal(entries.a, undefined)
+ assert.equal(unread.a, undefined)
+})
+
test('clearing activity while a poll is in flight cannot restore old account state', async () => {
const entries = reactive<Record<string, SessionActivity>>({})
let resolve!: (messages: any[]) => void
diff --git a/frontend/src/stores/sessionActivityState.ts b/frontend/src/stores/sessionActivityState.ts
index 060e09ecb..26296e917 100644
--- a/frontend/src/stores/sessionActivityState.ts
+++ b/frontend/src/stores/sessionActivityState.ts
@@ -10,18 +10,69 @@ interface ActivityMessage {
is_completed: boolean
}
+interface PersistedSessionActivity {
+ running: Record<string, string>
+ unread: string[]
+}
+
+const MAX_PERSISTED_UNREAD = 100
+
+// A reload drops every live stream, so whatever was running is saved as
+// detached: polling then decides whether it finished while the page was gone.
+export function serializeSessionActivity(
+ entries: Record<string, SessionActivity>,
+ unread: Record<string, true>,
+): string {
+ const running: Record<string, string> = {}
+ for (const [sessionId, entry] of Object.entries(entries)) running[sessionId] = entry.messageId
+ const data: PersistedSessionActivity = { running, unread: Object.keys(unread).slice(-MAX_PERSISTED_UNREAD) }
+ return JSON.stringify(data)
+}
+
+export function restoreSessionActivity(
+ raw: string | null,
+ entries: Record<string, SessionActivity>,
+ unread: Record<string, true>,
+) {
+ if (!raw) return
+ let data: Partial<PersistedSessionActivity>
+ try {
+ data = JSON.parse(raw)
+ } catch {
+ return
+ }
+ if (data.running && typeof data.running === 'object') {
+ for (const [sessionId, messageId] of Object.entries(data.running)) {
+ if (sessionId && !entries[sessionId]) {
+ entries[sessionId] = { messageId: typeof messageId === 'string' ? messageId : '', detached: true, failures: 0 }
+ }
+ }
+ }
+ if (Array.isArray(data.unread)) {
+ for (const sessionId of data.unread) {
+ if (typeof sessionId === 'string' && sessionId) unread[sessionId] = true
+ }
+ }
+}
+
// Entries are replaced on every local update so stale polling responses cannot
// clear a newer turn or a stream that has since reattached.
export function createSessionActivityState(
entries: Record<string, SessionActivity>,
fetchMessages: (sessionId: string) => Promise<ActivityMessage[]>,
+ unread: Record<string, true> = {},
) {
const pending = new Set<string>()
+ let viewingSessionId = ''
function update(sessionId: string, running: boolean, messageId = '') {
if (!sessionId) return
- if (running) entries[sessionId] = { messageId, detached: false, failures: 0 }
- else delete entries[sessionId]
+ if (running) {
+ entries[sessionId] = { messageId, detached: false, failures: 0 }
+ delete unread[sessionId]
+ } else {
+ delete entries[sessionId]
+ }
}
function detach(sessionId: string) {
@@ -29,6 +80,16 @@ export function createSessionActivityState(
if (entry) entries[sessionId] = { ...entry, detached: true }
}
+ function setViewing(sessionId: string) {
+ viewingSessionId = sessionId
+ if (sessionId) delete unread[sessionId]
+ }
+
+ function dismiss(sessionId: string) {
+ delete entries[sessionId]
+ delete unread[sessionId]
+ }
+
async function refresh() {
await Promise.all(Object.entries(entries).map(async ([sessionId, entry]) => {
if (!entry.detached || pending.has(sessionId)) return
@@ -39,7 +100,10 @@ export function createSessionActivityState(
const message = entry.messageId
? messages.find(message => message.id === entry.messageId)
: messages.find(message => message.role === 'assistant' && !message.is_completed)
- if (message?.is_completed || (!message && entry.messageId)) {
+ if (message?.is_completed) {
+ delete entries[sessionId]
+ if (sessionId !== viewingSessionId) unread[sessionId] = true
+ } else if (!message && entry.messageId) {
delete entries[sessionId]
} else if (message) {
entries[sessionId] = { messageId: message.id, detached: true, failures: 0 }
@@ -61,7 +125,8 @@ export function createSessionActivityState(
function clear() {
for (const sessionId of Object.keys(entries)) delete entries[sessionId]
+ for (const sessionId of Object.keys(unread)) delete unread[sessionId]
}
- return { update, detach, refresh, clear }
+ return { update, detach, setViewing, dismiss, refresh, clear }
}
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index 2dec64e5e..f85930710 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -391,14 +391,18 @@
</t-tooltip>
<t-popconfirm
v-if="canRewind"
- :content="t('chat.rewind.confirmBody')"
- :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger' }"
- :cancel-btn="{ content: t('chat.rewind.cancelButton') }"
+ :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger', size: 'small' }"
+ :cancel-btn="{ content: t('chat.rewind.cancelButton'), size: 'small' }"
theme="warning"
placement="top"
- overlay-class-name="chat-rewind-popconfirm"
+ :show-arrow="false"
+ overlay-class-name="wk-popover chat-rewind-popconfirm"
@confirm="emitRewind"
>
+ <template #content>
+ <div class="chat-rewind-confirm__title">{{ t('chat.rewind.confirmTitle') }}</div>
+ <div class="chat-rewind-confirm__body">{{ t('chat.rewind.confirmBody') }}</div>
+ </template>
<t-tooltip :content="rewindTooltip">
<t-button size="small" variant="outline" shape="round" @click.stop>
<t-icon name="rollback" />
diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue
index 7a3b70e37..c794b1813 100644
--- a/frontend/src/views/chat/components/botmsg.vue
+++ b/frontend/src/views/chat/components/botmsg.vue
@@ -61,14 +61,18 @@
</t-tooltip>
<t-popconfirm
v-if="canRewind"
- :content="t('chat.rewind.confirmBody')"
- :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger' }"
- :cancel-btn="{ content: t('chat.rewind.cancelButton') }"
+ :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger', size: 'small' }"
+ :cancel-btn="{ content: t('chat.rewind.cancelButton'), size: 'small' }"
theme="warning"
placement="top"
- overlay-class-name="chat-rewind-popconfirm"
+ :show-arrow="false"
+ overlay-class-name="wk-popover chat-rewind-popconfirm"
@confirm="emitRewind"
>
+ <template #content>
+ <div class="chat-rewind-confirm__title">{{ t('chat.rewind.confirmTitle') }}</div>
+ <div class="chat-rewind-confirm__body">{{ t('chat.rewind.confirmBody') }}</div>
+ </template>
<t-tooltip :content="rewindTooltip">
<t-button size="small" variant="outline" shape="round" @click.stop>
<t-icon name="rollback" />
diff --git a/frontend/src/views/chat/components/usermsg.vue b/frontend/src/views/chat/components/usermsg.vue
index de6463088..92fed55d6 100644
--- a/frontend/src/views/chat/components/usermsg.vue
+++ b/frontend/src/views/chat/components/usermsg.vue
@@ -1,5 +1,5 @@
<template>
- <div class="user_msg_container" ref="containerRef" :class="{ 'is-embedded': embeddedMode }">
+ <div class="user_msg_container" ref="containerRef" :class="{ 'is-embedded': embeddedMode, 'is-actions-pinned': rewindConfirmOpen }">
<!-- 显示@的知识库和文件 -->
<div v-if="mentioned_items && mentioned_items.length > 0" class="mentioned_items">
<span v-for="item in mentioned_items" :key="item.id" class="mentioned_tag" :class="[
@@ -50,16 +50,21 @@
</t-tooltip>
<t-popconfirm
v-if="canRewind"
- :content="t('chat.rewind.confirmBody')"
- :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger' }"
- :cancel-btn="{ content: t('chat.rewind.cancelButton') }"
+ :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger', size: 'small' }"
+ :cancel-btn="{ content: t('chat.rewind.cancelButton'), size: 'small' }"
theme="warning"
placement="top"
- overlay-class-name="chat-rewind-popconfirm"
+ :show-arrow="false"
+ overlay-class-name="wk-popover chat-rewind-popconfirm"
+ @visible-change="(visible) => (rewindConfirmOpen = visible)"
@confirm="emit('rewind', messageId)"
>
+ <template #content>
+ <div class="chat-rewind-confirm__title">{{ t('chat.rewind.confirmTitle') }}</div>
+ <div class="chat-rewind-confirm__body">{{ t('chat.rewind.confirmBody') }}</div>
+ </template>
<t-tooltip :content="rewindTooltip">
- <button type="button" class="user_msg_action" :aria-label="rewindTooltip" @click.stop>
+ <button type="button" class="user_msg_action" :class="{ 'is-active': rewindConfirmOpen }" :aria-label="rewindTooltip" @click.stop>
<t-icon name="rollback" />
</button>
</t-tooltip>
@@ -160,6 +165,7 @@ const timestamp = computed(() => getConversationTimestampModel(props.createdAt))
const fullTimestamp = computed(() => formatMessageTimestamp(props.createdAt));
const handleCopy = () => copyWithToast(props.content, 'common.copySuccess', 'common.copyFailed');
const rewindTooltip = computed(() => t('chat.rewind.tooltip'));
+const rewindConfirmOpen = ref(false);
const attachmentPreviewDrawer = useChatAttachmentPreviewDrawer();
@@ -425,7 +431,8 @@ html[theme-mode="dark"] {
}
.user_msg_container:hover .user_msg_meta,
-.user_msg_container:focus-within .user_msg_meta {
+.user_msg_container:focus-within .user_msg_meta,
+.user_msg_container.is-actions-pinned .user_msg_meta {
opacity: 1;
pointer-events: auto;
}
@@ -445,7 +452,8 @@ html[theme-mode="dark"] {
cursor: pointer;
}
-.user_msg_action:hover {
+.user_msg_action:hover,
+.user_msg_action.is-active {
color: var(--td-text-color-secondary);
background: var(--td-bg-color-container-hover);
}
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 75092a92d..4b8db23c3 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -576,6 +576,9 @@ watch([activitySessionId, isReplying, isImRecovering, currentAssistantMessageId]
sessionActivity.update(activitySessionId.value, isReplying.value || isImRecovering.value, currentAssistantMessageId.value);
}, { flush: 'sync' });
const historyLoading = ref(true);
+watch(activitySessionId, (id) => {
+ if (!props.embeddedMode) sessionActivity.setViewing(id);
+}, { flush: 'sync' });
const historyLoadingMore = ref(false);
const hasMoreHistory = ref(true);
@@ -2160,13 +2163,54 @@ onBeforeRouteUpdate((to, from, next) => {
<style lang="less">
.chat-rewind-popconfirm {
- max-width: 260px;
+ .t-popconfirm__content {
+ width: 280px;
+ max-width: calc(100vw - 24px);
+ padding: 14px 16px 12px;
+ box-sizing: border-box;
+ }
+
+ .t-popconfirm__body {
+ gap: 8px;
+ }
- .t-popconfirm__content,
- .t-popup__content {
- max-width: 260px;
+ .t-popconfirm__body > .t-icon {
+ flex-shrink: 0;
+ margin: 0;
+ padding: 3px 0 0;
+ font-size: 16px;
+ }
+
+ .t-popconfirm__inner {
+ flex: 1;
+ min-width: 0;
+ max-width: none;
white-space: normal;
- line-height: 1.5;
+ }
+
+ .chat-rewind-confirm__title {
+ font-size: var(--app-text-base);
+ font-weight: 500;
+ line-height: 22px;
+ color: var(--td-text-color-primary);
+ }
+
+ .chat-rewind-confirm__body {
+ margin-top: 2px;
+ font-size: var(--app-text-md);
+ line-height: 20px;
+ color: var(--td-text-color-secondary);
+ }
+
+ .t-popconfirm__buttons {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 12px;
+
+ .t-popconfirm__confirm {
+ margin-left: 0;
+ }
}
}
</style>
diff --git a/frontend/src/views/chat/rewindView.test.ts b/frontend/src/views/chat/rewindView.test.ts
index 3736fae16..937ec655d 100644
--- a/frontend/src/views/chat/rewindView.test.ts
+++ b/frontend/src/views/chat/rewindView.test.ts
@@ -65,9 +65,11 @@ test('offers rewind on user and assistant messages unless outgoing work or an in
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: true },
+ { id: 'u2', role: 'user' },
]
assert.equal(resolveRewindAffordance(messages, 'u1').canRewind, true)
assert.equal(resolveRewindAffordance(messages, 'a1').canRewind, true)
+ assert.equal(resolveRewindAffordance(messages, 'u2').canRewind, true)
assert.equal(resolveRewindAffordance(messages, 'u1', { embeddedMode: true }).canRewind, false)
assert.equal(resolveRewindAffordance(messages, 'u1', { outgoingWork: true }).canRewind, false)
assert.equal(
@@ -96,10 +98,11 @@ test('resolves every rewindable id in a single pass', () => {
const messages = [
{ id: 'u1', role: 'user' },
{ id: 'a1', role: 'assistant', is_completed: true },
+ { id: 'u2', role: 'user' },
{ id: 'sys', role: 'system' },
{ id: '', role: 'user' },
]
- assert.deepEqual([...rewindableMessageIds(messages)], ['u1', 'a1'])
+ assert.deepEqual([...rewindableMessageIds(messages)], ['u1', 'a1', 'u2'])
assert.deepEqual([...rewindableMessageIds(messages, { embeddedMode: true })], [])
assert.deepEqual([...rewindableMessageIds(messages, { outgoingWork: true })], [])
assert.deepEqual(
@@ -108,3 +111,14 @@ test('resolves every rewindable id in a single pass', () => {
'an unfinished turn withdraws the control from the whole transcript',
)
})
+
+test('withholds rewind from the newest assistant answer', () => {
+ const messages = [
+ { id: 'u1', role: 'user' },
+ { id: 'a1', role: 'assistant', is_completed: true },
+ { id: 'u2', role: 'user' },
+ { id: 'a2', role: 'assistant', is_completed: true },
+ { id: 'sys', role: 'system' },
+ ]
+ assert.deepEqual([...rewindableMessageIds(messages)], ['u1', 'a1', 'u2'])
+})
diff --git a/frontend/src/views/chat/rewindView.ts b/frontend/src/views/chat/rewindView.ts
index dd52d245e..849797859 100644
--- a/frontend/src/views/chat/rewindView.ts
+++ b/frontend/src/views/chat/rewindView.ts
@@ -83,6 +83,7 @@ export function rewindableMessageIds(
if (opts.embeddedMode || opts.outgoingWork) {
return ids
}
+ let tail: { id: string; role: unknown } | null = null
for (const message of messages) {
if (message.role === 'assistant' && message.is_completed === false) {
return new Set<string>()
@@ -90,8 +91,13 @@ export function rewindableMessageIds(
const id = String(message.id || '')
if (id && (message.role === 'assistant' || message.role === 'user')) {
ids.add(id)
+ tail = { id, role: message.role }
}
}
+ // Rewinding to the newest answer would delete nothing.
+ if (tail?.role === 'assistant') {
+ ids.delete(tail.id)
+ }
return ids
}