From 1a2021b3f87077d42a8b7e6675e6c28d0907eab3 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 17 Jul 2026 16:15:18 +0800 Subject: [PATCH] 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. --- frontend/src/components/ChatHeader.vue | 641 ++++++++++++++++++ frontend/src/components/SessionSidebarRow.vue | 357 ++++++---- frontend/src/components/menu.vue | 87 +-- frontend/src/components/sessionMutations.ts | 66 ++ frontend/src/i18n/locales/en-US.ts | 31 + frontend/src/i18n/locales/ko-KR.ts | 31 + frontend/src/i18n/locales/ru-RU.ts | 31 + frontend/src/i18n/locales/zh-CN.ts | 31 + frontend/src/utils/sessionMarkdown.test.ts | 63 ++ frontend/src/utils/sessionMarkdown.ts | 143 ++++ frontend/src/views/chat/index.vue | 39 +- 11 files changed, 1343 insertions(+), 177 deletions(-) create mode 100644 frontend/src/components/ChatHeader.vue create mode 100644 frontend/src/components/sessionMutations.ts create mode 100644 frontend/src/utils/sessionMarkdown.test.ts create mode 100644 frontend/src/utils/sessionMarkdown.ts diff --git a/frontend/src/components/ChatHeader.vue b/frontend/src/components/ChatHeader.vue new file mode 100644 index 00000000..c5549eff --- /dev/null +++ b/frontend/src/components/ChatHeader.vue @@ -0,0 +1,641 @@ + + + + + + + diff --git a/frontend/src/components/SessionSidebarRow.vue b/frontend/src/components/SessionSidebarRow.vue index 4a199cbc..0ff20766 100644 --- a/frontend/src/components/SessionSidebarRow.vue +++ b/frontend/src/components/SessionSidebarRow.vue @@ -37,48 +37,77 @@ {{ item.title }}
- - - - + + + +
-.session-row-menu__item--error { - color: var(--td-error-color); + diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index 3b2d2415..f45622a7 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -202,10 +202,18 @@ import { storeToRefs } from 'pinia'; import { onMounted, onUnmounted, watch, computed, ref, h, nextTick } from 'vue'; 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 { listAllIMChannels } from '@/api/agent/index'; import SessionSidebarRow from './SessionSidebarRow.vue'; +import { + clearSession, + removeSession, + renameSession, + SESSION_MUTATION_EVENT, + setSessionPinned, + type SessionMutationDetail, +} from './sessionMutations'; import SessionSourceFilter from './SessionSourceFilter.vue'; import { SIDEBAR_BUCKET_PAGE_SIZE, @@ -609,7 +617,7 @@ const buildSessionMenuOptions = (item: any) => { options.push({ content: t('menu.unpin'), value: 'unpin', - prefixIcon: () => h(TIcon, { name: 'pin', size: '16px' }), + prefixIcon: () => h(TIcon, { name: 'pin-filled', size: '16px' }), }); } else { options.push({ @@ -644,19 +652,8 @@ const updateSessionInBuckets = ( const renameSessionTitle = async (item: any, title: string) => { try { - const res: any = await updateSession(item.id, { - title, - 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')); - } + await renameSession(item.id, title, item.description || ''); + MessagePlugin.success(t('menu.renameSessionSuccess')); } catch { MessagePlugin.error(t('menu.renameSessionFailed')); } @@ -666,17 +663,7 @@ const togglePin = (item: any, pin: boolean) => { if (pinningIds.value.has(item.id)) return; pinningIds.value.add(item.id); - const call = pin ? pinSession(item.id) : unpinSession(item.id); - 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(() => { + setSessionPinned(item.id, pin).catch(() => { MessagePlugin.error(pin ? t('menu.pinFailed') : t('menu.unpinFailed')); }).finally(() => { pinningIds.value.delete(item.id); @@ -684,33 +671,15 @@ const togglePin = (item: any, pin: boolean) => { }; const clearMessages = (item: any) => { - clearSessionMessages(item.id).then((res: any) => { - if (res && res.success) { - 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')); - } + clearSession(item.id).then(() => { + MessagePlugin.success(t('menu.clearMessagesSuccess')); }).catch(() => { MessagePlugin.error(t('menu.clearMessagesFailed')); }); }; const delCard = (item: any) => { - delSession(item.id).then((res: any) => { - 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')); - } - }) + removeSession(item.id).catch(() => MessagePlugin.error(t('chat.deleteSessionFailed'))) } @@ -964,10 +933,22 @@ const loadSessionOriginMeta = async () => { } }; -const handleSessionTitleUpdated = (event: Event) => { - const detail = (event as CustomEvent<{ sessionId?: string; title?: string }>).detail; - if (!detail?.sessionId || !detail.title) return; - updateSessionInBuckets(detail.sessionId, { title: detail.title, isNoTitle: false }); +const handleSessionMutation = (event: Event) => { + const detail = (event as CustomEvent).detail; + if (!detail?.sessionId) return; + 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 () => { @@ -977,7 +958,7 @@ onMounted(async () => { currentSecondpath.value = `chat/${route.params.chatid}`; } - window.addEventListener('session-title-updated', handleSessionTitleUpdated); + window.addEventListener(SESSION_MUTATION_EVENT, handleSessionMutation); isLiteEdition.value = authStore.isLiteMode getSystemInfo().then(res => { @@ -1003,7 +984,7 @@ onMounted(async () => { }); onUnmounted(() => { - window.removeEventListener('session-title-updated', handleSessionTitleUpdated); + window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation); }); watch([() => route.name, () => route.params], (newvalue, oldvalue) => { diff --git a/frontend/src/components/sessionMutations.ts b/frontend/src/components/sessionMutations.ts new file mode 100644 index 00000000..cffa76e0 --- /dev/null +++ b/frontend/src/components/sessionMutations.ts @@ -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(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 { + 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 { + 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 { + ensureSuccess(await clearSessionMessages(sessionId)) + notifySessionMutation({ sessionId, messagesCleared: true }) +} + +export async function removeSession(sessionId: string): Promise { + ensureSuccess(await delSession(sessionId)) + notifySessionMutation({ sessionId, removed: true }) +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 106f7dc8..40fbb1a0 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -43,6 +43,37 @@ export default { noSessions: 'No conversations yet', 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: { stepOf: '{current} / {total}', skip: 'Skip', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 16d1d425..3e769042 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -43,6 +43,37 @@ export default { noSessions: "대화가 없습니다", 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: { stepOf: "{current} / {total}", skip: "건너뛰기", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index ae378ee1..17817599 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -43,6 +43,37 @@ export default { integrations: 'Публикация и интеграция', 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: { stepOf: '{current} / {total}', skip: 'Пропустить', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index b9f0b648..9cf7201c 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -43,6 +43,37 @@ export default { noSessions: "暂无对话", 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: { stepOf: "{current} / {total}", skip: "跳过引导", diff --git a/frontend/src/utils/sessionMarkdown.test.ts b/frontend/src/utils/sessionMarkdown.test.ts new file mode 100644 index 00000000..120b8a9a --- /dev/null +++ b/frontend/src/utils/sessionMarkdown.test.ts @@ -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 = { + '': [ + { 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. ', + 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, /