feat(chat): add session header actions and Markdown export
Give chat a left-aligned header for rename/pin/copy/clear/delete, share session mutations across sidebar and chat view, and support copying the full conversation as Markdown.
This commit is contained in:
@@ -0,0 +1,641 @@
|
|||||||
|
<template>
|
||||||
|
<header class="chat-header" :class="{ 'is-editing': titleEditing }">
|
||||||
|
<form
|
||||||
|
v-if="titleEditing"
|
||||||
|
class="chat-header__edit"
|
||||||
|
@submit.prevent="submitTitleEdit"
|
||||||
|
@click.stop
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref="titleInputRef"
|
||||||
|
v-model="titleDraft"
|
||||||
|
class="chat-header__edit-input"
|
||||||
|
:maxlength="SESSION_TITLE_MAX_LENGTH"
|
||||||
|
:disabled="busyAction === 'rename'"
|
||||||
|
:placeholder="t('chatHeader.renamePlaceholder')"
|
||||||
|
@keydown.esc.prevent="cancelTitleEdit"
|
||||||
|
@blur="submitTitleEdit"
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
<h1
|
||||||
|
v-else
|
||||||
|
class="chat-header__title"
|
||||||
|
:title="displayTitle"
|
||||||
|
@dblclick="startTitleEdit"
|
||||||
|
>
|
||||||
|
<t-icon v-if="session?.is_pinned" name="pin" size="12px" class="chat-header__pin" />
|
||||||
|
<span class="chat-header__title-text">{{ displayTitle }}</span>
|
||||||
|
</h1>
|
||||||
|
<t-popup
|
||||||
|
v-if="!titleEditing"
|
||||||
|
v-model:visible="menuVisible"
|
||||||
|
:overlay-class-name="menuOverlayClass"
|
||||||
|
trigger="click"
|
||||||
|
destroy-on-close
|
||||||
|
placement="bottom-left"
|
||||||
|
:disabled="!session || Boolean(busyAction)"
|
||||||
|
@visible-change="onMenuVisibleChange"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="chat-header__menu-btn"
|
||||||
|
:class="{ 'is-loading': Boolean(busyAction) }"
|
||||||
|
:disabled="!session || Boolean(busyAction)"
|
||||||
|
:aria-label="t('chatHeader.moreActions')"
|
||||||
|
@click.stop
|
||||||
|
>
|
||||||
|
<t-icon v-if="busyAction" name="loading" size="14px" class="chat-header__menu-loading" />
|
||||||
|
<t-icon v-else name="ellipsis" size="16px" />
|
||||||
|
</button>
|
||||||
|
<template #content>
|
||||||
|
<div class="chat-header-menu" @click.stop>
|
||||||
|
<template v-if="menuMode === 'menu'">
|
||||||
|
<button type="button" class="chat-header-menu__item" @click="onMenuAction(session?.is_pinned ? 'unpin' : 'pin')">
|
||||||
|
<t-icon class="chat-header-menu__icon" :name="session?.is_pinned ? 'pin-filled' : 'pin'" />
|
||||||
|
<span>{{ session?.is_pinned ? t('menu.unpin') : t('menu.pin') }}</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="chat-header-menu__item" @click="onMenuAction('rename')">
|
||||||
|
<t-icon class="chat-header-menu__icon" name="edit-1" />
|
||||||
|
<span>{{ t('menu.renameSession') }}</span>
|
||||||
|
</button>
|
||||||
|
<div class="chat-header-menu__divider" />
|
||||||
|
<button type="button" class="chat-header-menu__item" @click="onMenuAction('copyId')">
|
||||||
|
<t-icon class="chat-header-menu__icon" name="copy" />
|
||||||
|
<span>{{ t('chatHeader.copySessionId') }}</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="chat-header-menu__item" @click="onMenuAction('copyLink')">
|
||||||
|
<t-icon class="chat-header-menu__icon" name="link" />
|
||||||
|
<span>{{ t('chatHeader.copyLink') }}</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="chat-header-menu__item" @click="onMenuAction('copyMarkdown')">
|
||||||
|
<t-icon class="chat-header-menu__icon" name="file-copy" />
|
||||||
|
<span>{{ t('chatHeader.copyMarkdown') }}</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="chat-header-menu__item" @click="onMenuAction('openNewWindow')">
|
||||||
|
<t-icon class="chat-header-menu__icon" name="browse" />
|
||||||
|
<span>{{ t('chatHeader.openNewWindow') }}</span>
|
||||||
|
</button>
|
||||||
|
<div class="chat-header-menu__divider" />
|
||||||
|
<button type="button" class="chat-header-menu__item" @click="enterConfirmMode('clear')">
|
||||||
|
<t-icon class="chat-header-menu__icon" name="clear" />
|
||||||
|
<span>{{ t('menu.clearMessages') }}</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="chat-header-menu__item is-danger" @click="enterConfirmMode('delete')">
|
||||||
|
<t-icon class="chat-header-menu__icon" name="delete" />
|
||||||
|
<span>{{ t('chatHeader.deleteSession') }}</span>
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div v-else class="chat-header-confirm">
|
||||||
|
<div class="chat-header-confirm__title">
|
||||||
|
{{ menuMode === 'clear' ? t('chatHeader.clearConfirmTitle') : t('chatHeader.deleteConfirmTitle') }}
|
||||||
|
</div>
|
||||||
|
<div class="chat-header-confirm__body">
|
||||||
|
{{ menuMode === 'clear' ? t('chatHeader.clearConfirmBody') : t('chatHeader.deleteConfirmBody') }}
|
||||||
|
</div>
|
||||||
|
<div class="chat-header-confirm__footer">
|
||||||
|
<button type="button" class="chat-header-confirm__btn" :disabled="Boolean(busyAction)" @click="backToMenu">
|
||||||
|
{{ t('common.cancel') }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="chat-header-confirm__btn is-danger"
|
||||||
|
:disabled="Boolean(busyAction)"
|
||||||
|
@click="menuMode === 'clear' ? submitClearMessages() : submitDeleteSession()"
|
||||||
|
>
|
||||||
|
{{ menuMode === 'clear' ? t('common.clear') : t('common.delete') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</t-popup>
|
||||||
|
</header>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, nextTick, ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { MessagePlugin } from 'tdesign-vue-next'
|
||||||
|
import { getMessageList } from '@/api/chat'
|
||||||
|
import {
|
||||||
|
clearSession,
|
||||||
|
removeSession,
|
||||||
|
renameSession,
|
||||||
|
setSessionPinned,
|
||||||
|
} from './sessionMutations'
|
||||||
|
import { normalizeSessionTitleDraft, SESSION_TITLE_MAX_LENGTH } from './sessionTitleEdit'
|
||||||
|
import { buildSessionMarkdown, collectAllSessionMessages } from '@/utils/sessionMarkdown'
|
||||||
|
|
||||||
|
interface ChatHeaderSession {
|
||||||
|
id: string
|
||||||
|
title?: string
|
||||||
|
description?: string
|
||||||
|
tenant_id?: number | string
|
||||||
|
is_pinned?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
type MenuMode = 'menu' | 'clear' | 'delete'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
session: ChatHeaderSession | null
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
const busyAction = ref('')
|
||||||
|
const menuVisible = ref(false)
|
||||||
|
const menuMode = ref<MenuMode>('menu')
|
||||||
|
const titleEditing = ref(false)
|
||||||
|
const titleDraft = ref('')
|
||||||
|
const titleInputRef = ref<HTMLInputElement | null>(null)
|
||||||
|
|
||||||
|
const displayTitle = computed(() => props.session?.title?.trim() || t('menu.newSession'))
|
||||||
|
const menuOverlayClass = computed(() => (
|
||||||
|
menuMode.value === 'menu' ? 'chat-header-menu-popup' : 'chat-header-menu-popup is-confirm'
|
||||||
|
))
|
||||||
|
|
||||||
|
function onMenuVisibleChange(visible: boolean): void {
|
||||||
|
if (!visible) menuMode.value = 'menu'
|
||||||
|
}
|
||||||
|
|
||||||
|
function enterConfirmMode(mode: 'clear' | 'delete'): void {
|
||||||
|
menuMode.value = mode
|
||||||
|
}
|
||||||
|
|
||||||
|
function backToMenu(): void {
|
||||||
|
if (busyAction.value) return
|
||||||
|
menuMode.value = 'menu'
|
||||||
|
}
|
||||||
|
|
||||||
|
function onMenuAction(value: string): void {
|
||||||
|
if (value === 'rename') {
|
||||||
|
menuVisible.value = false
|
||||||
|
startTitleEdit()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
menuVisible.value = false
|
||||||
|
handleMenuClick({ value })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyText(text: string): Promise<void> {
|
||||||
|
if (navigator.clipboard?.writeText) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text)
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
// Some browsers expose Clipboard API outside a permitted context.
|
||||||
|
// Fall through to the legacy copy path before reporting a failure.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const textarea = document.createElement('textarea')
|
||||||
|
textarea.value = text
|
||||||
|
textarea.setAttribute('readonly', '')
|
||||||
|
textarea.style.position = 'fixed'
|
||||||
|
textarea.style.opacity = '0'
|
||||||
|
document.body.appendChild(textarea)
|
||||||
|
textarea.select()
|
||||||
|
const copied = document.execCommand('copy')
|
||||||
|
textarea.remove()
|
||||||
|
if (!copied) throw new Error('clipboard unavailable')
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentSessionLink(): string {
|
||||||
|
const url = new URL(window.location.href)
|
||||||
|
url.search = ''
|
||||||
|
url.hash = ''
|
||||||
|
return url.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
function startTitleEdit(): void {
|
||||||
|
if (!props.session || busyAction.value) return
|
||||||
|
menuVisible.value = false
|
||||||
|
titleDraft.value = props.session.title || ''
|
||||||
|
titleEditing.value = true
|
||||||
|
nextTick(() => {
|
||||||
|
titleInputRef.value?.focus()
|
||||||
|
titleInputRef.value?.select()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelTitleEdit(): void {
|
||||||
|
titleEditing.value = false
|
||||||
|
titleDraft.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitTitleEdit(): Promise<void> {
|
||||||
|
// Enter 会先触发 form submit,随后 input blur 再进一次;必须同步退出编辑态防重入。
|
||||||
|
if (!titleEditing.value || busyAction.value) return
|
||||||
|
const session = props.session
|
||||||
|
if (!session) {
|
||||||
|
cancelTitleEdit()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = normalizeSessionTitleDraft(titleDraft.value)
|
||||||
|
const currentTitle = normalizeSessionTitleDraft(session.title || '')
|
||||||
|
titleEditing.value = false
|
||||||
|
titleDraft.value = ''
|
||||||
|
if (!title || title === currentTitle) return
|
||||||
|
|
||||||
|
busyAction.value = 'rename'
|
||||||
|
try {
|
||||||
|
await renameSession(session.id, title, session.description || '')
|
||||||
|
MessagePlugin.success(t('menu.renameSessionSuccess'))
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error(t('menu.renameSessionFailed'))
|
||||||
|
} finally {
|
||||||
|
busyAction.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function togglePin(pinned: boolean): Promise<void> {
|
||||||
|
const session = props.session
|
||||||
|
if (!session || busyAction.value) return
|
||||||
|
busyAction.value = 'pin'
|
||||||
|
try {
|
||||||
|
await setSessionPinned(session.id, pinned)
|
||||||
|
MessagePlugin.success(t(pinned ? 'chatHeader.pinSuccess' : 'chatHeader.unpinSuccess'))
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error(t(pinned ? 'menu.pinFailed' : 'menu.unpinFailed'))
|
||||||
|
} finally {
|
||||||
|
busyAction.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copySessionId(): Promise<void> {
|
||||||
|
if (!props.session) return
|
||||||
|
try {
|
||||||
|
await copyText(props.session.id)
|
||||||
|
MessagePlugin.success(t('chatHeader.sessionIdCopied'))
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error(t('chatHeader.copyFailed'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyLink(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await copyText(currentSessionLink())
|
||||||
|
MessagePlugin.success(t('chatHeader.linkCopied'))
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error(t('chatHeader.copyFailed'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyMarkdown(): Promise<void> {
|
||||||
|
const session = props.session
|
||||||
|
if (!session || busyAction.value) return
|
||||||
|
busyAction.value = 'markdown'
|
||||||
|
try {
|
||||||
|
const messages = await collectAllSessionMessages(async (beforeTime, limit) => {
|
||||||
|
const response: any = await getMessageList({
|
||||||
|
session_id: session.id,
|
||||||
|
created_at: beforeTime,
|
||||||
|
limit,
|
||||||
|
})
|
||||||
|
if (!response?.success || !Array.isArray(response.data)) {
|
||||||
|
throw new Error(response?.message || 'failed to load session messages')
|
||||||
|
}
|
||||||
|
return response.data
|
||||||
|
})
|
||||||
|
const markdown = buildSessionMarkdown({
|
||||||
|
sessionId: session.id,
|
||||||
|
title: session.title || t('menu.newSession'),
|
||||||
|
messages,
|
||||||
|
labels: {
|
||||||
|
sessionId: t('chatHeader.markdown.sessionId'),
|
||||||
|
exportedAt: t('chatHeader.markdown.exportedAt'),
|
||||||
|
user: t('chatHeader.markdown.user'),
|
||||||
|
assistant: t('chatHeader.markdown.assistant'),
|
||||||
|
attachments: t('chatHeader.markdown.attachments'),
|
||||||
|
references: t('chatHeader.markdown.references'),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await copyText(markdown)
|
||||||
|
MessagePlugin.success(t('chatHeader.markdownCopied'))
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error(t('chatHeader.markdownCopyFailed'))
|
||||||
|
} finally {
|
||||||
|
busyAction.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitClearMessages(): Promise<void> {
|
||||||
|
const session = props.session
|
||||||
|
if (!session || busyAction.value) return
|
||||||
|
busyAction.value = 'clear'
|
||||||
|
try {
|
||||||
|
await clearSession(session.id)
|
||||||
|
menuVisible.value = false
|
||||||
|
menuMode.value = 'menu'
|
||||||
|
MessagePlugin.success(t('menu.clearMessagesSuccess'))
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error(t('menu.clearMessagesFailed'))
|
||||||
|
} finally {
|
||||||
|
busyAction.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitDeleteSession(): Promise<void> {
|
||||||
|
const session = props.session
|
||||||
|
if (!session || busyAction.value) return
|
||||||
|
busyAction.value = 'delete'
|
||||||
|
try {
|
||||||
|
await removeSession(session.id)
|
||||||
|
menuVisible.value = false
|
||||||
|
menuMode.value = 'menu'
|
||||||
|
MessagePlugin.success(t('chatHeader.deleteSuccess'))
|
||||||
|
} catch {
|
||||||
|
MessagePlugin.error(t('chat.deleteSessionFailed'))
|
||||||
|
} finally {
|
||||||
|
busyAction.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMenuClick(data: { value: string }): void {
|
||||||
|
switch (data.value) {
|
||||||
|
case 'pin': void togglePin(true); break
|
||||||
|
case 'unpin': void togglePin(false); break
|
||||||
|
case 'copyId': void copySessionId(); break
|
||||||
|
case 'copyLink': void copyLink(); break
|
||||||
|
case 'copyMarkdown': void copyMarkdown(); break
|
||||||
|
case 'openNewWindow': window.open(currentSessionLink(), '_blank', 'noopener,noreferrer'); break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped lang="less">
|
||||||
|
.chat-header {
|
||||||
|
position: absolute;
|
||||||
|
top: 10px;
|
||||||
|
left: 12px;
|
||||||
|
z-index: 6;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 2px;
|
||||||
|
max-width: min(280px, calc(100% - 24px));
|
||||||
|
min-width: 0;
|
||||||
|
padding: 2px 2px 2px 8px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background: color-mix(in srgb, var(--td-bg-color-container) 88%, transparent);
|
||||||
|
backdrop-filter: blur(8px);
|
||||||
|
-webkit-backdrop-filter: blur(8px);
|
||||||
|
pointer-events: auto;
|
||||||
|
|
||||||
|
&.is-editing {
|
||||||
|
max-width: min(360px, calc(100% - 24px));
|
||||||
|
padding: 2px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header__edit {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
width: 240px;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header__edit-input {
|
||||||
|
width: 100%;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0 8px;
|
||||||
|
border: 1px solid var(--td-brand-color);
|
||||||
|
border-radius: 5px;
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
background: var(--td-bg-color-container);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 26px;
|
||||||
|
outline: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
box-shadow: 0 0 0 2px var(--td-brand-color-light);
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header__title {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 0;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
line-height: 20px;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header__title-text {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header__pin {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
color: var(--td-text-color-placeholder);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header__menu-btn {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 5px;
|
||||||
|
color: var(--td-text-color-placeholder);
|
||||||
|
background: transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.15s ease, color 0.15s ease;
|
||||||
|
|
||||||
|
&:hover:not(:disabled) {
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
background: var(--td-bg-color-container-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:active:not(:disabled) {
|
||||||
|
background: var(--td-bg-color-container-active);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-loading {
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header__menu-loading {
|
||||||
|
animation: chat-header-spin 0.8s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes chat-header-spin {
|
||||||
|
from {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<style lang="less">
|
||||||
|
.chat-header-menu-popup {
|
||||||
|
z-index: 99 !important;
|
||||||
|
|
||||||
|
.t-popup__content {
|
||||||
|
padding: 4px !important;
|
||||||
|
margin-top: 2px !important;
|
||||||
|
min-width: 168px !important;
|
||||||
|
width: max-content !important;
|
||||||
|
border-radius: 8px !important;
|
||||||
|
background: var(--td-bg-color-container) !important;
|
||||||
|
border: 0.5px solid var(--td-component-stroke) !important;
|
||||||
|
box-shadow:
|
||||||
|
0 0 0 0.5px rgba(0, 0, 0, 0.03),
|
||||||
|
0 2px 6px rgba(0, 0, 0, 0.08) !important;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-confirm .t-popup__content {
|
||||||
|
padding: 12px !important;
|
||||||
|
width: 260px !important;
|
||||||
|
min-width: 260px !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-menu {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1px;
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-confirm {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
width: 236px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-confirm__title {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-confirm__body {
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-confirm__footer {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-confirm__btn {
|
||||||
|
min-width: 60px;
|
||||||
|
height: 30px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border: 0.5px solid var(--td-component-stroke);
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
background: var(--td-bg-color-container);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 28px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||||
|
|
||||||
|
&:hover:not(:disabled) {
|
||||||
|
background: var(--td-bg-color-container-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-danger {
|
||||||
|
border-color: transparent;
|
||||||
|
color: #fff;
|
||||||
|
background: var(--td-error-color-6);
|
||||||
|
|
||||||
|
&:hover:not(:disabled) {
|
||||||
|
background: var(--td-error-color-5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-menu__item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 32px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 5px;
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
background: transparent;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 20px;
|
||||||
|
text-align: left;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-sizing: border-box;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: var(--td-bg-color-container-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-danger {
|
||||||
|
color: var(--td-error-color-6);
|
||||||
|
|
||||||
|
.chat-header-menu__icon {
|
||||||
|
color: var(--td-error-color-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: var(--td-error-color-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-menu__icon {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
font-size: 16px;
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header-menu__divider {
|
||||||
|
height: 1px;
|
||||||
|
margin: 2px 6px;
|
||||||
|
background: var(--td-component-stroke);
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[theme-mode='dark'] .chat-header-menu-popup .t-popup__content {
|
||||||
|
background: rgba(36, 36, 36, 0.92) !important;
|
||||||
|
border-color: rgba(255, 255, 255, 0.08) !important;
|
||||||
|
box-shadow:
|
||||||
|
0 0 0 0.5px rgba(255, 255, 255, 0.05),
|
||||||
|
0 2px 6px rgba(0, 0, 0, 0.2) !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -37,48 +37,77 @@
|
|||||||
<span class="submenu_title-text">{{ item.title }}</span>
|
<span class="submenu_title-text">{{ item.title }}</span>
|
||||||
</span>
|
</span>
|
||||||
<div v-if="!batchMode" class="session-row-menu-wrap" @click.stop>
|
<div v-if="!batchMode" class="session-row-menu-wrap" @click.stop>
|
||||||
<button
|
<t-popup
|
||||||
ref="triggerRef"
|
v-model:visible="menuOpen"
|
||||||
type="button"
|
:overlay-class-name="menuOverlayClass"
|
||||||
class="menu-more-wrap"
|
trigger="click"
|
||||||
aria-haspopup="menu"
|
destroy-on-close
|
||||||
:aria-expanded="menuOpen"
|
placement="bottom-right"
|
||||||
@click="toggleMenu"
|
@visible-change="onMenuVisibleChange"
|
||||||
>
|
>
|
||||||
<t-icon name="ellipsis" class="menu-more" />
|
<button
|
||||||
</button>
|
type="button"
|
||||||
<Teleport to="body">
|
class="menu-more-wrap"
|
||||||
<div
|
aria-haspopup="menu"
|
||||||
v-if="menuOpen"
|
:aria-expanded="menuOpen"
|
||||||
class="session-row-menu"
|
|
||||||
role="menu"
|
|
||||||
:style="menuStyle"
|
|
||||||
@click.stop
|
@click.stop
|
||||||
>
|
>
|
||||||
<button
|
<t-icon name="ellipsis" class="menu-more" />
|
||||||
v-for="option in menuOptions"
|
</button>
|
||||||
:key="option.value"
|
<template #content>
|
||||||
type="button"
|
<div class="session-action-menu" @click.stop>
|
||||||
class="session-row-menu__item"
|
<template v-if="menuMode === 'menu'">
|
||||||
:class="{ 'session-row-menu__item--error': option.theme === 'error' }"
|
<template v-for="(option, index) in menuOptions" :key="option.value">
|
||||||
role="menuitem"
|
<div
|
||||||
@click="handleMenuClick(option)"
|
v-if="shouldShowDividerBefore(option.value, index)"
|
||||||
>
|
class="session-action-menu__divider"
|
||||||
<component
|
/>
|
||||||
:is="option.prefixIcon"
|
<button
|
||||||
v-if="option.prefixIcon"
|
type="button"
|
||||||
class="session-row-menu__icon"
|
class="session-action-menu__item"
|
||||||
/>
|
:class="{ 'is-danger': option.theme === 'error' }"
|
||||||
<span class="session-row-menu__text">{{ option.content }}</span>
|
@click="handleMenuClick(option)"
|
||||||
</button>
|
>
|
||||||
</div>
|
<component
|
||||||
</Teleport>
|
:is="option.prefixIcon"
|
||||||
|
v-if="option.prefixIcon"
|
||||||
|
class="session-action-menu__icon"
|
||||||
|
/>
|
||||||
|
<span>{{ option.content }}</span>
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div v-else class="session-action-confirm">
|
||||||
|
<div class="session-action-confirm__title">
|
||||||
|
{{ menuMode === 'clear' ? t('chatHeader.clearConfirmTitle') : t('chatHeader.deleteConfirmTitle') }}
|
||||||
|
</div>
|
||||||
|
<div class="session-action-confirm__body">
|
||||||
|
{{ menuMode === 'clear' ? t('chatHeader.clearConfirmBody') : t('chatHeader.deleteConfirmBody') }}
|
||||||
|
</div>
|
||||||
|
<div class="session-action-confirm__footer">
|
||||||
|
<button type="button" class="session-action-confirm__btn" @click="backToMenu">
|
||||||
|
{{ t('common.cancel') }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="session-action-confirm__btn is-danger"
|
||||||
|
@click="confirmDangerAction"
|
||||||
|
>
|
||||||
|
{{ menuMode === 'clear' ? t('common.clear') : t('common.delete') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</t-popup>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onBeforeUnmount, nextTick, ref } from 'vue'
|
import { computed, nextTick, ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
import { normalizeSessionTitleDraft, SESSION_TITLE_MAX_LENGTH } from './sessionTitleEdit'
|
import { normalizeSessionTitleDraft, SESSION_TITLE_MAX_LENGTH } from './sessionTitleEdit'
|
||||||
|
|
||||||
interface SessionMenuOption {
|
interface SessionMenuOption {
|
||||||
@@ -88,6 +117,8 @@ interface SessionMenuOption {
|
|||||||
prefixIcon?: any
|
prefixIcon?: any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type MenuMode = 'menu' | 'clear' | 'delete'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
item: { id: string; path: string; title: string; is_pinned?: boolean }
|
item: { id: string; path: string; title: string; is_pinned?: boolean }
|
||||||
batchMode: boolean
|
batchMode: boolean
|
||||||
@@ -107,59 +138,36 @@ const emit = defineEmits<{
|
|||||||
(e: 'hover-out'): void
|
(e: 'hover-out'): void
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const MENU_WIDTH = 132
|
const { t } = useI18n()
|
||||||
const MENU_GAP = 4
|
|
||||||
const VIEWPORT_MARGIN = 8
|
|
||||||
|
|
||||||
const menuOpen = ref(false)
|
const menuOpen = ref(false)
|
||||||
|
const menuMode = ref<MenuMode>('menu')
|
||||||
const titleEditing = ref(false)
|
const titleEditing = ref(false)
|
||||||
const titleDraft = ref('')
|
const titleDraft = ref('')
|
||||||
const triggerRef = ref<HTMLButtonElement | null>(null)
|
|
||||||
const titleInputRef = ref<HTMLInputElement | null>(null)
|
const titleInputRef = ref<HTMLInputElement | null>(null)
|
||||||
const menuStyle = ref<Record<string, string>>({})
|
|
||||||
|
|
||||||
const updateMenuPosition = (): void => {
|
const menuOverlayClass = computed(() => (
|
||||||
const trigger = triggerRef.value
|
menuMode.value === 'menu'
|
||||||
if (!trigger) return
|
? 'session-action-menu-popup'
|
||||||
const rect = trigger.getBoundingClientRect()
|
: 'session-action-menu-popup is-confirm'
|
||||||
const left = Math.max(
|
))
|
||||||
VIEWPORT_MARGIN,
|
|
||||||
Math.min(rect.right - MENU_WIDTH, window.innerWidth - MENU_WIDTH - VIEWPORT_MARGIN),
|
const onMenuVisibleChange = (visible: boolean): void => {
|
||||||
)
|
if (!visible) menuMode.value = 'menu'
|
||||||
menuStyle.value = {
|
|
||||||
top: `${rect.bottom + MENU_GAP}px`,
|
|
||||||
left: `${left}px`,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeListeners = (): void => {
|
const backToMenu = (): void => {
|
||||||
document.removeEventListener('click', closeMenu)
|
menuMode.value = 'menu'
|
||||||
window.removeEventListener('resize', closeMenu)
|
|
||||||
window.removeEventListener('scroll', closeMenu, true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const closeMenu = (): void => {
|
const shouldShowDividerBefore = (value: string, index: number): boolean => {
|
||||||
menuOpen.value = false
|
if (index === 0) return false
|
||||||
removeListeners()
|
return value === 'clearMessages' || value === 'delete'
|
||||||
}
|
|
||||||
|
|
||||||
const toggleMenu = (): void => {
|
|
||||||
if (menuOpen.value) {
|
|
||||||
closeMenu()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
updateMenuPosition()
|
|
||||||
menuOpen.value = true
|
|
||||||
nextTick(() => {
|
|
||||||
document.addEventListener('click', closeMenu)
|
|
||||||
window.addEventListener('resize', closeMenu)
|
|
||||||
// 捕获阶段监听任意滚动容器,滚动时关闭以避免菜单与触发点错位
|
|
||||||
window.addEventListener('scroll', closeMenu, true)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const startTitleEdit = (): void => {
|
const startTitleEdit = (): void => {
|
||||||
closeMenu()
|
menuOpen.value = false
|
||||||
|
menuMode.value = 'menu'
|
||||||
titleDraft.value = props.item.title || ''
|
titleDraft.value = props.item.title || ''
|
||||||
titleEditing.value = true
|
titleEditing.value = true
|
||||||
nextTick(() => {
|
nextTick(() => {
|
||||||
@@ -174,6 +182,7 @@ const cancelTitleEdit = (): void => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const submitTitleEdit = (): void => {
|
const submitTitleEdit = (): void => {
|
||||||
|
// Enter 会先触发 form submit,随后 input blur 再进一次;必须同步退出编辑态防重入。
|
||||||
if (!titleEditing.value) return
|
if (!titleEditing.value) return
|
||||||
const nextTitle = normalizeSessionTitleDraft(titleDraft.value)
|
const nextTitle = normalizeSessionTitleDraft(titleDraft.value)
|
||||||
const currentTitle = normalizeSessionTitleDraft(props.item.title || '')
|
const currentTitle = normalizeSessionTitleDraft(props.item.title || '')
|
||||||
@@ -188,13 +197,25 @@ const handleMenuClick = (option: SessionMenuOption): void => {
|
|||||||
startTitleEdit()
|
startTitleEdit()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
closeMenu()
|
if (option.value === 'clearMessages') {
|
||||||
|
menuMode.value = 'clear'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (option.value === 'delete') {
|
||||||
|
menuMode.value = 'delete'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
menuOpen.value = false
|
||||||
|
menuMode.value = 'menu'
|
||||||
emit('menu-click', { value: option.value })
|
emit('menu-click', { value: option.value })
|
||||||
}
|
}
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
const confirmDangerAction = (): void => {
|
||||||
removeListeners()
|
const value = menuMode.value === 'clear' ? 'clearMessages' : 'delete'
|
||||||
})
|
menuOpen.value = false
|
||||||
|
menuMode.value = 'menu'
|
||||||
|
emit('menu-click', { value })
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped lang="less">
|
<style scoped lang="less">
|
||||||
@@ -234,57 +255,163 @@ onBeforeUnmount(() => {
|
|||||||
height: 24px;
|
height: 24px;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-radius: 6px;
|
border-radius: 5px;
|
||||||
color: inherit;
|
color: inherit;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
transition: background-color 0.15s ease, color 0.15s ease;
|
||||||
|
|
||||||
.session-row-menu {
|
|
||||||
position: fixed;
|
|
||||||
z-index: 3000;
|
|
||||||
min-width: 132px;
|
|
||||||
padding: 4px;
|
|
||||||
border: 1px solid var(--td-component-stroke);
|
|
||||||
border-radius: 6px;
|
|
||||||
background: var(--td-bg-color-container);
|
|
||||||
box-shadow: var(--td-shadow-2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.session-row-menu__item {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
width: 100%;
|
|
||||||
min-height: 32px;
|
|
||||||
padding: 0 10px;
|
|
||||||
border: 0;
|
|
||||||
border-radius: 4px;
|
|
||||||
color: var(--td-text-color-primary);
|
|
||||||
background: transparent;
|
|
||||||
font-size: 14px;
|
|
||||||
line-height: 20px;
|
|
||||||
text-align: left;
|
|
||||||
cursor: pointer;
|
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
background: var(--td-bg-color-container-hover);
|
background: var(--td-bg-color-container-hover);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
.session-row-menu__item--error {
|
<style lang="less">
|
||||||
color: var(--td-error-color);
|
.session-action-menu-popup {
|
||||||
|
z-index: 3000 !important;
|
||||||
|
|
||||||
|
.t-popup__content {
|
||||||
|
padding: 4px !important;
|
||||||
|
margin-top: 2px !important;
|
||||||
|
min-width: 160px !important;
|
||||||
|
width: max-content !important;
|
||||||
|
border-radius: 8px !important;
|
||||||
|
background: var(--td-bg-color-container) !important;
|
||||||
|
border: 0.5px solid var(--td-component-stroke) !important;
|
||||||
|
box-shadow:
|
||||||
|
0 0 0 0.5px rgba(0, 0, 0, 0.03),
|
||||||
|
0 2px 6px rgba(0, 0, 0, 0.08) !important;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-confirm .t-popup__content {
|
||||||
|
padding: 12px !important;
|
||||||
|
width: 260px !important;
|
||||||
|
min-width: 260px !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.session-row-menu__icon {
|
.session-action-menu {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1px;
|
||||||
|
min-width: 152px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-action-menu__item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 32px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 5px;
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
background: transparent;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 20px;
|
||||||
|
text-align: left;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-sizing: border-box;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: var(--td-bg-color-container-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-danger {
|
||||||
|
color: var(--td-error-color-6);
|
||||||
|
|
||||||
|
.session-action-menu__icon {
|
||||||
|
color: var(--td-error-color-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: var(--td-error-color-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-action-menu__icon {
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
|
||||||
|
.t-icon {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.session-row-menu__text {
|
.session-action-menu__divider {
|
||||||
min-width: 0;
|
height: 1px;
|
||||||
overflow: hidden;
|
margin: 2px 6px;
|
||||||
text-overflow: ellipsis;
|
background: var(--td-component-stroke);
|
||||||
white-space: nowrap;
|
}
|
||||||
|
|
||||||
|
.session-action-confirm {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
width: 236px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-action-confirm__title {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-action-confirm__body {
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-action-confirm__footer {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-action-confirm__btn {
|
||||||
|
min-width: 60px;
|
||||||
|
height: 30px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border: 0.5px solid var(--td-component-stroke);
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--td-text-color-primary);
|
||||||
|
background: var(--td-bg-color-container);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 28px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||||
|
|
||||||
|
&:hover:not(:disabled) {
|
||||||
|
background: var(--td-bg-color-container-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-danger {
|
||||||
|
border-color: transparent;
|
||||||
|
color: #fff;
|
||||||
|
background: var(--td-error-color-6);
|
||||||
|
|
||||||
|
&:hover:not(:disabled) {
|
||||||
|
background: var(--td-error-color-5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[theme-mode='dark'] .session-action-menu-popup .t-popup__content {
|
||||||
|
background: rgba(36, 36, 36, 0.92) !important;
|
||||||
|
border-color: rgba(255, 255, 255, 0.08) !important;
|
||||||
|
box-shadow:
|
||||||
|
0 0 0 0.5px rgba(255, 255, 255, 0.05),
|
||||||
|
0 2px 6px rgba(0, 0, 0, 0.2) !important;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -202,10 +202,18 @@
|
|||||||
import { storeToRefs } from 'pinia';
|
import { storeToRefs } from 'pinia';
|
||||||
import { onMounted, onUnmounted, watch, computed, ref, h, nextTick } from 'vue';
|
import { onMounted, onUnmounted, watch, computed, ref, h, nextTick } from 'vue';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
import { getSessionsList, delSession, batchDelSessions, deleteAllSessions, clearSessionMessages, pinSession, unpinSession, updateSession } from "@/api/chat/index";
|
import { getSessionsList, batchDelSessions, deleteAllSessions } from "@/api/chat/index";
|
||||||
import { useChatResourcesStore } from '@/stores/chatResources';
|
import { useChatResourcesStore } from '@/stores/chatResources';
|
||||||
import { listAllIMChannels } from '@/api/agent/index';
|
import { listAllIMChannels } from '@/api/agent/index';
|
||||||
import SessionSidebarRow from './SessionSidebarRow.vue';
|
import SessionSidebarRow from './SessionSidebarRow.vue';
|
||||||
|
import {
|
||||||
|
clearSession,
|
||||||
|
removeSession,
|
||||||
|
renameSession,
|
||||||
|
SESSION_MUTATION_EVENT,
|
||||||
|
setSessionPinned,
|
||||||
|
type SessionMutationDetail,
|
||||||
|
} from './sessionMutations';
|
||||||
import SessionSourceFilter from './SessionSourceFilter.vue';
|
import SessionSourceFilter from './SessionSourceFilter.vue';
|
||||||
import {
|
import {
|
||||||
SIDEBAR_BUCKET_PAGE_SIZE,
|
SIDEBAR_BUCKET_PAGE_SIZE,
|
||||||
@@ -609,7 +617,7 @@ const buildSessionMenuOptions = (item: any) => {
|
|||||||
options.push({
|
options.push({
|
||||||
content: t('menu.unpin'),
|
content: t('menu.unpin'),
|
||||||
value: 'unpin',
|
value: 'unpin',
|
||||||
prefixIcon: () => h(TIcon, { name: 'pin', size: '16px' }),
|
prefixIcon: () => h(TIcon, { name: 'pin-filled', size: '16px' }),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
options.push({
|
options.push({
|
||||||
@@ -644,19 +652,8 @@ const updateSessionInBuckets = (
|
|||||||
|
|
||||||
const renameSessionTitle = async (item: any, title: string) => {
|
const renameSessionTitle = async (item: any, title: string) => {
|
||||||
try {
|
try {
|
||||||
const res: any = await updateSession(item.id, {
|
await renameSession(item.id, title, item.description || '');
|
||||||
title,
|
MessagePlugin.success(t('menu.renameSessionSuccess'));
|
||||||
description: item.description || '',
|
|
||||||
});
|
|
||||||
if (res && res.success) {
|
|
||||||
updateSessionInBuckets(item.id, {
|
|
||||||
title: res.data?.title || title,
|
|
||||||
isNoTitle: false,
|
|
||||||
});
|
|
||||||
MessagePlugin.success(t('menu.renameSessionSuccess'));
|
|
||||||
} else {
|
|
||||||
MessagePlugin.error(t('menu.renameSessionFailed'));
|
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
MessagePlugin.error(t('menu.renameSessionFailed'));
|
MessagePlugin.error(t('menu.renameSessionFailed'));
|
||||||
}
|
}
|
||||||
@@ -666,17 +663,7 @@ const togglePin = (item: any, pin: boolean) => {
|
|||||||
if (pinningIds.value.has(item.id)) return;
|
if (pinningIds.value.has(item.id)) return;
|
||||||
pinningIds.value.add(item.id);
|
pinningIds.value.add(item.id);
|
||||||
|
|
||||||
const call = pin ? pinSession(item.id) : unpinSession(item.id);
|
setSessionPinned(item.id, pin).catch(() => {
|
||||||
call.then((res: any) => {
|
|
||||||
if (res && res.success) {
|
|
||||||
updateSessionInBuckets(item.id, {
|
|
||||||
is_pinned: pin,
|
|
||||||
pinned_at: pin ? new Date().toISOString() : null,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
MessagePlugin.error(pin ? t('menu.pinFailed') : t('menu.unpinFailed'));
|
|
||||||
}
|
|
||||||
}).catch(() => {
|
|
||||||
MessagePlugin.error(pin ? t('menu.pinFailed') : t('menu.unpinFailed'));
|
MessagePlugin.error(pin ? t('menu.pinFailed') : t('menu.unpinFailed'));
|
||||||
}).finally(() => {
|
}).finally(() => {
|
||||||
pinningIds.value.delete(item.id);
|
pinningIds.value.delete(item.id);
|
||||||
@@ -684,33 +671,15 @@ const togglePin = (item: any, pin: boolean) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const clearMessages = (item: any) => {
|
const clearMessages = (item: any) => {
|
||||||
clearSessionMessages(item.id).then((res: any) => {
|
clearSession(item.id).then(() => {
|
||||||
if (res && res.success) {
|
MessagePlugin.success(t('menu.clearMessagesSuccess'));
|
||||||
MessagePlugin.success(t('menu.clearMessagesSuccess'));
|
|
||||||
if (item.id === route.params.chatid) {
|
|
||||||
window.dispatchEvent(new CustomEvent('session-messages-cleared', { detail: { sessionId: item.id } }));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
MessagePlugin.error(t('menu.clearMessagesFailed'));
|
|
||||||
}
|
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
MessagePlugin.error(t('menu.clearMessagesFailed'));
|
MessagePlugin.error(t('menu.clearMessagesFailed'));
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const delCard = (item: any) => {
|
const delCard = (item: any) => {
|
||||||
delSession(item.id).then((res: any) => {
|
removeSession(item.id).catch(() => MessagePlugin.error(t('chat.deleteSessionFailed')))
|
||||||
if (res && (res as any).success) {
|
|
||||||
sessionBuckets.value = removeSessionFromBuckets(sessionBuckets.value, item.id);
|
|
||||||
syncMenuStoreFromBuckets();
|
|
||||||
|
|
||||||
if (item.id == route.params.chatid) {
|
|
||||||
router.push('/platform/creatChat');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
MessagePlugin.error(t('chat.deleteSessionFailed'));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -964,10 +933,22 @@ const loadSessionOriginMeta = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSessionTitleUpdated = (event: Event) => {
|
const handleSessionMutation = (event: Event) => {
|
||||||
const detail = (event as CustomEvent<{ sessionId?: string; title?: string }>).detail;
|
const detail = (event as CustomEvent<SessionMutationDetail>).detail;
|
||||||
if (!detail?.sessionId || !detail.title) return;
|
if (!detail?.sessionId) return;
|
||||||
updateSessionInBuckets(detail.sessionId, { title: detail.title, isNoTitle: false });
|
if (detail.patch) {
|
||||||
|
updateSessionInBuckets(detail.sessionId, {
|
||||||
|
...detail.patch,
|
||||||
|
...(detail.patch.title ? { isNoTitle: false } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (detail.removed) {
|
||||||
|
sessionBuckets.value = removeSessionFromBuckets(sessionBuckets.value, detail.sessionId);
|
||||||
|
syncMenuStoreFromBuckets();
|
||||||
|
if (detail.sessionId === route.params.chatid) {
|
||||||
|
router.push('/platform/creatChat');
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
@@ -977,7 +958,7 @@ onMounted(async () => {
|
|||||||
currentSecondpath.value = `chat/${route.params.chatid}`;
|
currentSecondpath.value = `chat/${route.params.chatid}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('session-title-updated', handleSessionTitleUpdated);
|
window.addEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);
|
||||||
|
|
||||||
isLiteEdition.value = authStore.isLiteMode
|
isLiteEdition.value = authStore.isLiteMode
|
||||||
getSystemInfo().then(res => {
|
getSystemInfo().then(res => {
|
||||||
@@ -1003,7 +984,7 @@ onMounted(async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
window.removeEventListener('session-title-updated', handleSessionTitleUpdated);
|
window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);
|
||||||
});
|
});
|
||||||
|
|
||||||
watch([() => route.name, () => route.params], (newvalue, oldvalue) => {
|
watch([() => route.name, () => route.params], (newvalue, oldvalue) => {
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import {
|
||||||
|
clearSessionMessages,
|
||||||
|
delSession,
|
||||||
|
pinSession,
|
||||||
|
unpinSession,
|
||||||
|
updateSession,
|
||||||
|
} from '@/api/chat'
|
||||||
|
|
||||||
|
export const SESSION_MUTATION_EVENT = 'weknora:session-mutation'
|
||||||
|
|
||||||
|
export interface SessionMutationPatch {
|
||||||
|
title?: string
|
||||||
|
is_pinned?: boolean
|
||||||
|
pinned_at?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionMutationDetail {
|
||||||
|
sessionId: string
|
||||||
|
patch?: SessionMutationPatch
|
||||||
|
messagesCleared?: boolean
|
||||||
|
removed?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function notifySessionMutation(detail: SessionMutationDetail): void {
|
||||||
|
if (typeof window === 'undefined') return
|
||||||
|
window.dispatchEvent(new CustomEvent<SessionMutationDetail>(SESSION_MUTATION_EVENT, { detail }))
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureSuccess(response: any): any {
|
||||||
|
if (!response?.success) {
|
||||||
|
throw new Error(response?.message || 'session mutation failed')
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function renameSession(
|
||||||
|
sessionId: string,
|
||||||
|
title: string,
|
||||||
|
description = '',
|
||||||
|
): Promise<any> {
|
||||||
|
const response = ensureSuccess(await updateSession(sessionId, { title, description }))
|
||||||
|
const nextTitle = response.data?.title || title
|
||||||
|
notifySessionMutation({ sessionId, patch: { title: nextTitle } })
|
||||||
|
return response.data
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setSessionPinned(sessionId: string, pinned: boolean): Promise<void> {
|
||||||
|
const response = ensureSuccess(pinned ? await pinSession(sessionId) : await unpinSession(sessionId))
|
||||||
|
notifySessionMutation({
|
||||||
|
sessionId,
|
||||||
|
patch: {
|
||||||
|
is_pinned: pinned,
|
||||||
|
pinned_at: pinned ? new Date().toISOString() : null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearSession(sessionId: string): Promise<void> {
|
||||||
|
ensureSuccess(await clearSessionMessages(sessionId))
|
||||||
|
notifySessionMutation({ sessionId, messagesCleared: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeSession(sessionId: string): Promise<void> {
|
||||||
|
ensureSuccess(await delSession(sessionId))
|
||||||
|
notifySessionMutation({ sessionId, removed: true })
|
||||||
|
}
|
||||||
@@ -43,6 +43,37 @@ export default {
|
|||||||
noSessions: 'No conversations yet',
|
noSessions: 'No conversations yet',
|
||||||
loadMoreSessions: 'Load more',
|
loadMoreSessions: 'Load more',
|
||||||
},
|
},
|
||||||
|
chatHeader: {
|
||||||
|
moreActions: 'More conversation actions',
|
||||||
|
copySessionId: 'Copy Session ID',
|
||||||
|
copyLink: 'Copy Conversation Link',
|
||||||
|
copyMarkdown: 'Copy as Markdown',
|
||||||
|
openNewWindow: 'Open in New Window',
|
||||||
|
deleteSession: 'Delete Conversation',
|
||||||
|
renameTitle: 'Rename Conversation',
|
||||||
|
renamePlaceholder: 'Enter a conversation title',
|
||||||
|
renameRequired: 'Conversation title is required',
|
||||||
|
pinSuccess: 'Conversation pinned',
|
||||||
|
unpinSuccess: 'Conversation unpinned',
|
||||||
|
sessionIdCopied: 'Session ID copied',
|
||||||
|
linkCopied: 'Conversation link copied',
|
||||||
|
copyFailed: 'Copy failed. Check your browser clipboard permission.',
|
||||||
|
markdownCopied: 'Full conversation copied as Markdown',
|
||||||
|
markdownCopyFailed: 'Failed to copy Markdown. Please try again.',
|
||||||
|
clearConfirmTitle: 'Clear Conversation Messages',
|
||||||
|
clearConfirmBody: 'Clear all messages in this conversation? The conversation will remain, but this cannot be undone.',
|
||||||
|
deleteConfirmTitle: 'Delete Conversation',
|
||||||
|
deleteConfirmBody: 'Delete this conversation? This cannot be undone.',
|
||||||
|
deleteSuccess: 'Conversation deleted',
|
||||||
|
markdown: {
|
||||||
|
sessionId: 'Session ID',
|
||||||
|
exportedAt: 'Exported at',
|
||||||
|
user: 'User',
|
||||||
|
assistant: 'Assistant',
|
||||||
|
attachments: 'Attachments',
|
||||||
|
references: 'References',
|
||||||
|
},
|
||||||
|
},
|
||||||
newUserGuide: {
|
newUserGuide: {
|
||||||
stepOf: '{current} / {total}',
|
stepOf: '{current} / {total}',
|
||||||
skip: 'Skip',
|
skip: 'Skip',
|
||||||
|
|||||||
@@ -43,6 +43,37 @@ export default {
|
|||||||
noSessions: "대화가 없습니다",
|
noSessions: "대화가 없습니다",
|
||||||
loadMoreSessions: "더 보기",
|
loadMoreSessions: "더 보기",
|
||||||
},
|
},
|
||||||
|
chatHeader: {
|
||||||
|
moreActions: "대화 추가 작업",
|
||||||
|
copySessionId: "세션 ID 복사",
|
||||||
|
copyLink: "대화 링크 복사",
|
||||||
|
copyMarkdown: "Markdown으로 복사",
|
||||||
|
openNewWindow: "새 창에서 열기",
|
||||||
|
deleteSession: "대화 삭제",
|
||||||
|
renameTitle: "대화 제목 수정",
|
||||||
|
renamePlaceholder: "대화 제목을 입력하세요",
|
||||||
|
renameRequired: "대화 제목은 비워 둘 수 없습니다",
|
||||||
|
pinSuccess: "대화가 고정되었습니다",
|
||||||
|
unpinSuccess: "대화 고정이 해제되었습니다",
|
||||||
|
sessionIdCopied: "세션 ID가 복사되었습니다",
|
||||||
|
linkCopied: "대화 링크가 복사되었습니다",
|
||||||
|
copyFailed: "복사하지 못했습니다. 브라우저 클립보드 권한을 확인하세요.",
|
||||||
|
markdownCopied: "전체 대화가 Markdown으로 복사되었습니다",
|
||||||
|
markdownCopyFailed: "Markdown 복사에 실패했습니다. 다시 시도하세요.",
|
||||||
|
clearConfirmTitle: "대화 메시지 지우기",
|
||||||
|
clearConfirmBody: "현재 대화의 모든 메시지를 지울까요? 대화는 유지되지만 복구할 수 없습니다.",
|
||||||
|
deleteConfirmTitle: "대화 삭제",
|
||||||
|
deleteConfirmBody: "현재 대화를 삭제할까요? 삭제 후에는 복구할 수 없습니다.",
|
||||||
|
deleteSuccess: "대화가 삭제되었습니다",
|
||||||
|
markdown: {
|
||||||
|
sessionId: "세션 ID",
|
||||||
|
exportedAt: "내보낸 시간",
|
||||||
|
user: "사용자",
|
||||||
|
assistant: "어시스턴트",
|
||||||
|
attachments: "첨부 파일",
|
||||||
|
references: "참조",
|
||||||
|
},
|
||||||
|
},
|
||||||
newUserGuide: {
|
newUserGuide: {
|
||||||
stepOf: "{current} / {total}",
|
stepOf: "{current} / {total}",
|
||||||
skip: "건너뛰기",
|
skip: "건너뛰기",
|
||||||
|
|||||||
@@ -43,6 +43,37 @@ export default {
|
|||||||
integrations: 'Публикация и интеграция',
|
integrations: 'Публикация и интеграция',
|
||||||
organizations: 'Общие пространства'
|
organizations: 'Общие пространства'
|
||||||
},
|
},
|
||||||
|
chatHeader: {
|
||||||
|
moreActions: 'Другие действия с диалогом',
|
||||||
|
copySessionId: 'Копировать ID сессии',
|
||||||
|
copyLink: 'Копировать ссылку на диалог',
|
||||||
|
copyMarkdown: 'Копировать как Markdown',
|
||||||
|
openNewWindow: 'Открыть в новом окне',
|
||||||
|
deleteSession: 'Удалить диалог',
|
||||||
|
renameTitle: 'Переименовать диалог',
|
||||||
|
renamePlaceholder: 'Введите название диалога',
|
||||||
|
renameRequired: 'Название диалога не может быть пустым',
|
||||||
|
pinSuccess: 'Диалог закреплён',
|
||||||
|
unpinSuccess: 'Диалог откреплён',
|
||||||
|
sessionIdCopied: 'ID сессии скопирован',
|
||||||
|
linkCopied: 'Ссылка на диалог скопирована',
|
||||||
|
copyFailed: 'Не удалось скопировать. Проверьте разрешение браузера на доступ к буферу обмена.',
|
||||||
|
markdownCopied: 'Весь диалог скопирован как Markdown',
|
||||||
|
markdownCopyFailed: 'Не удалось скопировать Markdown. Повторите попытку.',
|
||||||
|
clearConfirmTitle: 'Очистить сообщения диалога',
|
||||||
|
clearConfirmBody: 'Очистить все сообщения? Диалог останется, но это действие нельзя отменить.',
|
||||||
|
deleteConfirmTitle: 'Удалить диалог',
|
||||||
|
deleteConfirmBody: 'Удалить этот диалог? Это действие нельзя отменить.',
|
||||||
|
deleteSuccess: 'Диалог удалён',
|
||||||
|
markdown: {
|
||||||
|
sessionId: 'ID сессии',
|
||||||
|
exportedAt: 'Время экспорта',
|
||||||
|
user: 'Пользователь',
|
||||||
|
assistant: 'Ассистент',
|
||||||
|
attachments: 'Вложения',
|
||||||
|
references: 'Источники',
|
||||||
|
},
|
||||||
|
},
|
||||||
newUserGuide: {
|
newUserGuide: {
|
||||||
stepOf: '{current} / {total}',
|
stepOf: '{current} / {total}',
|
||||||
skip: 'Пропустить',
|
skip: 'Пропустить',
|
||||||
|
|||||||
@@ -43,6 +43,37 @@ export default {
|
|||||||
noSessions: "暂无对话",
|
noSessions: "暂无对话",
|
||||||
loadMoreSessions: "加载更多",
|
loadMoreSessions: "加载更多",
|
||||||
},
|
},
|
||||||
|
chatHeader: {
|
||||||
|
moreActions: "更多对话操作",
|
||||||
|
copySessionId: "复制会话 ID",
|
||||||
|
copyLink: "复制对话链接",
|
||||||
|
copyMarkdown: "复制为 Markdown",
|
||||||
|
openNewWindow: "在新窗口中打开",
|
||||||
|
deleteSession: "删除对话",
|
||||||
|
renameTitle: "修改对话标题",
|
||||||
|
renamePlaceholder: "输入对话标题",
|
||||||
|
renameRequired: "对话标题不能为空",
|
||||||
|
pinSuccess: "对话已置顶",
|
||||||
|
unpinSuccess: "已取消置顶",
|
||||||
|
sessionIdCopied: "会话 ID 已复制",
|
||||||
|
linkCopied: "对话链接已复制",
|
||||||
|
copyFailed: "复制失败,请检查浏览器剪贴板权限",
|
||||||
|
markdownCopied: "完整对话已复制为 Markdown",
|
||||||
|
markdownCopyFailed: "复制 Markdown 失败,请稍后重试",
|
||||||
|
clearConfirmTitle: "清空对话消息",
|
||||||
|
clearConfirmBody: "确认清空当前对话的全部消息?对话本身会保留,此操作无法恢复。",
|
||||||
|
deleteConfirmTitle: "删除对话",
|
||||||
|
deleteConfirmBody: "确认删除当前对话?删除后将无法恢复。",
|
||||||
|
deleteSuccess: "对话已删除",
|
||||||
|
markdown: {
|
||||||
|
sessionId: "会话 ID",
|
||||||
|
exportedAt: "导出时间",
|
||||||
|
user: "用户",
|
||||||
|
assistant: "助手",
|
||||||
|
attachments: "附件",
|
||||||
|
references: "引用",
|
||||||
|
},
|
||||||
|
},
|
||||||
newUserGuide: {
|
newUserGuide: {
|
||||||
stepOf: "{current} / {total}",
|
stepOf: "{current} / {total}",
|
||||||
skip: "跳过引导",
|
skip: "跳过引导",
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { buildSessionMarkdown, collectAllSessionMessages } from './sessionMarkdown'
|
||||||
|
|
||||||
|
const labels = {
|
||||||
|
sessionId: 'Session ID',
|
||||||
|
exportedAt: 'Exported at',
|
||||||
|
user: 'User',
|
||||||
|
assistant: 'Assistant',
|
||||||
|
attachments: 'Attachments',
|
||||||
|
references: 'References',
|
||||||
|
}
|
||||||
|
|
||||||
|
test('collectAllSessionMessages walks backwards and returns chronological unique messages', async () => {
|
||||||
|
const pages: Record<string, any[]> = {
|
||||||
|
'': [
|
||||||
|
{ id: '3', role: 'user', content: 'new question', created_at: '2026-01-03T00:00:00Z' },
|
||||||
|
{ id: '4', role: 'assistant', content: 'new answer', created_at: '2026-01-04T00:00:00Z' },
|
||||||
|
],
|
||||||
|
'2026-01-03T00:00:00Z': [
|
||||||
|
{ id: '1', role: 'user', content: 'old question', created_at: '2026-01-01T00:00:00Z' },
|
||||||
|
{ id: '2', role: 'assistant', content: 'old answer', created_at: '2026-01-02T00:00:00Z' },
|
||||||
|
],
|
||||||
|
'2026-01-01T00:00:00Z': [],
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await collectAllSessionMessages(async (beforeTime) => pages[beforeTime], 2)
|
||||||
|
assert.deepEqual(result.map((message) => message.id), ['1', '2', '3', '4'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('buildSessionMarkdown exports visible conversation content without internal citation tags', () => {
|
||||||
|
const markdown = buildSessionMarkdown({
|
||||||
|
sessionId: 'session-1',
|
||||||
|
title: 'Example chat',
|
||||||
|
exportedAt: '2026-01-05T00:00:00Z',
|
||||||
|
labels,
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
role: 'user',
|
||||||
|
content: 'Read this file',
|
||||||
|
attachments: [{ file_name: 'notes.md' }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
role: 'assistant',
|
||||||
|
content: 'Done. <kb doc="notes.md" chunk_id="1" />',
|
||||||
|
knowledge_references: [
|
||||||
|
{ knowledge_title: 'Notes', knowledge_source: 'https://example.com/notes' },
|
||||||
|
{ knowledge_title: 'Notes', knowledge_source: 'https://example.com/notes' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ role: 'system', content: 'hidden system prompt' },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.match(markdown, /^# Example chat/)
|
||||||
|
assert.match(markdown, /## User\n\nRead this file/)
|
||||||
|
assert.match(markdown, /### Attachments\n\n- notes\.md/)
|
||||||
|
assert.match(markdown, /## Assistant\n\nDone\./)
|
||||||
|
assert.match(markdown, /- \[Notes\]\(https:\/\/example\.com\/notes\)/)
|
||||||
|
assert.doesNotMatch(markdown, /<kb/)
|
||||||
|
assert.doesNotMatch(markdown, /hidden system prompt/)
|
||||||
|
assert.equal(markdown.match(/\[Notes\]/g)?.length, 1)
|
||||||
|
})
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { KB_WEB_TAG_RE } from './citationMarkdown'
|
||||||
|
|
||||||
|
export interface SessionExportAttachment {
|
||||||
|
file_name?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionExportReference {
|
||||||
|
knowledge_title?: string
|
||||||
|
knowledge_filename?: string
|
||||||
|
knowledge_source?: string
|
||||||
|
chunk_type?: string
|
||||||
|
metadata?: Record<string, string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionExportMessage {
|
||||||
|
id?: string
|
||||||
|
role?: string
|
||||||
|
content?: string
|
||||||
|
created_at?: string
|
||||||
|
attachments?: SessionExportAttachment[]
|
||||||
|
knowledge_references?: SessionExportReference[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionMarkdownLabels {
|
||||||
|
sessionId: string
|
||||||
|
exportedAt: string
|
||||||
|
user: string
|
||||||
|
assistant: string
|
||||||
|
attachments: string
|
||||||
|
references: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionMessagePageFetcher {
|
||||||
|
(beforeTime: string, limit: number): Promise<SessionExportMessage[]>
|
||||||
|
}
|
||||||
|
|
||||||
|
const roleOrder = (role?: string): number => {
|
||||||
|
if (role === 'user') return 0
|
||||||
|
if (role === 'assistant') return 1
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function collectAllSessionMessages(
|
||||||
|
fetchPage: SessionMessagePageFetcher,
|
||||||
|
pageSize = 100,
|
||||||
|
maxPages = 500,
|
||||||
|
): Promise<SessionExportMessage[]> {
|
||||||
|
const pages: SessionExportMessage[][] = []
|
||||||
|
let beforeTime = ''
|
||||||
|
|
||||||
|
for (let pageIndex = 0; pageIndex < maxPages; pageIndex += 1) {
|
||||||
|
const page = await fetchPage(beforeTime, pageSize)
|
||||||
|
if (!Array.isArray(page) || page.length === 0) break
|
||||||
|
pages.unshift(page)
|
||||||
|
|
||||||
|
const oldestTime = page[0]?.created_at || ''
|
||||||
|
if (page.length < pageSize || !oldestTime || oldestTime === beforeTime) break
|
||||||
|
beforeTime = oldestTime
|
||||||
|
}
|
||||||
|
|
||||||
|
const seen = new Set<string>()
|
||||||
|
return pages
|
||||||
|
.flat()
|
||||||
|
.filter((message) => {
|
||||||
|
const key = message.id
|
||||||
|
|| `${message.role || ''}:${message.created_at || ''}:${message.content || ''}`
|
||||||
|
if (seen.has(key)) return false
|
||||||
|
seen.add(key)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
.sort((a, b) => {
|
||||||
|
const timeCompare = String(a.created_at || '').localeCompare(String(b.created_at || ''))
|
||||||
|
return timeCompare || roleOrder(a.role) - roleOrder(b.role)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanMessageContent(content?: string): string {
|
||||||
|
return String(content || '')
|
||||||
|
.replace(KB_WEB_TAG_RE, '')
|
||||||
|
.replace(/[ \t]+\n/g, '\n')
|
||||||
|
.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function markdownListText(value: string): string {
|
||||||
|
return value.replace(/\s+/g, ' ').replace(/([\\`*_[\]<>])/g, '\\$1').trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function isHttpUrl(value: string): boolean {
|
||||||
|
return /^https?:\/\//i.test(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function referenceLine(reference: SessionExportReference): string {
|
||||||
|
const title = reference.knowledge_title
|
||||||
|
|| reference.knowledge_filename
|
||||||
|
|| reference.metadata?.title
|
||||||
|
|| reference.knowledge_source
|
||||||
|
|| ''
|
||||||
|
if (!title) return ''
|
||||||
|
|
||||||
|
const source = reference.metadata?.url || reference.knowledge_source || ''
|
||||||
|
const safeTitle = markdownListText(title)
|
||||||
|
return isHttpUrl(source) ? `- [${safeTitle}](${source})` : `- ${safeTitle}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildSessionMarkdown(options: {
|
||||||
|
sessionId: string
|
||||||
|
title: string
|
||||||
|
messages: SessionExportMessage[]
|
||||||
|
labels: SessionMarkdownLabels
|
||||||
|
exportedAt?: string
|
||||||
|
}): string {
|
||||||
|
const { sessionId, labels } = options
|
||||||
|
const title = options.title.replace(/\s+/g, ' ').trim() || sessionId
|
||||||
|
const exportedAt = options.exportedAt || new Date().toISOString()
|
||||||
|
const blocks = [
|
||||||
|
`# ${title.replace(/^#+\s*/, '')}`,
|
||||||
|
`> ${labels.sessionId}: ${sessionId} `,
|
||||||
|
`> ${labels.exportedAt}: ${exportedAt}`,
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const message of options.messages) {
|
||||||
|
if (message.role !== 'user' && message.role !== 'assistant') continue
|
||||||
|
const content = cleanMessageContent(message.content)
|
||||||
|
const attachments = (message.attachments || [])
|
||||||
|
.map((attachment) => attachment.file_name?.trim() || '')
|
||||||
|
.filter(Boolean)
|
||||||
|
const references = [...new Set(
|
||||||
|
(message.knowledge_references || []).map(referenceLine).filter(Boolean),
|
||||||
|
)]
|
||||||
|
if (!content && attachments.length === 0 && references.length === 0) continue
|
||||||
|
|
||||||
|
blocks.push(`## ${message.role === 'user' ? labels.user : labels.assistant}`)
|
||||||
|
if (content) blocks.push(content)
|
||||||
|
if (attachments.length > 0) {
|
||||||
|
blocks.push(`### ${labels.attachments}`, ...attachments.map((name) => `- ${markdownListText(name)}`))
|
||||||
|
}
|
||||||
|
if (references.length > 0) {
|
||||||
|
blocks.push(`### ${labels.references}`, ...references)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${blocks.join('\n\n')}\n`
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
'is-sidebar-collapsed': uiStore.sidebarCollapsed,
|
'is-sidebar-collapsed': uiStore.sidebarCollapsed,
|
||||||
'has-references-panel': referencesDrawerVisible,
|
'has-references-panel': referencesDrawerVisible,
|
||||||
}">
|
}">
|
||||||
|
<ChatHeader v-if="!embeddedMode" :session="currentSession" />
|
||||||
<div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll">
|
<div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll">
|
||||||
<div class="msg_list" :class="{ 'is-embedded': embeddedMode }">
|
<div class="msg_list" :class="{ 'is-embedded': embeddedMode }">
|
||||||
<!-- 消息列表骨架屏 -->
|
<!-- 消息列表骨架屏 -->
|
||||||
@@ -146,6 +147,11 @@ import { clearCitationChunkCache } from '@/utils/citationChunkCache';
|
|||||||
import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue';
|
import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue';
|
||||||
import ChatAttachmentPreviewDrawer from '@/components/ChatAttachmentPreviewDrawer.vue';
|
import ChatAttachmentPreviewDrawer from '@/components/ChatAttachmentPreviewDrawer.vue';
|
||||||
import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue';
|
import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue';
|
||||||
|
import ChatHeader from '@/components/ChatHeader.vue';
|
||||||
|
import {
|
||||||
|
notifySessionMutation,
|
||||||
|
SESSION_MUTATION_EVENT,
|
||||||
|
} from '@/components/sessionMutations';
|
||||||
import {
|
import {
|
||||||
ensureMessageSuggestions,
|
ensureMessageSuggestions,
|
||||||
getMessageSuggestions,
|
getMessageSuggestions,
|
||||||
@@ -208,6 +214,7 @@ const attachStreamDebugToMessage = (message) => {
|
|||||||
};
|
};
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const session_id = ref(props.session_id || route.params.chatid);
|
const session_id = ref(props.session_id || route.params.chatid);
|
||||||
|
const currentSession = ref(null);
|
||||||
|
|
||||||
// 拉 session 详情,并按其 last_request_state 把输入栏状态恢复到当时的发起态。
|
// 拉 session 详情,并按其 last_request_state 把输入栏状态恢复到当时的发起态。
|
||||||
// 嵌入式(embeddedMode)由宿主页面注入 agent/KB,所以跳过整套恢复逻辑,
|
// 嵌入式(embeddedMode)由宿主页面注入 agent/KB,所以跳过整套恢复逻辑,
|
||||||
@@ -216,7 +223,8 @@ const loadSessionAndHydrate = async (sid) => {
|
|||||||
if (!sid || props.embeddedMode) return;
|
if (!sid || props.embeddedMode) return;
|
||||||
try {
|
try {
|
||||||
const sessionRes = await getSession(sid);
|
const sessionRes = await getSession(sid);
|
||||||
if (sessionRes?.data) {
|
if (sessionRes?.data && sid === session_id.value) {
|
||||||
|
currentSession.value = sessionRes.data;
|
||||||
const lastState = sessionRes.data.last_request_state;
|
const lastState = sessionRes.data.last_request_state;
|
||||||
if (lastState) {
|
if (lastState) {
|
||||||
// 先把当前的"全局默认"快照下来,再用 session 状态覆盖;
|
// 先把当前的"全局默认"快照下来,再用 session 状态覆盖;
|
||||||
@@ -434,6 +442,7 @@ watch([() => route.params], async (newvalue) => {
|
|||||||
}
|
}
|
||||||
messagesList.splice(0);
|
messagesList.splice(0);
|
||||||
session_id.value = newvalue[0].chatid;
|
session_id.value = newvalue[0].chatid;
|
||||||
|
currentSession.value = null;
|
||||||
clearCitationChunkCache();
|
clearCitationChunkCache();
|
||||||
|
|
||||||
// 切换会话时,重置状态
|
// 切换会话时,重置状态
|
||||||
@@ -909,17 +918,27 @@ onChunk((data) => {
|
|||||||
});
|
});
|
||||||
usemenuStore.updatasessionTitle(data.data.session_id, title);
|
usemenuStore.updatasessionTitle(data.data.session_id, title);
|
||||||
usemenuStore.changeIsFirstSession(false);
|
usemenuStore.changeIsFirstSession(false);
|
||||||
window.dispatchEvent(new CustomEvent('session-title-updated', {
|
notifySessionMutation({
|
||||||
detail: { sessionId: data.data.session_id, title },
|
sessionId: data.data.session_id,
|
||||||
}));
|
patch: { title },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
processStreamChunk(data);
|
processStreamChunk(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleSessionCleared = (e) => {
|
const handleSessionMutation = (event) => {
|
||||||
if (e.detail?.sessionId === session_id.value) {
|
const detail = event.detail;
|
||||||
|
if (detail?.sessionId !== session_id.value) return;
|
||||||
|
|
||||||
|
if (detail.patch) {
|
||||||
|
currentSession.value = {
|
||||||
|
...(currentSession.value || { id: session_id.value }),
|
||||||
|
...detail.patch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (detail.messagesCleared) {
|
||||||
messagesList.splice(0);
|
messagesList.splice(0);
|
||||||
created_at.value = '';
|
created_at.value = '';
|
||||||
hasMoreHistory.value = true;
|
hasMoreHistory.value = true;
|
||||||
@@ -947,7 +966,7 @@ onBeforeMount(async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
window.addEventListener('session-messages-cleared', handleSessionCleared);
|
window.addEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);
|
||||||
messagesList.splice(0);
|
messagesList.splice(0);
|
||||||
|
|
||||||
// 初始化状态:加载历史消息时不应显示loading
|
// 初始化状态:加载历史消息时不应显示loading
|
||||||
@@ -988,7 +1007,7 @@ const clearData = () => {
|
|||||||
isImRecovering.value = false;
|
isImRecovering.value = false;
|
||||||
}
|
}
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
window.removeEventListener('session-messages-cleared', handleSessionCleared);
|
window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);
|
||||||
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
|
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
|
||||||
});
|
});
|
||||||
onBeforeRouteLeave((to, from, next) => {
|
onBeforeRouteLeave((to, from, next) => {
|
||||||
@@ -1008,7 +1027,7 @@ onBeforeRouteUpdate((to, from, next) => {
|
|||||||
.chat {
|
.chat {
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
// 右侧不留 padding,滚动条贴到内容区最右缘
|
// 右侧不留 padding,滚动条贴到内容区最右缘
|
||||||
padding: 20px 0 20px 20px;
|
padding: 0 0 20px 20px;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
// The parent .platform-route-outlet is a flex column with min-height:0
|
// The parent .platform-route-outlet is a flex column with min-height:0
|
||||||
@@ -1086,6 +1105,8 @@ onBeforeRouteUpdate((to, from, next) => {
|
|||||||
// this box instead of stretching it.
|
// this box instead of stretching it.
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
padding-top: 8px;
|
||||||
|
box-sizing: border-box;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
// 使用系统原生滚动条(macOS 滚动时自动显示 overlay 滚动条,类似 ChatGPT)
|
// 使用系统原生滚动条(macOS 滚动时自动显示 overlay 滚动条,类似 ChatGPT)
|
||||||
scrollbar-width: auto;
|
scrollbar-width: auto;
|
||||||
|
|||||||
Reference in New Issue
Block a user