feat(sessions): 添加会话重命名功能和工具调用详情展示

- 实现了后端 API 接口 /api/sessions/:id/rename 用于重命名会话
- 添加了 Hermes CLI renameSession 方法来处理会话重命名逻辑
- 在前端添加了会话右键菜单,支持复制会话ID和重命名操作
- 新增重命名模态框组件供用户输入新标题
- 增强了消息项组件,支持展开查看工具调用的参数和结果详情
- 改进了工具消息的UI展示,包括运行状态指示器和错误标记
- 更新了会话列表显示源标识(如 Telegram、API 等)
- 优化了工具调用数据的映射逻辑,正确关联参数和执行结果
This commit is contained in:
cuiliang
2026-04-12 23:59:18 +08:00
parent 5887462f7d
commit 17a667c947
6 changed files with 349 additions and 26 deletions
+17
View File
@@ -32,3 +32,20 @@ sessionRoutes.delete('/api/sessions/:id', async (ctx) => {
}
ctx.body = { ok: true }
})
// Rename session
sessionRoutes.post('/api/sessions/:id/rename', async (ctx) => {
const { title } = ctx.request.body as { title?: string }
if (!title || typeof title !== 'string') {
ctx.status = 400
ctx.body = { error: 'title is required' }
return
}
const ok = await hermesCli.renameSession(ctx.params.id, title.trim())
if (!ok) {
ctx.status = 500
ctx.body = { error: 'Failed to rename session' }
return
}
ctx.body = { ok: true }
})
+15
View File
@@ -140,6 +140,21 @@ export async function deleteSession(id: string): Promise<boolean> {
}
}
/**
* Rename a session title via Hermes CLI
*/
export async function renameSession(id: string, title: string): Promise<boolean> {
try {
await execFileAsync('hermes', ['sessions', 'rename', id, title], {
timeout: 10000,
})
return true
} catch (err: any) {
console.error('[Hermes CLI] session rename failed:', err.message)
return false
}
}
export interface LogFileInfo {
name: string
size: string
+12
View File
@@ -59,3 +59,15 @@ export async function deleteSession(id: string): Promise<boolean> {
return false
}
}
export async function renameSession(id: string, title: string): Promise<boolean> {
try {
await request(`/api/sessions/${id}/rename`, {
method: 'POST',
body: JSON.stringify({ title }),
})
return true
} catch {
return false
}
}
+155 -12
View File
@@ -1,36 +1,70 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { NButton, NTooltip, NPopconfirm, useMessage } from 'naive-ui'
import MessageList from './MessageList.vue'
import ChatInput from './ChatInput.vue'
import { useChatStore } from '@/stores/chat'
import { renameSession } from '@/api/sessions'
import { useAppStore } from '@/stores/app'
import { useChatStore } from '@/stores/chat'
import { NButton, NDropdown, NInput, NModal, NPopconfirm, NTooltip, useMessage } from 'naive-ui'
import { computed, nextTick, ref } from 'vue'
import ChatInput from './ChatInput.vue'
import MessageList from './MessageList.vue'
const chatStore = useChatStore()
const appStore = useAppStore()
const message = useMessage()
const showSessions = ref(true)
const showRenameModal = ref(false)
const renameValue = ref('')
const renameSessionId = ref<string | null>(null)
const renameInputRef = ref<InstanceType<typeof NInput> | null>(null)
const sortedSessions = computed(() => {
return [...chatStore.sessions].sort((a, b) => b.createdAt - a.createdAt)
})
const activeSessionLabel = computed(() =>
chatStore.activeSession?.id || 'New Chat',
const activeSessionTitle = computed(() =>
chatStore.activeSession?.title || 'New Chat',
)
const activeSessionSource = computed(() =>
chatStore.activeSession?.source || '',
)
const sessionModelLabel = computed(() =>
chatStore.activeSession?.model || appStore.selectedModel || '',
)
const sourceLabel: Record<string, string> = {
telegram: 'Telegram',
api_server: 'API Server',
cli: 'CLI',
discord: 'Discord',
slack: 'Slack',
matrix: 'Matrix',
whatsapp: 'WhatsApp',
signal: 'Signal',
email: 'Email',
sms: 'SMS',
dingtalk: 'DingTalk',
feishu: 'Feishu',
wecom: 'WeCom',
weixin: 'WeChat',
bluebubbles: 'iMessage',
mattermost: 'Mattermost',
}
function getSourceLabel(source?: string): string {
if (!source) return ''
return sourceLabel[source] || source
}
function handleNewChat() {
chatStore.newChat()
}
function copySessionId() {
if (chatStore.activeSessionId) {
navigator.clipboard.writeText(chatStore.activeSessionId)
function copySessionId(id?: string) {
const sessionId = id || chatStore.activeSessionId
if (sessionId) {
navigator.clipboard.writeText(sessionId)
message.success('Copied')
}
}
@@ -47,6 +81,61 @@ function formatTime(ts: number) {
if (isToday) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
return d.toLocaleDateString([], { month: 'short', day: 'numeric' })
}
// Context menu
const contextMenuOptions = [
{ label: 'Rename', key: 'rename' },
{ label: 'Copy Session ID', key: 'copy-id' },
]
const contextSessionId = ref<string | null>(null)
function handleContextMenu(e: MouseEvent, sessionId: string) {
e.preventDefault()
contextSessionId.value = sessionId
showContextMenu.value = true
contextMenuX.value = e.clientX
contextMenuY.value = e.clientY
}
const showContextMenu = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
function handleContextMenuSelect(key: string) {
showContextMenu.value = false
if (!contextSessionId.value) return
if (key === 'copy-id') {
copySessionId(contextSessionId.value)
} else if (key === 'rename') {
const session = chatStore.sessions.find(s => s.id === contextSessionId.value)
renameSessionId.value = contextSessionId.value
renameValue.value = session?.title || ''
showRenameModal.value = true
nextTick(() => {
renameInputRef.value?.focus()
})
}
}
function handleClickOutside() {
showContextMenu.value = false
}
async function handleRenameConfirm() {
if (!renameSessionId.value || !renameValue.value.trim()) return
const ok = await renameSession(renameSessionId.value, renameValue.value.trim())
if (ok) {
const session = chatStore.sessions.find(s => s.id === renameSessionId.value)
if (session) session.title = renameValue.value.trim()
if (chatStore.activeSession?.id === renameSessionId.value) {
chatStore.activeSession.title = renameValue.value.trim()
}
message.success('Renamed')
} else {
message.error('Rename failed')
}
showRenameModal.value = false
}
</script>
<template>
@@ -70,11 +159,13 @@ function formatTime(ts: number) {
class="session-item"
:class="{ active: s.id === chatStore.activeSessionId }"
@click="chatStore.switchSession(s.id)"
@contextmenu="handleContextMenu($event, s.id)"
>
<div class="session-item-content">
<span class="session-item-title">{{ s.title }}</span>
<span class="session-item-meta">
<span v-if="s.model" class="session-item-model">{{ s.model }}</span>
<!-- <span v-if="s.source" class="session-item-source">{{ getSourceLabel(s.source) }}</span> -->
<span class="session-item-time">{{ formatTime(s.createdAt) }}</span>
</span>
</div>
@@ -93,6 +184,35 @@ function formatTime(ts: number) {
</div>
</aside>
<!-- Context Menu -->
<NDropdown
placement="bottom-start"
trigger="manual"
:x="contextMenuX"
:y="contextMenuY"
:options="contextMenuOptions"
:show="showContextMenu"
@select="handleContextMenuSelect"
@clickoutside="handleClickOutside"
/>
<!-- Rename Modal -->
<NModal
v-model:show="showRenameModal"
preset="dialog"
title="Rename Session"
positive-text="OK"
negative-text="Cancel"
@positive-click="handleRenameConfirm"
>
<NInput
ref="renameInputRef"
v-model:value="renameValue"
placeholder="Enter new title"
@keydown.enter="handleRenameConfirm"
/>
</NModal>
<!-- Chat Area -->
<div class="chat-main">
<header class="chat-header">
@@ -102,7 +222,8 @@ function formatTime(ts: number) {
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
</template>
</NButton>
<span class="header-session-title">{{ activeSessionLabel }}</span>
<span class="header-session-title">{{ activeSessionTitle }}</span>
<span v-if="activeSessionSource" class="source-badge">{{ getSourceLabel(activeSessionSource) }}</span>
</div>
<div class="header-center">
<span v-if="sessionModelLabel" class="model-badge">{{ sessionModelLabel }}</span>
@@ -110,7 +231,7 @@ function formatTime(ts: number) {
<div class="header-actions">
<NTooltip trigger="hover">
<template #trigger>
<NButton quaternary size="small" @click="copySessionId" circle>
<NButton quaternary size="small" @click="copySessionId()" circle>
<template #icon>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</template>
@@ -258,6 +379,17 @@ function formatTime(ts: number) {
white-space: nowrap;
}
.session-item-source {
font-size: 10px;
color: $text-muted;
background: rgba($text-muted, 0.1);
padding: 0 5px;
border-radius: 3px;
line-height: 16px;
flex-shrink: 0;
white-space: nowrap;
}
.session-item-delete {
flex-shrink: 0;
opacity: 0;
@@ -316,6 +448,17 @@ function formatTime(ts: number) {
text-overflow: ellipsis;
}
.source-badge {
font-size: 10px;
color: $text-muted;
background: rgba($text-muted, 0.12);
padding: 1px 7px;
border-radius: 8px;
flex-shrink: 0;
white-space: nowrap;
line-height: 16px;
}
.model-badge {
font-size: 11px;
color: $text-muted;
+125 -7
View File
@@ -1,11 +1,12 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { Message } from '@/stores/chat'
import MarkdownRenderer from './MarkdownRenderer.vue'
import type { Message } from '@/stores/chat';
import { computed, ref } from 'vue';
import MarkdownRenderer from './MarkdownRenderer.vue';
const props = defineProps<{ message: Message }>()
const isSystem = computed(() => props.message.role === 'system')
const toolExpanded = ref(false)
const timeStr = computed(() => {
const d = new Date(props.message.timestamp)
@@ -23,15 +24,54 @@ function formatSize(bytes: number): string {
}
const hasAttachments = computed(() => (props.message.attachments?.length ?? 0) > 0)
const hasToolDetails = computed(() => !!(props.message.toolArgs || props.message.toolResult))
const formattedToolArgs = computed(() => {
if (!props.message.toolArgs) return ''
try {
return JSON.stringify(JSON.parse(props.message.toolArgs), null, 2)
} catch {
return props.message.toolArgs
}
})
const formattedToolResult = computed(() => {
if (!props.message.toolResult) return ''
try {
const parsed = JSON.parse(props.message.toolResult)
const str = JSON.stringify(parsed, null, 2)
// Truncate very long output
if (str.length > 2000) return str.slice(0, 2000) + '\n... (truncated)'
return str
} catch {
const raw = props.message.toolResult
if (raw.length > 2000) return raw.slice(0, 2000) + '\n... (truncated)'
return raw
}
})
</script>
<template>
<div class="message" :class="[message.role]">
<template v-if="message.role === 'tool'">
<div class="tool-line">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="tool-icon"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>
<div class="tool-line" :class="{ expandable: hasToolDetails }" @click="hasToolDetails && (toolExpanded = !toolExpanded)">
<svg v-if="hasToolDetails" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="tool-chevron" :class="{ rotated: toolExpanded }"><polyline points="9 18 15 12 9 6"/></svg>
<svg v-else width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="tool-icon"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>
<span class="tool-name">{{ message.toolName }}</span>
<span v-if="message.toolPreview" class="tool-preview">{{ message.toolPreview }}</span>
<span v-if="message.toolPreview && !toolExpanded" class="tool-preview">{{ message.toolPreview }}</span>
<span v-if="message.toolStatus === 'running'" class="tool-spinner"></span>
<span v-if="message.toolStatus === 'error'" class="tool-error-badge">error</span>
</div>
<div v-if="toolExpanded && hasToolDetails" class="tool-details">
<div v-if="formattedToolArgs" class="tool-detail-section">
<div class="tool-detail-label">Arguments</div>
<pre class="tool-detail-code">{{ formattedToolArgs }}</pre>
</div>
<div v-if="formattedToolResult" class="tool-detail-section">
<div class="tool-detail-label">Result</div>
<pre class="tool-detail-code">{{ formattedToolResult }}</pre>
</div>
</div>
</template>
<template v-else>
@@ -214,10 +254,20 @@ const hasAttachments = computed(() => (props.message.attachments?.length ?? 0) >
gap: 6px;
font-size: 11px;
color: $text-muted;
padding: 0 4px;
padding: 2px 4px;
border-radius: $radius-sm;
&.expandable {
cursor: pointer;
&:hover {
background: rgba(0, 0, 0, 0.03);
}
}
.tool-name {
font-family: $font-code;
flex-shrink: 0;
}
.tool-preview {
@@ -228,6 +278,74 @@ const hasAttachments = computed(() => (props.message.attachments?.length ?? 0) >
}
}
.tool-chevron {
flex-shrink: 0;
transition: transform 0.15s ease;
&.rotated {
transform: rotate(90deg);
}
}
.tool-spinner {
width: 10px;
height: 10px;
border: 1.5px solid $text-muted;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.6s linear infinite;
flex-shrink: 0;
}
.tool-error-badge {
font-size: 9px;
color: $error;
background: rgba($error, 0.08);
padding: 0 4px;
border-radius: 3px;
line-height: 14px;
}
.tool-details {
margin-left: 16px;
margin-top: 2px;
border-left: 2px solid $border-light;
padding-left: 10px;
}
.tool-detail-section {
margin-bottom: 6px;
}
.tool-detail-label {
font-size: 10px;
font-weight: 600;
color: $text-muted;
text-transform: uppercase;
letter-spacing: 0.3px;
margin-bottom: 2px;
}
.tool-detail-code {
font-family: $font-code;
font-size: 11px;
line-height: 1.5;
color: $text-secondary;
background: $code-bg;
border-radius: $radius-sm;
padding: 6px 8px;
margin: 0;
overflow-x: auto;
max-height: 300px;
overflow-y: auto;
white-space: pre-wrap;
word-break: break-all;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.streaming-cursor {
display: inline-block;
width: 2px;
+25 -7
View File
@@ -1,7 +1,7 @@
import { startRun, streamRunEvents, type ChatMessage, type RunEvent } from '@/api/chat'
import { deleteSession as deleteSessionApi, fetchSession, fetchSessions, type HermesMessage, type SessionSummary } from '@/api/sessions'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { startRun, streamRunEvents, type ChatMessage, type RunEvent } from '@/api/chat'
import { fetchSessions, fetchSession, deleteSession as deleteSessionApi, type SessionSummary, type HermesMessage } from '@/api/sessions'
import { useAppStore } from './app'
export interface Attachment {
@@ -20,6 +20,8 @@ export interface Message {
timestamp: number
toolName?: string
toolPreview?: string
toolArgs?: string
toolResult?: string
toolStatus?: 'running' | 'done' | 'error'
isStreaming?: boolean
attachments?: Attachment[]
@@ -28,6 +30,7 @@ export interface Message {
export interface Session {
id: string
title: string
source?: string
messages: Message[]
createdAt: number
updatedAt: number
@@ -53,13 +56,15 @@ async function uploadFiles(attachments: Attachment[]): Promise<{ name: string; p
}
function mapHermesMessages(msgs: HermesMessage[]): Message[] {
// Build a lookup of tool_call_id -> tool name from assistant messages with tool_calls
// Build lookups from assistant messages with tool_calls
const toolNameMap = new Map<string, string>()
const toolArgsMap = new Map<string, string>()
for (const msg of msgs) {
if (msg.role === 'assistant' && msg.tool_calls) {
for (const tc of msg.tool_calls) {
if (tc.function?.name && tc.id) {
toolNameMap.set(tc.id, tc.function.name)
if (tc.id) {
if (tc.function?.name) toolNameMap.set(tc.id, tc.function.name)
if (tc.function?.arguments) toolArgsMap.set(tc.id, tc.function.arguments)
}
}
}
@@ -77,6 +82,7 @@ function mapHermesMessages(msgs: HermesMessage[]): Message[] {
content: '',
timestamp: Math.round(msg.timestamp * 1000),
toolName: tc.function?.name || 'Tool',
toolArgs: tc.function?.arguments || undefined,
toolStatus: 'done',
})
}
@@ -85,7 +91,9 @@ function mapHermesMessages(msgs: HermesMessage[]): Message[] {
// Tool result messages
if (msg.role === 'tool') {
const toolName = msg.tool_name || toolNameMap.get(msg.tool_call_id || '') || 'Tool'
const tcId = msg.tool_call_id || ''
const toolName = msg.tool_name || toolNameMap.get(tcId) || 'Tool'
const toolArgs = toolArgsMap.get(tcId) || undefined
// Extract a short preview from the content
let preview = ''
if (msg.content) {
@@ -96,13 +104,22 @@ function mapHermesMessages(msgs: HermesMessage[]): Message[] {
preview = msg.content.slice(0, 80)
}
}
// Find and remove the matching placeholder from tool_calls above
const placeholderIdx = result.findIndex(
m => m.role === 'tool' && m.toolName === toolName && !m.toolResult && m.id.includes('_' + tcId)
)
if (placeholderIdx !== -1) {
result.splice(placeholderIdx, 1)
}
result.push({
id: String(msg.id),
role: 'tool',
content: '',
timestamp: Math.round(msg.timestamp * 1000),
toolName,
toolArgs,
toolPreview: preview.slice(0, 100) || undefined,
toolResult: msg.content || undefined,
toolStatus: 'done',
})
continue
@@ -123,6 +140,7 @@ function mapHermesSession(s: SessionSummary): Session {
return {
id: s.id,
title: s.title || 'New Chat',
source: s.source || undefined,
messages: [],
createdAt: Math.round(s.started_at * 1000),
updatedAt: Math.round((s.ended_at || s.started_at) * 1000),
@@ -146,7 +164,7 @@ export const useChatStore = defineStore('chat', () => {
async function loadSessions() {
isLoadingSessions.value = true
try {
const list = await fetchSessions('api_server')
const list = await fetchSessions()
sessions.value = list.map(mapHermesSession)
// Backfill titles from first user message for sessions with null title
const nullTitleSessions = sessions.value.filter(s => s.title === 'New Chat')