feat: group chat session lifecycle, typing recovery, mention highlighting (#186)
* feat: restore group chat system with Socket.IO and SQLite persistence - GroupChatServer: Socket.IO server with room management, message history, typing indicators - SQLite storage for rooms, messages, and agent configuration - AgentClients: manages AI agent connections via socket.io-client, forwards @mentions to Hermes gateway - REST API: room CRUD, agent management, invite codes - Agent auto-restoration on server restart - Tests for all REST endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: add context-engine design document for group chat compression Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: handle special-character session search * fix: keep unicode dotted session search on quoted FTS path * feat: add context engine and group chat frontend UI - Context engine: three-zone compression (head/tail/summary) with LLM summarization, incremental updates, TTL cache, and graceful degradation - Frontend: group chat page with Socket.IO client, room sidebar, message list, agent/member display, create/join-by-code modals - Integration: wire context engine into agent-clients before /v1/runs - Refactor ChatStorage to use global DB (getDb/ensureTable) with gc_ prefix - Add i18n keys for group chat to all 8 locales - Add sidebar nav entry and router for group chat page Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: remove leftover main branch code from merge conflict resolution The `isNumericQuery`, `hasUnsafeChars`, and `runLikeContentSearch` functions no longer exist — they were replaced by HEAD's `shouldUseLiteralContentSearch` and `runLiteralContentSearch`. This dead code block caused a TypeScript compile error after the merge. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: install missing socket.io dep and type ack params Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: enable WebSocket proxy and fix socket.io transport for group chat - Add ws: true to Vite proxy config so WebSocket upgrade requests are forwarded to the backend - Allow both polling and websocket transports on server and client (polling as fallback when WebSocket upgrade fails through proxy) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: separate socket.io path from REST routes for group chat socket.io was mounted at /api/hermes/group-chat which intercepted all REST requests to /api/hermes/group-chat/rooms etc, returning "Transport unknown". Changed socket.io path to /api/hermes/group-chat/ws to avoid conflicts. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: improve group chat UI, agent management, and socket.io reliability - Redesign GroupChatPanel with Naive UI, stacked agent avatars, and popover management - Match GroupChatInput style with single chat input, add IME composition handling - Add agent add/remove per room with profile selection and duplicate prevention - Use @multiavatar for SVG avatar generation with caching - Decouple joinRoom from socket.io, use REST API for data loading - Switch socket.io to default path with /group-chat namespace to avoid proxy conflicts - Restore agent connections after server is listening - Add getRoomDetail REST endpoint and duplicate agent prevention (409) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: server-side @mention routing with context compression status and queue - Move @mention detection from agent socket listeners to server-side processMentions() - Add per-room processing lock to block mention dispatch during compression - Queue mentions during processing, drain only the latest when ready - Emit context_status events (compressing/replying/ready) to room via Socket.IO - Frontend displays compression status indicator above input - Token-based compression trigger (100k threshold) with CJK-aware estimation - Fix compressor type errors (countTokens parameter type) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: improve group chat profile handling and session sync Refine group chat room/session behavior with per-room compression controls, sidebar updates, and better stale session cleanup so multi-profile group chat state stays consistent. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: group chat improvements — session lifecycle, typing recovery, mention highlighting - Fix cross-profile session deletion with deferred delete queue - Move saveSessionProfile to after gateway response confirmation - Replace all console.log with logger in group-chat modules - Add server-side typing/context_status state tracking for room rejoin - Fix @ mention popup position to follow cursor - Add @ mention highlighting (blue) in chat message content - Fix mention regex to match all occurrences after HTML tags - Enable esbuild minify and treeShaking - Move @multiavatar/multiavatar to devDependencies - Add i18n keys for group chat features - Update tests for new functionality Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: bump version to 0.4.5 and move @multiavatar to devDependencies Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Zhicheng Han <zhicheng.han@mathematik.uni-goettingen.de>
This commit is contained in:
+7
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hermes-web-ui",
|
||||
"version": "0.4.4",
|
||||
"version": "0.4.5",
|
||||
"description": "Self-hosted AI chat dashboard for Hermes Agent — multi-model (Claude, GPT, Gemini, DeepSeek) web UI with Telegram, Discord, Slack, WhatsApp integration",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -61,13 +61,18 @@
|
||||
"dist/"
|
||||
],
|
||||
"dependencies": {
|
||||
"node-pty": "^1.1.0"
|
||||
"eventsource": "^4.1.0",
|
||||
"node-pty": "^1.1.0",
|
||||
"socket.io": "^4.8.3",
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@multiavatar/multiavatar": "^1.0.7",
|
||||
"@koa/bodyparser": "^5.0.0",
|
||||
"@koa/cors": "^5.0.0",
|
||||
"@koa/router": "^15.4.0",
|
||||
"@pinia/testing": "^1.0.3",
|
||||
"@types/eventsource": "^1.1.15",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/koa": "^2.15.0",
|
||||
"@types/koa__cors": "^5.0.0",
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { io } from 'socket.io-client'
|
||||
import { request, getApiKey } from '../client'
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────
|
||||
|
||||
export interface RoomInfo {
|
||||
id: string
|
||||
name: string
|
||||
inviteCode: string | null
|
||||
triggerTokens?: number
|
||||
maxHistoryTokens?: number
|
||||
tailMessageCount?: number
|
||||
totalTokens?: number
|
||||
}
|
||||
|
||||
export interface RoomAgent {
|
||||
id: string
|
||||
roomId: string
|
||||
agentId: string
|
||||
profile: string
|
||||
name: string
|
||||
description: string
|
||||
invited: number
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string
|
||||
roomId: string
|
||||
senderId: string
|
||||
senderName: string
|
||||
content: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface MemberInfo {
|
||||
id: string
|
||||
userId: string
|
||||
name: string
|
||||
description: string
|
||||
joinedAt: number
|
||||
}
|
||||
|
||||
export interface JoinResult {
|
||||
roomId: string
|
||||
roomName: string
|
||||
members: MemberInfo[]
|
||||
messages: ChatMessage[]
|
||||
rooms: string[]
|
||||
}
|
||||
|
||||
// ─── Socket.IO Client ──────────────────────────────────────
|
||||
|
||||
let socket: ReturnType<typeof io> | null = null
|
||||
|
||||
export function connectGroupChat(opts?: { userId?: string; userName?: string; description?: string }): ReturnType<typeof io> {
|
||||
if (socket?.connected) return socket
|
||||
|
||||
const token = getApiKey()
|
||||
const userId = opts?.userId || localStorage.getItem('gc_user_id') || generateUUID()
|
||||
localStorage.setItem('gc_user_id', userId)
|
||||
|
||||
socket = io('/group-chat', {
|
||||
auth: {
|
||||
token: token || undefined,
|
||||
userId,
|
||||
name: opts?.userName || localStorage.getItem('gc_user_name') || undefined,
|
||||
description: opts?.description || localStorage.getItem('gc_user_description') || undefined,
|
||||
},
|
||||
transports: ['websocket'],
|
||||
reconnection: true,
|
||||
reconnectionAttempts: Infinity,
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 30000,
|
||||
})
|
||||
|
||||
return socket
|
||||
}
|
||||
|
||||
export function getStoredUserId(): string {
|
||||
let id = localStorage.getItem('gc_user_id')
|
||||
if (!id) {
|
||||
id = generateUUID()
|
||||
localStorage.setItem('gc_user_id', id)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
export function getStoredUserName(): string | null {
|
||||
return localStorage.getItem('gc_user_name')
|
||||
}
|
||||
|
||||
function generateUUID(): string {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||||
const r = Math.random() * 16 | 0
|
||||
const v = c === 'x' ? r : (r & 0x3 | 0x8)
|
||||
return v.toString(16)
|
||||
})
|
||||
}
|
||||
|
||||
export function getSocket(): ReturnType<typeof io> | null {
|
||||
return socket?.connected ? socket : null
|
||||
}
|
||||
|
||||
export function disconnectGroupChat(): void {
|
||||
if (socket) {
|
||||
socket.disconnect()
|
||||
socket = null
|
||||
}
|
||||
}
|
||||
|
||||
// ─── REST API ───────────────────────────────────────────────
|
||||
|
||||
export async function createRoom(data: {
|
||||
name: string
|
||||
inviteCode: string
|
||||
agents?: { profile: string; name?: string; description?: string; invited?: boolean }[]
|
||||
compression?: { triggerTokens?: number; maxHistoryTokens?: number; tailMessageCount?: number }
|
||||
}): Promise<{ room: RoomInfo; agents: RoomAgent[] }> {
|
||||
return request('/api/hermes/group-chat/rooms', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listRooms(): Promise<{ rooms: RoomInfo[] }> {
|
||||
return request('/api/hermes/group-chat/rooms')
|
||||
}
|
||||
|
||||
export async function getRoomDetail(roomId: string): Promise<{ room: RoomInfo; messages: ChatMessage[]; agents: RoomAgent[]; members: MemberInfo[] }> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}`)
|
||||
}
|
||||
|
||||
export async function joinRoomByCode(code: string): Promise<{ room: RoomInfo }> {
|
||||
return request(`/api/hermes/group-chat/rooms/join/${code}`)
|
||||
}
|
||||
|
||||
export async function updateInviteCode(roomId: string, inviteCode: string): Promise<void> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}/invite-code`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ inviteCode }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function addAgent(roomId: string, data: {
|
||||
profile: string
|
||||
name?: string
|
||||
description?: string
|
||||
invited?: boolean
|
||||
}): Promise<{ agent: RoomAgent }> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}/agents`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export async function listAgents(roomId: string): Promise<{ agents: RoomAgent[] }> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}/agents`)
|
||||
}
|
||||
|
||||
export async function removeAgent(roomId: string, agentId: string): Promise<void> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}/agents/${agentId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteRoom(roomId: string): Promise<void> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateRoomConfig(roomId: string, config: { triggerTokens?: number; maxHistoryTokens?: number; tailMessageCount?: number }): Promise<{ room: RoomInfo }> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}/config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config),
|
||||
})
|
||||
}
|
||||
|
||||
export async function forceCompress(roomId: string): Promise<{ success: boolean; summary: string }> {
|
||||
return request(`/api/hermes/group-chat/rooms/${roomId}/compress`, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,7 +6,13 @@ import MarkdownIt from 'markdown-it'
|
||||
import { handleCodeBlockCopyClick, renderHighlightedCodeBlock } from './highlight'
|
||||
import { downloadFile } from '@/api/hermes/download'
|
||||
|
||||
const props = defineProps<{ content: string }>()
|
||||
const props = withDefaults(defineProps<{
|
||||
content: string
|
||||
mentionNames?: string[]
|
||||
}>(), {
|
||||
mentionNames: () => [],
|
||||
})
|
||||
|
||||
const { t } = useI18n()
|
||||
const message = useMessage()
|
||||
|
||||
@@ -19,7 +25,15 @@ const md: MarkdownIt = new MarkdownIt({
|
||||
},
|
||||
})
|
||||
|
||||
const renderedHtml = computed(() => md.render(props.content))
|
||||
const renderedHtml = computed(() => {
|
||||
let html = md.render(props.content)
|
||||
if (props.mentionNames && props.mentionNames.length > 0) {
|
||||
const escaped = props.mentionNames.map(n => n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
||||
const re = new RegExp(`(?<=[\\s>]|^)@(${escaped.join('|')})(?=\\s|$)`, 'gi')
|
||||
html = html.replace(re, '<span class="mention-highlight">@$1</span>')
|
||||
}
|
||||
return html
|
||||
})
|
||||
|
||||
function handleMarkdownClick(event: MouseEvent): void {
|
||||
void handleCodeBlockCopyClick(event)
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, nextTick } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { NInput, NButton, NSpace, NInputNumber, NCollapse, NCollapseItem } from 'naive-ui'
|
||||
|
||||
type InputLikeInstance = {
|
||||
focus: () => void
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const emit = defineEmits<{
|
||||
submit: [name: string, inviteCode: string, userName: string, description: string, compression: { triggerTokens: number; maxHistoryTokens: number; tailMessageCount: number }]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const roomName = ref('')
|
||||
const inviteCode = ref('')
|
||||
const userName = ref('')
|
||||
const description = ref('')
|
||||
const roomInput = ref<InputLikeInstance | null>(null)
|
||||
|
||||
const compression = ref({
|
||||
triggerTokens: 100000,
|
||||
maxHistoryTokens: 32000,
|
||||
tailMessageCount: 20,
|
||||
})
|
||||
|
||||
function generateCode(): string {
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
|
||||
let code = ''
|
||||
for (let i = 0; i < 6; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)]
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
function handleCreate() {
|
||||
const name = roomName.value.trim()
|
||||
const code = inviteCode.value.trim() || generateCode()
|
||||
const user = userName.value.trim()
|
||||
if (!name || !user) return
|
||||
emit('submit', name, code, user, description.value.trim(), { ...compression.value })
|
||||
}
|
||||
|
||||
function focusRoomInput() {
|
||||
nextTick(() => roomInput.value?.focus())
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="create-form">
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.yourName') }}</label>
|
||||
<NInput
|
||||
v-model:value="userName"
|
||||
:placeholder="t('groupChat.yourNamePlaceholder')"
|
||||
@keyup.enter="focusRoomInput"
|
||||
/>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.yourDescription') }}</label>
|
||||
<NInput
|
||||
v-model:value="description"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
:placeholder="t('groupChat.yourDescriptionPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.roomName') }}</label>
|
||||
<NInput
|
||||
ref="roomInput"
|
||||
v-model:value="roomName"
|
||||
:placeholder="t('groupChat.roomNamePlaceholder')"
|
||||
@keyup.enter="handleCreate"
|
||||
/>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.inviteCode') }}</label>
|
||||
<div class="code-row">
|
||||
<NInput
|
||||
v-model:value="inviteCode"
|
||||
:placeholder="t('groupChat.autoGenerate')"
|
||||
/>
|
||||
<NButton size="small" @click="inviteCode = generateCode()">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10" /><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
|
||||
</svg>
|
||||
</NButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NCollapse class="compression-collapse">
|
||||
<NCollapseItem :title="t('groupChat.compressionSettings')" name="compression">
|
||||
<div class="compression-fields">
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.triggerTokens') }}</label>
|
||||
<NInputNumber v-model:value="compression.triggerTokens" :min="1000" :step="1000" style="width: 100%" />
|
||||
<p class="form-hint">{{ t('groupChat.triggerTokensDesc') }}</p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.maxHistoryTokens') }}</label>
|
||||
<NInputNumber v-model:value="compression.maxHistoryTokens" :min="1000" :step="1000" style="width: 100%" />
|
||||
<p class="form-hint">{{ t('groupChat.maxHistoryTokensDesc') }}</p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.tailMessageCount') }}</label>
|
||||
<NInputNumber v-model:value="compression.tailMessageCount" :min="1" :step="5" style="width: 100%" />
|
||||
<p class="form-hint">{{ t('groupChat.tailMessageCountDesc') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</NCollapseItem>
|
||||
</NCollapse>
|
||||
|
||||
<div class="modal-actions">
|
||||
<NSpace justify="end">
|
||||
<NButton @click="emit('cancel')">{{ t('common.cancel') }}</NButton>
|
||||
<NButton type="primary" :disabled="!roomName.trim() || !userName.trim()" @click="handleCreate">{{ t('common.create') }}</NButton>
|
||||
</NSpace>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@use "@/styles/variables" as *;
|
||||
|
||||
.create-form {
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.form-label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: $text-secondary;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.form-hint {
|
||||
font-size: 11px;
|
||||
color: $text-muted;
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
|
||||
.code-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.compression-collapse {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.compression-fields {
|
||||
padding-top: 8px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,321 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, nextTick } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { NButton, NDropdown } from 'naive-ui'
|
||||
import { useGroupChatStore } from '@/stores/hermes/group-chat'
|
||||
import type { DropdownOption } from 'naive-ui'
|
||||
|
||||
const { t } = useI18n()
|
||||
const emit = defineEmits<{ send: [content: string] }>()
|
||||
const store = useGroupChatStore()
|
||||
|
||||
const inputText = ref('')
|
||||
const textareaRef = ref<HTMLTextAreaElement>()
|
||||
const isComposing = ref(false)
|
||||
|
||||
// ─── Mention State ───────────────────────────────────────
|
||||
|
||||
const mentionActive = ref(false)
|
||||
const mentionQuery = ref('')
|
||||
const mentionStartIndex = ref(-1)
|
||||
const dropdownX = ref(0)
|
||||
const dropdownY = ref(0)
|
||||
const activeIndex = ref(0)
|
||||
|
||||
const filteredAgents = computed(() => {
|
||||
const query = mentionQuery.value.toLowerCase()
|
||||
return store.agents.filter(a => a.name.toLowerCase().includes(query))
|
||||
})
|
||||
|
||||
const dropdownOptions = computed<DropdownOption[]>(() => {
|
||||
return filteredAgents.value.map((a, i) => ({
|
||||
label: `${a.name} (${a.profile})`,
|
||||
key: a.name,
|
||||
index: i,
|
||||
}))
|
||||
})
|
||||
|
||||
const canSend = computed(() => !!inputText.value.trim())
|
||||
|
||||
// ─── Mention Logic ───────────────────────────────────────
|
||||
|
||||
function updateMentionState() {
|
||||
const el = textareaRef.value
|
||||
if (!el) { mentionActive.value = false; return }
|
||||
|
||||
const text = inputText.value
|
||||
const cursorPos = el.selectionStart
|
||||
|
||||
// Find the last @ before the cursor
|
||||
let atPos = -1
|
||||
for (let i = cursorPos - 1; i >= 0; i--) {
|
||||
if (text[i] === '@') { atPos = i; break }
|
||||
if (text[i] === ' ' || text[i] === '\n') break
|
||||
}
|
||||
|
||||
if (atPos === -1) {
|
||||
mentionActive.value = false
|
||||
return
|
||||
}
|
||||
|
||||
// Make sure the @ is not part of a word (preceded by space or start of line)
|
||||
if (atPos > 0 && text[atPos - 1] !== ' ' && text[atPos - 1] !== '\n') {
|
||||
mentionActive.value = false
|
||||
return
|
||||
}
|
||||
|
||||
const query = text.slice(atPos + 1, cursorPos)
|
||||
if (query.includes(' ')) {
|
||||
mentionActive.value = false
|
||||
return
|
||||
}
|
||||
|
||||
mentionQuery.value = query
|
||||
mentionStartIndex.value = atPos
|
||||
activeIndex.value = 0
|
||||
|
||||
// Calculate dropdown position using mirror span
|
||||
const mirror = document.createElement('span')
|
||||
const style = getComputedStyle(el)
|
||||
const props = ['fontFamily', 'fontSize', 'fontWeight', 'letterSpacing', 'textTransform', 'wordSpacing', 'textIndent', 'border', 'padding', 'boxSizing', 'lineHeight']
|
||||
props.forEach(p => { (mirror.style as any)[p] = style[p as any] })
|
||||
mirror.style.position = 'absolute'
|
||||
mirror.style.visibility = 'hidden'
|
||||
mirror.style.whiteSpace = 'nowrap'
|
||||
mirror.textContent = text.slice(0, atPos + 1)
|
||||
|
||||
const rect = el.getBoundingClientRect()
|
||||
document.body.appendChild(mirror)
|
||||
const mirrorRect = mirror.getBoundingClientRect()
|
||||
document.body.removeChild(mirror)
|
||||
|
||||
dropdownX.value = rect.left + mirrorRect.width - el.scrollLeft
|
||||
// Estimate Y based on newlines before @ and line height
|
||||
const linesBeforeAt = text.slice(0, atPos + 1).split('\n').length - 1
|
||||
const lineHeight = parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2
|
||||
dropdownY.value = rect.top + linesBeforeAt * lineHeight - el.scrollTop + lineHeight + 4
|
||||
|
||||
mentionActive.value = filteredAgents.value.length > 0
|
||||
}
|
||||
|
||||
function selectMention(name: string) {
|
||||
const el = textareaRef.value
|
||||
if (!el || mentionStartIndex.value === -1) return
|
||||
|
||||
const before = inputText.value.slice(0, mentionStartIndex.value)
|
||||
const after = inputText.value.slice(el.selectionStart)
|
||||
inputText.value = `${before}@${name} ${after}`
|
||||
mentionActive.value = false
|
||||
|
||||
nextTick(() => {
|
||||
if (el) {
|
||||
const newPos = before.length + name.length + 2
|
||||
el.setSelectionRange(newPos, newPos)
|
||||
el.focus()
|
||||
el.style.height = 'auto'
|
||||
el.style.height = Math.min(el.scrollHeight, 100) + 'px'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Event Handlers ──────────────────────────────────────
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
// Mention navigation
|
||||
if (mentionActive.value && filteredAgents.value.length > 0) {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
activeIndex.value = (activeIndex.value + 1) % filteredAgents.value.length
|
||||
return
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
activeIndex.value = (activeIndex.value - 1 + filteredAgents.value.length) % filteredAgents.value.length
|
||||
return
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
selectMention(filteredAgents.value[activeIndex.value].name)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
mentionActive.value = false
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key !== 'Enter' || e.shiftKey) return
|
||||
if (isComposing.value || e.isComposing || e.keyCode === 229) return
|
||||
e.preventDefault()
|
||||
handleSend()
|
||||
}
|
||||
|
||||
function handleSend() {
|
||||
const content = inputText.value.trim()
|
||||
if (!content) return
|
||||
|
||||
emit('send', content)
|
||||
inputText.value = ''
|
||||
mentionActive.value = false
|
||||
|
||||
nextTick(() => {
|
||||
if (textareaRef.value) {
|
||||
textareaRef.value.style.height = 'auto'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function handleInput(e: Event) {
|
||||
store.emitTyping()
|
||||
const el = e.target as HTMLTextAreaElement
|
||||
el.style.height = 'auto'
|
||||
el.style.height = Math.min(el.scrollHeight, 100) + 'px'
|
||||
|
||||
if (!isComposing.value) {
|
||||
updateMentionState()
|
||||
}
|
||||
}
|
||||
|
||||
function handleDropdownSelect(key: string) {
|
||||
selectMention(key)
|
||||
}
|
||||
|
||||
function handleDropdownClickOutside() {
|
||||
mentionActive.value = false
|
||||
}
|
||||
|
||||
function handleCompositionStart() {
|
||||
isComposing.value = true
|
||||
}
|
||||
|
||||
function handleCompositionEnd() {
|
||||
requestAnimationFrame(() => {
|
||||
isComposing.value = false
|
||||
updateMentionState()
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="chat-input-area">
|
||||
<div class="input-wrapper">
|
||||
<textarea
|
||||
ref="textareaRef"
|
||||
v-model="inputText"
|
||||
class="input-textarea"
|
||||
:placeholder="t('groupChat.inputPlaceholder')"
|
||||
rows="1"
|
||||
@keydown="handleKeydown"
|
||||
@compositionstart="handleCompositionStart"
|
||||
@compositionend="handleCompositionEnd"
|
||||
@input="handleInput"
|
||||
/>
|
||||
<div class="input-actions">
|
||||
<NButton
|
||||
size="small"
|
||||
type="primary"
|
||||
:disabled="!canSend"
|
||||
@click="handleSend"
|
||||
>
|
||||
<template #icon>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
|
||||
</template>
|
||||
{{ t('chat.send') }}
|
||||
</NButton>
|
||||
</div>
|
||||
</div>
|
||||
<NDropdown
|
||||
placement="top-start"
|
||||
trigger="manual"
|
||||
:x="dropdownX"
|
||||
:y="dropdownY"
|
||||
:options="dropdownOptions"
|
||||
:show="mentionActive"
|
||||
:render-icon="() => null"
|
||||
@select="handleDropdownSelect"
|
||||
@clickoutside="handleDropdownClickOutside"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@use "@/styles/variables" as *;
|
||||
|
||||
.chat-input-area {
|
||||
padding: 20px 20px 16px;
|
||||
border-top: 1px solid $border-color;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.typing-dots {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
|
||||
span {
|
||||
display: block;
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 50%;
|
||||
background-color: $text-muted;
|
||||
animation: typing-bounce 1.2s infinite;
|
||||
|
||||
&:nth-child(2) { animation-delay: 0.2s; }
|
||||
&:nth-child(3) { animation-delay: 0.4s; }
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes typing-bounce {
|
||||
0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
|
||||
30% { transform: translateY(-3px); opacity: 1; }
|
||||
}
|
||||
|
||||
.input-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background-color: $bg-input;
|
||||
border: 1px solid $border-color;
|
||||
border-radius: $radius-md;
|
||||
padding: 10px 12px;
|
||||
transition: border-color $transition-fast, background-color $transition-fast;
|
||||
|
||||
&:focus-within {
|
||||
border-color: $accent-primary;
|
||||
}
|
||||
|
||||
.dark & {
|
||||
background-color: #333333;
|
||||
}
|
||||
}
|
||||
|
||||
.input-textarea {
|
||||
flex: 1;
|
||||
background: none;
|
||||
border: none;
|
||||
outline: none;
|
||||
color: $text-primary;
|
||||
font-family: $font-ui;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
resize: none;
|
||||
max-height: 100px;
|
||||
min-height: 20px;
|
||||
overflow-y: auto;
|
||||
|
||||
&::placeholder {
|
||||
color: $text-muted;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
.input-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,896 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, nextTick, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useMessage, NInput, NButton, NSpace, NSelect, NPopover, NPopconfirm, NInputNumber } from 'naive-ui'
|
||||
import multiavatar from '@multiavatar/multiavatar'
|
||||
import { useGroupChatStore } from '@/stores/hermes/group-chat'
|
||||
import { useProfilesStore } from '@/stores/hermes/profiles'
|
||||
import { updateRoomConfig, forceCompress } from '@/api/hermes/group-chat'
|
||||
import GroupMessageList from './GroupMessageList.vue'
|
||||
import GroupChatInput from './GroupChatInput.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const message = useMessage()
|
||||
const store = useGroupChatStore()
|
||||
const profilesStore = useProfilesStore()
|
||||
|
||||
const showSidebar = ref(true)
|
||||
const showCreateModal = ref(false)
|
||||
const showAddAgentModal = ref(false)
|
||||
const showCompressionModal = ref(false)
|
||||
const compressionConfig = ref({ triggerTokens: 100000, maxHistoryTokens: 32000, tailMessageCount: 20 })
|
||||
const isCompressing = ref(false)
|
||||
const selectedProfile = ref<string | null>(null)
|
||||
const agentName = ref('')
|
||||
const agentDescription = ref('')
|
||||
|
||||
const profileOptions = computed(() =>
|
||||
profilesStore.profiles.map(p => ({ label: p.name, value: p.name }))
|
||||
)
|
||||
|
||||
const avatarCache = new Map<string, string>()
|
||||
|
||||
function agentAvatarUrl(name: string): string {
|
||||
if (avatarCache.has(name)) return avatarCache.get(name)!
|
||||
const uri = multiavatar(name)
|
||||
avatarCache.set(name, uri)
|
||||
return uri
|
||||
}
|
||||
|
||||
const hasRoom = computed(() => !!store.currentRoomId)
|
||||
|
||||
function formatTokens(tokens: number): string {
|
||||
if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}k tokens`
|
||||
return `${tokens} tokens`
|
||||
}
|
||||
|
||||
function toggleSidebar() {
|
||||
showSidebar.value = !showSidebar.value
|
||||
}
|
||||
|
||||
async function handleCreateRoom(name: string, inviteCode: string, userName: string, description: string, compression: { triggerTokens: number; maxHistoryTokens: number; tailMessageCount: number }) {
|
||||
try {
|
||||
store.setUserInfo(userName, description)
|
||||
const res = await store.createNewRoom(name, inviteCode, undefined, compression)
|
||||
showCreateModal.value = false
|
||||
message.success(t('groupChat.roomCreated'))
|
||||
await store.joinRoom(res.room.id)
|
||||
} catch {
|
||||
message.error(t('common.saveFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteRoom(roomId: string) {
|
||||
try {
|
||||
await store.deleteRoom(roomId)
|
||||
message.success(t('groupChat.roomDeleted'))
|
||||
} catch {
|
||||
message.error(t('common.saveFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSelectRoom(roomId: string) {
|
||||
try {
|
||||
await store.joinRoom(roomId)
|
||||
} catch {
|
||||
message.error(t('groupChat.joinFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendMessage(content: string) {
|
||||
try {
|
||||
await store.sendMessage(content)
|
||||
} catch (err: any) {
|
||||
message.error(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAddAgent() {
|
||||
await profilesStore.fetchProfiles()
|
||||
showAddAgentModal.value = true
|
||||
}
|
||||
|
||||
async function confirmAddAgent() {
|
||||
if (!selectedProfile.value || !store.currentRoomId) return
|
||||
try {
|
||||
await store.addAgentToRoom(store.currentRoomId, {
|
||||
profile: selectedProfile.value,
|
||||
name: agentName.value.trim() || undefined,
|
||||
description: agentDescription.value.trim() || undefined,
|
||||
})
|
||||
showAddAgentModal.value = false
|
||||
selectedProfile.value = null
|
||||
agentName.value = ''
|
||||
agentDescription.value = ''
|
||||
message.success(t('groupChat.agentAdded'))
|
||||
} catch (err: any) {
|
||||
if (err.message?.includes('already')) {
|
||||
message.warning(t('groupChat.agentAlreadyInRoom'))
|
||||
} else {
|
||||
message.error(t('common.saveFailed'))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleOpenCompressionConfig() {
|
||||
const room = store.rooms.find(r => r.id === store.currentRoomId)
|
||||
if (room) {
|
||||
compressionConfig.value = {
|
||||
triggerTokens: room.triggerTokens ?? 100000,
|
||||
maxHistoryTokens: room.maxHistoryTokens ?? 32000,
|
||||
tailMessageCount: room.tailMessageCount ?? 20,
|
||||
}
|
||||
}
|
||||
showCompressionModal.value = true
|
||||
}
|
||||
|
||||
async function handleSaveCompressionConfig() {
|
||||
if (!store.currentRoomId) return
|
||||
try {
|
||||
const res = await updateRoomConfig(store.currentRoomId, { ...compressionConfig.value })
|
||||
const idx = store.rooms.findIndex(r => r.id === store.currentRoomId)
|
||||
if (idx >= 0 && res.room) store.rooms[idx] = res.room
|
||||
showCompressionModal.value = false
|
||||
message.success(t('groupChat.compressionSaved'))
|
||||
} catch {
|
||||
message.error(t('common.saveFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function handleForceCompress() {
|
||||
if (!store.currentRoomId || isCompressing.value) return
|
||||
if (store.contextStatuses.size > 0) {
|
||||
message.warning(t('groupChat.compressingInProgress'))
|
||||
return
|
||||
}
|
||||
isCompressing.value = true
|
||||
try {
|
||||
await forceCompress(store.currentRoomId)
|
||||
message.success(t('groupChat.compressionSaved'))
|
||||
} catch {
|
||||
message.error(t('common.saveFailed'))
|
||||
} finally {
|
||||
isCompressing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveAgent(agentId: string) {
|
||||
if (!store.currentRoomId) return
|
||||
try {
|
||||
await store.removeAgentFromRoom(store.currentRoomId, agentId)
|
||||
} catch {
|
||||
message.error(t('common.deleteFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-scroll on new messages
|
||||
const messageListRef = ref()
|
||||
watch(() => store.sortedMessages.length, async () => {
|
||||
await nextTick()
|
||||
messageListRef.value?.scrollToBottom()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="group-chat-panel">
|
||||
<!-- Room sidebar -->
|
||||
<div v-if="showSidebar" class="room-sidebar">
|
||||
<div class="sidebar-header">
|
||||
<span class="sidebar-title">{{ t('groupChat.title') }}</span>
|
||||
<div class="sidebar-actions">
|
||||
<button class="icon-btn" :title="t('groupChat.createRoom')" @click="showCreateModal = true">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="room-list">
|
||||
<div
|
||||
v-for="room in store.rooms"
|
||||
:key="room.id"
|
||||
class="room-item"
|
||||
:class="{ active: store.currentRoomId === room.id }"
|
||||
@click="handleSelectRoom(room.id)"
|
||||
>
|
||||
<svg class="room-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
<div class="room-info">
|
||||
<span class="room-name">{{ room.name || room.id }}</span>
|
||||
<span v-if="room.inviteCode" class="room-code">{{ room.inviteCode }}</span>
|
||||
<span class="room-tokens">{{ formatTokens(room.totalTokens || 0) }}</span>
|
||||
</div>
|
||||
<NPopconfirm @positive-click="handleDeleteRoom(room.id)">
|
||||
<template #trigger>
|
||||
<button class="room-delete-btn" @click.stop>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</template>
|
||||
{{ t('groupChat.deleteRoomConfirm') }}
|
||||
</NPopconfirm>
|
||||
</div>
|
||||
<div v-if="store.rooms.length === 0" class="empty-rooms">
|
||||
{{ t('groupChat.noRooms') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main chat area -->
|
||||
<div class="chat-main">
|
||||
<div class="chat-header">
|
||||
<button class="icon-btn" @click="toggleSidebar">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" /><line x1="9" y1="3" x2="9" y2="21" />
|
||||
</svg>
|
||||
</button>
|
||||
<span class="room-title-text">{{ store.roomName || (store.currentRoomId || t('groupChat.title')) }}</span>
|
||||
<div class="header-info">
|
||||
<!-- Stacked avatars (user + agents) -->
|
||||
<NPopover v-if="store.agents.length" trigger="click" placement="bottom-end" :width="220">
|
||||
<template #trigger>
|
||||
<div class="avatar-stack-inner">
|
||||
<!-- User avatar first -->
|
||||
<span class="avatar-stack-item" :style="{ zIndex: store.agents.length + 1 }">
|
||||
<span class="agent-avatar" v-html="agentAvatarUrl(store.userName || store.userId)" />
|
||||
</span>
|
||||
<span
|
||||
v-for="(agent, index) in store.agents.slice(-4)"
|
||||
:key="agent.id"
|
||||
class="avatar-stack-item"
|
||||
:style="{ zIndex: store.agents.length - index }"
|
||||
>
|
||||
<span class="agent-avatar" v-html="agentAvatarUrl(agent.name)" />
|
||||
</span>
|
||||
<span v-if="store.agents.length > 4" class="avatar-stack-more">+{{ store.agents.length - 4 }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<div class="agent-popover">
|
||||
<div class="agent-popover-item" style="margin-bottom: 8px; padding-bottom: 8px; border-bottom: 1px solid var(--n-border-color, #efeff5);">
|
||||
<span class="agent-avatar" v-html="agentAvatarUrl(store.userName || store.userId)" />
|
||||
<div class="agent-popover-info">
|
||||
<span class="agent-popover-name">{{ store.userName || 'You' }}</span>
|
||||
<span class="agent-popover-profile">{{ t('groupChat.you') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="agent-popover-title">{{ t('groupChat.agents') }} ({{ store.agents.length }})</div>
|
||||
<div v-for="agent in store.agents" :key="agent.id" class="agent-popover-item">
|
||||
<span class="agent-avatar" v-html="agentAvatarUrl(agent.name)" />
|
||||
<div class="agent-popover-info">
|
||||
<span class="agent-popover-name">{{ agent.name }}</span>
|
||||
<span class="agent-popover-profile">{{ agent.profile }}</span>
|
||||
</div>
|
||||
<button class="agent-popover-remove" @click="handleRemoveAgent(agent.id)">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</NPopover>
|
||||
<!-- Only user avatar, no agents -->
|
||||
<div v-else-if="store.userName" class="avatar-stack-inner">
|
||||
<span class="avatar-stack-item">
|
||||
<span class="agent-avatar" v-html="agentAvatarUrl(store.userName || store.userId)" />
|
||||
</span>
|
||||
</div>
|
||||
<button class="icon-btn" :title="t('groupChat.addAgent')" @click="handleAddAgent">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||
</button>
|
||||
<button class="icon-btn" :title="t('groupChat.compressionConfig')" @click="handleOpenCompressionConfig">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 4.6a1.65 1.65 0 0 0 1.51 1V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1.51 1z"/></svg>
|
||||
</button>
|
||||
<span v-if="store.members.length" class="member-count">
|
||||
{{ store.members.length }} {{ t('groupChat.members') }}
|
||||
</span>
|
||||
<span class="connection-dot" :class="{ connected: store.connected, disconnected: !store.connected }"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="hasRoom">
|
||||
<GroupMessageList ref="messageListRef" />
|
||||
<div v-if="store.contextStatuses.size > 0 || (store.typingText && store.contextStatuses.size === 0)" class="status-bar">
|
||||
<div v-if="store.contextStatuses.size > 0" class="context-status-list">
|
||||
<div v-for="[name, status] in store.contextStatuses" :key="name" class="context-status">
|
||||
<span class="typing-dots">
|
||||
<span /><span /><span />
|
||||
</span>
|
||||
<span v-if="status.status === 'compressing'">
|
||||
@{{ status.agentName }} {{ t('groupChat.agentCompressing') }}
|
||||
</span>
|
||||
<span v-else>
|
||||
@{{ status.agentName }} {{ t('groupChat.agentReplying') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="store.typingText" class="typing-indicator">
|
||||
<span class="typing-dots">
|
||||
<span /><span /><span />
|
||||
</span>
|
||||
{{ store.typingText }}
|
||||
</div>
|
||||
</div>
|
||||
<GroupChatInput @send="handleSendMessage" />
|
||||
</template>
|
||||
|
||||
<div v-else class="no-room">
|
||||
<div class="no-room-icon">
|
||||
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p>{{ t('groupChat.selectOrCreate') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Create room modal -->
|
||||
<Teleport to="body">
|
||||
<div v-if="showCreateModal" class="modal-backdrop" @click.self="showCreateModal = false">
|
||||
<div class="modal">
|
||||
<h3>{{ t('groupChat.createRoom') }}</h3>
|
||||
<CreateRoomForm @submit="handleCreateRoom" @cancel="showCreateModal = false" />
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="showAddAgentModal" class="modal-backdrop" @click.self="showAddAgentModal = false">
|
||||
<div class="modal">
|
||||
<h3>{{ t('groupChat.addAgent') }}</h3>
|
||||
<div class="form-group">
|
||||
<NSelect
|
||||
v-model:value="selectedProfile"
|
||||
:options="profileOptions"
|
||||
:placeholder="t('groupChat.selectProfile')"
|
||||
filterable
|
||||
/>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.agentName') }}</label>
|
||||
<NInput
|
||||
v-model:value="agentName"
|
||||
:placeholder="t('groupChat.agentNamePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.agentDesc') }}</label>
|
||||
<NInput
|
||||
v-model:value="agentDescription"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
:placeholder="t('groupChat.agentDescPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<NSpace justify="end">
|
||||
<NButton @click="showAddAgentModal = false">{{ t('common.cancel') }}</NButton>
|
||||
<NButton type="primary" :disabled="!selectedProfile" @click="confirmAddAgent">{{ t('common.add') }}</NButton>
|
||||
</NSpace>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="showCompressionModal" class="modal-backdrop" @click.self="showCompressionModal = false">
|
||||
<div class="modal">
|
||||
<h3>{{ t('groupChat.compressionConfig') }}</h3>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.triggerTokens') }}</label>
|
||||
<NInputNumber v-model:value="compressionConfig.triggerTokens" :min="1000" :step="10000" style="width: 100%" />
|
||||
<p class="form-hint">{{ t('groupChat.triggerTokensDesc') }}</p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.maxHistoryTokens') }}</label>
|
||||
<NInputNumber v-model:value="compressionConfig.maxHistoryTokens" :min="1000" :step="1000" style="width: 100%" />
|
||||
<p class="form-hint">{{ t('groupChat.maxHistoryTokensDesc') }}</p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">{{ t('groupChat.tailMessageCount') }}</label>
|
||||
<NInputNumber v-model:value="compressionConfig.tailMessageCount" :min="1" :step="5" style="width: 100%" />
|
||||
<p class="form-hint">{{ t('groupChat.tailMessageCountDesc') }}</p>
|
||||
</div>
|
||||
<div style="margin-top: 8px">
|
||||
<NButton
|
||||
block
|
||||
:disabled="isCompressing || store.contextStatuses.size > 0"
|
||||
:loading="isCompressing"
|
||||
@click="handleForceCompress"
|
||||
>
|
||||
{{ isCompressing ? t('groupChat.compressingInProgress') : t('groupChat.compressNow') }}
|
||||
</NButton>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<NSpace justify="end">
|
||||
<NButton @click="showCompressionModal = false">{{ t('common.cancel') }}</NButton>
|
||||
<NButton type="primary" @click="handleSaveCompressionConfig">{{ t('common.save') }}</NButton>
|
||||
</NSpace>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
import CreateRoomForm from './CreateRoomForm.vue'
|
||||
|
||||
export default defineComponent({ components: { CreateRoomForm } })
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@use "@/styles/variables" as *;
|
||||
|
||||
.group-chat-panel {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
// ─── Status Bar ──────────────────────────────────────────
|
||||
|
||||
.status-bar {
|
||||
flex-shrink: 0;
|
||||
padding: 6px 20px;
|
||||
background: #ffffff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.context-status-list {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
overflow-x: auto;
|
||||
flex-wrap: nowrap;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.context-status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
color: $text-secondary;
|
||||
background-color: $bg-card-hover;
|
||||
border-radius: $radius-sm;
|
||||
|
||||
.dark & {
|
||||
background-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
}
|
||||
|
||||
.typing-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
.typing-dots {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
|
||||
span {
|
||||
display: block;
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 50%;
|
||||
background-color: $text-muted;
|
||||
animation: typing-bounce 1.2s infinite;
|
||||
|
||||
&:nth-child(2) { animation-delay: 0.2s; }
|
||||
&:nth-child(3) { animation-delay: 0.4s; }
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes typing-bounce {
|
||||
0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
|
||||
30% { transform: translateY(-3px); opacity: 1; }
|
||||
}
|
||||
|
||||
// ─── Room Sidebar ────────────────────────────────────────
|
||||
|
||||
.room-sidebar {
|
||||
width: 220px;
|
||||
flex-shrink: 0;
|
||||
background-color: $bg-sidebar;
|
||||
border-right: 1px solid $border-color;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.sidebar-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: $text-primary;
|
||||
}
|
||||
|
||||
.sidebar-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.room-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.room-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
border-radius: $radius-sm;
|
||||
cursor: pointer;
|
||||
transition: background-color $transition-fast;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(var(--accent-primary-rgb), 0.06);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background-color: rgba(var(--accent-primary-rgb), 0.12);
|
||||
}
|
||||
|
||||
.room-icon {
|
||||
color: $text-muted;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.room-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.room-name {
|
||||
font-size: 13px;
|
||||
color: $text-primary;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.room-code {
|
||||
font-size: 11px;
|
||||
color: $text-muted;
|
||||
font-family: $font-code;
|
||||
}
|
||||
|
||||
.room-tokens {
|
||||
font-size: 11px;
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
.room-delete-btn {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: $text-muted;
|
||||
cursor: pointer;
|
||||
border-radius: $radius-sm;
|
||||
opacity: 0;
|
||||
transition: opacity $transition-fast, color $transition-fast, background-color $transition-fast;
|
||||
|
||||
&:hover {
|
||||
color: $error;
|
||||
background-color: rgba(var(--error-rgb), 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .room-delete-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-rooms {
|
||||
padding: 20px 12px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
// ─── Chat Main ──────────────────────────────────────────
|
||||
|
||||
.chat-main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.chat-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 21px 20px;
|
||||
border-bottom: 1px solid $border-color;
|
||||
|
||||
.room-title-text {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: $text-primary;
|
||||
flex: 1;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.header-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.member-count {
|
||||
font-size: 12px;
|
||||
color: $text-muted;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Header Avatar Stack ──────────────────────────────
|
||||
|
||||
.avatar-stack {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.avatar-stack-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.avatar-stack-item {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid $bg-card;
|
||||
margin-left: -12px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: $bg-secondary;
|
||||
transition: transform $transition-fast;
|
||||
|
||||
&:first-child {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
z-index: 100 !important;
|
||||
}
|
||||
}
|
||||
|
||||
.avatar-stack-more {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid $bg-card;
|
||||
margin-left: -12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: $bg-secondary;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: $text-secondary;
|
||||
}
|
||||
|
||||
.agent-avatar {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
:deep(svg) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Agent Popover ─────────────────────────────────────
|
||||
|
||||
.agent-popover {
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.agent-popover-title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: $text-muted;
|
||||
padding: 0 0 8px;
|
||||
border-bottom: 1px solid $border-color;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.agent-popover-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 4px;
|
||||
border-radius: $radius-sm;
|
||||
transition: background-color $transition-fast;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(var(--accent-primary-rgb), 0.06);
|
||||
}
|
||||
|
||||
.agent-popover-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.agent-popover-name {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: $text-primary;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.agent-popover-profile {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: $text-muted;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.agent-popover-remove {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: none;
|
||||
background: none;
|
||||
border-radius: $radius-sm;
|
||||
color: $text-muted;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition: all $transition-fast;
|
||||
|
||||
&:hover {
|
||||
color: $error;
|
||||
background-color: rgba(200, 50, 50, 0.08);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── No Room State ────────────────────────────────────────
|
||||
|
||||
.no-room {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 16px;
|
||||
color: $text-muted;
|
||||
|
||||
.no-room-icon {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Shared ──────────────────────────────────────────────
|
||||
|
||||
.icon-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: none;
|
||||
background: none;
|
||||
border-radius: $radius-sm;
|
||||
color: $text-secondary;
|
||||
cursor: pointer;
|
||||
transition: all $transition-fast;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(var(--accent-primary-rgb), 0.08);
|
||||
color: $text-primary;
|
||||
}
|
||||
}
|
||||
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: $bg-card;
|
||||
border-radius: $radius-lg;
|
||||
padding: 24px;
|
||||
width: 400px;
|
||||
max-width: 90vw;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
|
||||
|
||||
h3 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: $text-primary;
|
||||
margin: 0 0 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
margin-top: 12px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.form-hint {
|
||||
font-size: 11px;
|
||||
color: $text-muted;
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
|
||||
// ─── Connection Dot ──────────────────────────────────────
|
||||
|
||||
.connection-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
|
||||
&.connected {
|
||||
background-color: $success;
|
||||
box-shadow: 0 0 6px rgba(var(--success-rgb), 0.5);
|
||||
}
|
||||
|
||||
&.disconnected {
|
||||
background-color: $error;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Mobile ──────────────────────────────────────────────
|
||||
|
||||
@media (max-width: $breakpoint-mobile) {
|
||||
.room-sidebar {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
z-index: 100;
|
||||
box-shadow: 4px 0 16px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,149 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import multiavatar from '@multiavatar/multiavatar'
|
||||
import MarkdownRenderer from '../chat/MarkdownRenderer.vue'
|
||||
import type { ChatMessage, RoomAgent } from '@/api/hermes/group-chat'
|
||||
|
||||
const props = defineProps<{
|
||||
message: ChatMessage
|
||||
agents: RoomAgent[]
|
||||
currentUserId?: string
|
||||
}>()
|
||||
|
||||
const isAgent = computed(() => {
|
||||
return props.agents.some(a => a.agentId === props.message.senderId)
|
||||
})
|
||||
|
||||
const isSelf = computed(() => {
|
||||
return !!props.currentUserId && props.message.senderId === props.currentUserId
|
||||
})
|
||||
|
||||
const agentInfo = computed(() => {
|
||||
return props.agents.find(a => a.agentId === props.message.senderId)
|
||||
})
|
||||
|
||||
const timeStr = computed(() => {
|
||||
const d = new Date(props.message.timestamp)
|
||||
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
})
|
||||
|
||||
const avatarSvg = computed(() => {
|
||||
return multiavatar(props.message.senderName || props.message.senderId)
|
||||
})
|
||||
|
||||
const mentionNames = computed(() => props.agents.map(a => a.name).filter(Boolean))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="group-message" :class="{ agent: isAgent, self: isSelf }">
|
||||
<!-- Avatar -->
|
||||
<div class="avatar">
|
||||
<span v-html="avatarSvg" />
|
||||
</div>
|
||||
|
||||
<div class="msg-body">
|
||||
<div class="msg-header">
|
||||
<span class="sender-name">{{ message.senderName }}</span>
|
||||
<span v-if="isAgent && agentInfo?.description" class="agent-desc">{{ agentInfo.description }}</span>
|
||||
<span class="msg-time">{{ timeStr }}</span>
|
||||
</div>
|
||||
<div class="msg-content" :class="{ 'agent-content': isAgent }">
|
||||
<MarkdownRenderer :content="message.content" :mention-names="mentionNames" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@use "@/styles/variables" as *;
|
||||
|
||||
.group-message {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 2px 0;
|
||||
|
||||
&.agent,
|
||||
&.self {
|
||||
flex-direction: row-reverse;
|
||||
|
||||
.msg-body {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.msg-header {
|
||||
flex-direction: row-reverse;
|
||||
}
|
||||
}
|
||||
|
||||
&.agent .msg-content.agent-content {
|
||||
background-color: rgba(var(--accent-primary-rgb), 0.06);
|
||||
}
|
||||
|
||||
&.self .msg-content {
|
||||
background-color: rgba(var(--accent-primary-rgb), 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
|
||||
:deep(svg) {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
}
|
||||
|
||||
.msg-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
max-width: 70%;
|
||||
}
|
||||
|
||||
.msg-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-bottom: 2px;
|
||||
|
||||
.sender-name {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: $text-primary;
|
||||
}
|
||||
|
||||
.agent-desc {
|
||||
font-size: 11px;
|
||||
color: $text-muted;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.msg-time {
|
||||
font-size: 11px;
|
||||
color: $text-muted;
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.msg-content {
|
||||
padding: 10px 14px;
|
||||
font-size: 14px;
|
||||
line-height: 1.65;
|
||||
color: $text-primary;
|
||||
border-radius: 10px;
|
||||
background-color: $msg-user-bg;
|
||||
word-break: break-word;
|
||||
overflow-wrap: break-word;
|
||||
|
||||
:deep(.mention-highlight) {
|
||||
color: #409eff;
|
||||
font-weight: 600;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,79 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, nextTick } from 'vue'
|
||||
import { useGroupChatStore } from '@/stores/hermes/group-chat'
|
||||
import GroupMessageItem from './GroupMessageItem.vue'
|
||||
|
||||
const store = useGroupChatStore()
|
||||
const listRef = ref<HTMLDivElement>()
|
||||
const isNearBottom = ref(true)
|
||||
|
||||
function checkNearBottom(): void {
|
||||
if (!listRef.value) return
|
||||
const { scrollTop, scrollHeight, clientHeight } = listRef.value
|
||||
isNearBottom.value = scrollHeight - scrollTop - clientHeight < 200
|
||||
}
|
||||
|
||||
function scrollToBottom(): void {
|
||||
if (!listRef.value) return
|
||||
listRef.value.scrollTop = listRef.value.scrollHeight
|
||||
}
|
||||
|
||||
function handleScroll(): void {
|
||||
checkNearBottom()
|
||||
}
|
||||
|
||||
watch(() => store.messages.length, async () => {
|
||||
await nextTick()
|
||||
if (isNearBottom.value) {
|
||||
scrollToBottom()
|
||||
}
|
||||
})
|
||||
|
||||
defineExpose({ scrollToBottom })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="listRef" class="message-list" @scroll="handleScroll">
|
||||
<div v-if="store.sortedMessages.length === 0" class="empty-state">
|
||||
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
<p>No messages yet</p>
|
||||
</div>
|
||||
<GroupMessageItem
|
||||
v-for="msg in store.sortedMessages"
|
||||
:key="msg.id"
|
||||
:message="msg"
|
||||
:agents="store.agents"
|
||||
:current-user-id="store.userId"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@use "@/styles/variables" as *;
|
||||
|
||||
.message-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
color: $text-muted;
|
||||
opacity: 0.4;
|
||||
|
||||
p {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -65,14 +65,30 @@ function openChangelog() {
|
||||
</div>
|
||||
|
||||
<nav class="sidebar-nav">
|
||||
<!-- Chat (standalone) -->
|
||||
<!-- Conversation -->
|
||||
<div class="nav-group">
|
||||
<div class="nav-group-label" @click="toggleGroup('conversation')">
|
||||
<span>{{ t("sidebar.groupConversation") }}</span>
|
||||
<svg class="nav-group-arrow" :class="{ collapsed: isGroupCollapsed('conversation') }" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="6 9 12 15 18 9" />
|
||||
</svg>
|
||||
</div>
|
||||
<div v-show="!isGroupCollapsed('conversation')">
|
||||
<button class="nav-item" :class="{ active: selectedKey === 'hermes.chat' }" @click="handleNav('hermes.chat')">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
|
||||
</svg>
|
||||
<span>{{ t("sidebar.chat") }}</span>
|
||||
</button>
|
||||
|
||||
<button class="nav-item" :class="{ active: selectedKey === 'hermes.groupChat' }" @click="handleNav('hermes.groupChat')">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
|
||||
</svg>
|
||||
<span>{{ t("sidebar.groupChat") }}<span class="beta-tag">(beta)</span></span>
|
||||
</button>
|
||||
<button class="nav-item" @click="openSessionSearch">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="11" cy="11" r="7" />
|
||||
@@ -80,6 +96,8 @@ function openChangelog() {
|
||||
</svg>
|
||||
<span>{{ t("sidebar.search") }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Agent -->
|
||||
<div class="nav-group">
|
||||
@@ -430,6 +448,12 @@ function openChangelog() {
|
||||
background-color: rgba(var(--accent-primary-rgb), 0.12);
|
||||
color: $accent-primary;
|
||||
}
|
||||
|
||||
.beta-tag {
|
||||
font-size: 10px;
|
||||
color: $text-muted;
|
||||
margin-left: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
|
||||
@@ -17,7 +17,7 @@ export const changelog: ChangelogEntry[] = [
|
||||
},
|
||||
{
|
||||
version: '0.4.2',
|
||||
date: '2026-03-20',
|
||||
date: '2026-04-22',
|
||||
changes: ['changelog.new_0_4_2_1', 'changelog.new_0_4_2_2', 'changelog.new_0_4_2_3', 'changelog.new_0_4_2_4', 'changelog.new_0_4_2_5'],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -48,6 +48,7 @@ export default {
|
||||
update: 'Aktualisieren',
|
||||
create: 'Erstellen',
|
||||
saveFailed: 'Speichern fehlgeschlagen',
|
||||
deleteFailed: 'Loschen fehlgeschlagen',
|
||||
ok: 'OK',
|
||||
copied: 'Kopiert',
|
||||
copy: 'Kopieren',
|
||||
@@ -76,6 +77,8 @@ export default {
|
||||
channels: 'Kanale',
|
||||
terminal: 'Terminal',
|
||||
files: 'Dateien',
|
||||
groupChat: 'Gruppenchat',
|
||||
groupConversation: 'Konversation',
|
||||
settings: 'Einstellungen',
|
||||
connected: 'Verbunden',
|
||||
disconnected: 'Getrennt',
|
||||
@@ -579,6 +582,55 @@ export default {
|
||||
saveFile: 'Speichern',
|
||||
},
|
||||
|
||||
// Gruppenchat
|
||||
groupChat: {
|
||||
title: 'Gruppenchat',
|
||||
createRoom: 'Raum erstellen',
|
||||
joinByCode: 'Mit Code beitreten',
|
||||
roomName: 'Raumname',
|
||||
roomNamePlaceholder: 'Raumnamen eingeben',
|
||||
inviteCode: 'Einladungscode',
|
||||
autoGenerate: 'Automatisch generieren',
|
||||
noRooms: 'Noch keine Raume',
|
||||
selectOrCreate: 'Wahlen oder erstellen Sie einen Raum, um zu chatten',
|
||||
agents: 'Agenten',
|
||||
addAgent: 'Agent hinzufugen',
|
||||
selectProfile: 'Wahlen Sie ein Profil',
|
||||
agentAdded: 'Agent hinzugefugt',
|
||||
agentAlreadyInRoom: 'Agent ist bereits in diesem Raum',
|
||||
noAgents: 'Keine Agenten in diesem Raum',
|
||||
members: 'Mitglieder',
|
||||
roomCreated: 'Raum erstellt',
|
||||
roomDeleted: 'Raum gelöscht',
|
||||
deleteRoomConfirm: 'Diesen Raum löschen?',
|
||||
you: 'Du',
|
||||
joined: 'Raum beigetreten',
|
||||
joinFailed: 'Beitreten fehlgeschlagen',
|
||||
inputPlaceholder: 'Nachricht eingeben... (Enter zum Senden)',
|
||||
enterCode: 'Einladungscode eingeben',
|
||||
yourName: 'Dein Name',
|
||||
yourNamePlaceholder: 'Gib deinen Anzeigenamen ein',
|
||||
yourDescription: 'Beschreibung (optional)',
|
||||
yourDescriptionPlaceholder: 'Erzahl anderen wer du bist...',
|
||||
agentName: 'Agent-Name',
|
||||
agentNamePlaceholder: 'Benutzerdefinierter Name (leer = Profilname)',
|
||||
agentDesc: 'Agent-Beschreibung',
|
||||
agentDescPlaceholder: 'Beschreiben Sie, was dieser Agent tut...',
|
||||
agentReplying: 'antwortet...',
|
||||
agentCompressing: 'komprimiert Kontext...',
|
||||
compressionSettings: 'Komprimierungseinstellungen',
|
||||
triggerTokens: 'Trigger-Token',
|
||||
triggerTokensDesc: 'Token-Schwelle für Kontextkomprimierung',
|
||||
maxHistoryTokens: 'Max. Verlaufs-Token',
|
||||
maxHistoryTokensDesc: 'Maximale Token für komprimierten Kontext',
|
||||
tailMessageCount: 'Nachrichten am Ende',
|
||||
tailMessageCountDesc: 'Anzahl der letzten Nachrichten, die unverändert bleiben',
|
||||
compressionConfig: 'Komprimierungskonfig',
|
||||
compressNow: 'Jetzt komprimieren',
|
||||
compressingInProgress: 'Komprimierung läuft, bitte warten',
|
||||
compressionSaved: 'Konfiguration gespeichert',
|
||||
},
|
||||
|
||||
// Download
|
||||
download: {
|
||||
downloading: 'Wird heruntergeladen...',
|
||||
|
||||
@@ -48,6 +48,7 @@ export default {
|
||||
update: 'Update',
|
||||
create: 'Create',
|
||||
saveFailed: 'Save failed',
|
||||
deleteFailed: 'Delete failed',
|
||||
ok: 'OK',
|
||||
copied: 'Copied',
|
||||
copy: 'Copy',
|
||||
@@ -79,6 +80,7 @@ export default {
|
||||
channels: 'Channels',
|
||||
gateways: 'Gateways',
|
||||
terminal: 'Terminal',
|
||||
groupChat: 'Group Chat',
|
||||
files: 'Files',
|
||||
groupConversation: 'Conversation',
|
||||
groupPlatform: 'Platform',
|
||||
@@ -535,6 +537,55 @@ export default {
|
||||
processExited: 'Process exited with code {code}',
|
||||
},
|
||||
|
||||
// Group Chat
|
||||
groupChat: {
|
||||
title: 'Group Chat',
|
||||
createRoom: 'Create Room',
|
||||
joinByCode: 'Join by Code',
|
||||
roomName: 'Room Name',
|
||||
roomNamePlaceholder: 'Enter room name',
|
||||
inviteCode: 'Invite Code',
|
||||
autoGenerate: 'Auto-generate',
|
||||
noRooms: 'No rooms yet',
|
||||
selectOrCreate: 'Select or create a room to start chatting',
|
||||
agents: 'Agents',
|
||||
addAgent: 'Add Agent',
|
||||
selectProfile: 'Select a profile',
|
||||
agentAdded: 'Agent added',
|
||||
agentAlreadyInRoom: 'Agent already in this room',
|
||||
noAgents: 'No agents in this room',
|
||||
members: 'members',
|
||||
roomCreated: 'Room created',
|
||||
roomDeleted: 'Room deleted',
|
||||
deleteRoomConfirm: 'Delete this room?',
|
||||
you: 'You',
|
||||
joined: 'Joined room',
|
||||
joinFailed: 'Failed to join room',
|
||||
inputPlaceholder: 'Type a message... (Enter to send)',
|
||||
enterCode: 'Enter invite code',
|
||||
yourName: 'Your Name',
|
||||
yourNamePlaceholder: 'Enter your display name',
|
||||
yourDescription: 'Description (optional)',
|
||||
yourDescriptionPlaceholder: 'Tell others who you are...',
|
||||
agentName: 'Agent Name',
|
||||
agentNamePlaceholder: 'Custom name (leave empty to use profile name)',
|
||||
agentDesc: 'Agent Description',
|
||||
agentDescPlaceholder: 'Describe what this agent does...',
|
||||
agentReplying: 'is replying...',
|
||||
agentCompressing: 'is compressing context...',
|
||||
compressionSettings: 'Compression Settings',
|
||||
triggerTokens: 'Trigger Tokens',
|
||||
triggerTokensDesc: 'Token threshold to trigger context compression',
|
||||
maxHistoryTokens: 'Max History Tokens',
|
||||
maxHistoryTokensDesc: 'Maximum tokens for compressed context sent to LLM',
|
||||
tailMessageCount: 'Tail Message Count',
|
||||
tailMessageCountDesc: 'Number of recent messages to keep verbatim after compression',
|
||||
compressionConfig: 'Compression Config',
|
||||
compressionSaved: 'Compression config saved',
|
||||
compressNow: 'Compress Now',
|
||||
compressingInProgress: 'Compression in progress, please wait',
|
||||
},
|
||||
|
||||
// Usage
|
||||
usage: {
|
||||
title: 'Usage Statistics',
|
||||
|
||||
@@ -48,6 +48,7 @@ export default {
|
||||
update: 'Actualizar',
|
||||
create: 'Crear',
|
||||
saveFailed: 'Error al guardar',
|
||||
deleteFailed: 'Error al eliminar',
|
||||
ok: 'OK',
|
||||
copied: 'Copiado',
|
||||
copy: 'Copiar',
|
||||
@@ -76,6 +77,8 @@ export default {
|
||||
channels: 'Canales',
|
||||
terminal: 'Terminal',
|
||||
files: 'Archivos',
|
||||
groupChat: 'Chat grupal',
|
||||
groupConversation: 'Conversación',
|
||||
settings: 'Configuracion',
|
||||
connected: 'Conectado',
|
||||
disconnected: 'Desconectado',
|
||||
@@ -579,6 +582,55 @@ export default {
|
||||
saveFile: 'Guardar',
|
||||
},
|
||||
|
||||
// Chat grupal
|
||||
groupChat: {
|
||||
title: 'Chat grupal',
|
||||
createRoom: 'Crear sala',
|
||||
joinByCode: 'Unirse con codigo',
|
||||
roomName: 'Nombre de la sala',
|
||||
roomNamePlaceholder: 'Ingrese el nombre de la sala',
|
||||
inviteCode: 'Codigo de invitacion',
|
||||
autoGenerate: 'Generar automaticamente',
|
||||
noRooms: 'Aun no hay salas',
|
||||
selectOrCreate: 'Seleccione o cree una sala para comenzar a chatear',
|
||||
agents: 'Agentes',
|
||||
addAgent: 'Agregar agente',
|
||||
selectProfile: 'Seleccione un perfil',
|
||||
agentAdded: 'Agente agregado',
|
||||
agentAlreadyInRoom: 'El agente ya esta en esta sala',
|
||||
noAgents: 'No hay agentes en esta sala',
|
||||
members: 'Miembros',
|
||||
roomCreated: 'Sala creada',
|
||||
roomDeleted: 'Sala eliminada',
|
||||
deleteRoomConfirm: '¿Eliminar esta sala?',
|
||||
you: 'Tú',
|
||||
joined: 'Se unio a la sala',
|
||||
joinFailed: 'Error al unirse a la sala',
|
||||
inputPlaceholder: 'Escriba un mensaje... (Enter para enviar)',
|
||||
enterCode: 'Ingrese el codigo de invitacion',
|
||||
yourName: 'Tu nombre',
|
||||
yourNamePlaceholder: 'Ingresa tu nombre para mostrar',
|
||||
yourDescription: 'Descripcion (opcional)',
|
||||
yourDescriptionPlaceholder: 'Cuentales a los demas quien eres...',
|
||||
agentName: 'Nombre del agente',
|
||||
agentNamePlaceholder: 'Nombre personalizado (vacío = nombre del perfil)',
|
||||
agentDesc: 'Descripción del agente',
|
||||
agentDescPlaceholder: 'Describe lo que hace este agente...',
|
||||
agentReplying: 'está respondiendo...',
|
||||
agentCompressing: 'está comprimiendo contexto...',
|
||||
compressionSettings: 'Configuración de compresión',
|
||||
triggerTokens: 'Tokens de activación',
|
||||
triggerTokensDesc: 'Umbral de tokens para activar la compresión',
|
||||
maxHistoryTokens: 'Tokens máximos de historial',
|
||||
maxHistoryTokensDesc: 'Máximo de tokens para el contexto comprimido',
|
||||
tailMessageCount: 'Mensajes recientes',
|
||||
tailMessageCountDesc: 'Número de mensajes recientes a conservar sin comprimir',
|
||||
compressionConfig: 'Config. de compresión',
|
||||
compressNow: 'Comprimir ahora',
|
||||
compressingInProgress: 'Compresión en progreso',
|
||||
compressionSaved: 'Configuración guardada',
|
||||
},
|
||||
|
||||
// Descarga
|
||||
download: {
|
||||
downloading: 'Descargando...',
|
||||
|
||||
@@ -48,6 +48,7 @@ export default {
|
||||
update: 'Mettre a jour',
|
||||
create: 'Creer',
|
||||
saveFailed: 'Echec de l\'enregistrement',
|
||||
deleteFailed: 'Echec de la suppression',
|
||||
ok: 'OK',
|
||||
copied: 'Copie',
|
||||
copy: 'Copier',
|
||||
@@ -76,6 +77,8 @@ export default {
|
||||
channels: 'Canaux',
|
||||
terminal: 'Terminal',
|
||||
files: 'Fichiers',
|
||||
groupChat: 'Chat de groupe',
|
||||
groupConversation: 'Conversation',
|
||||
settings: 'Parametres',
|
||||
connected: 'Connecte',
|
||||
disconnected: 'Deconnecte',
|
||||
@@ -579,6 +582,55 @@ export default {
|
||||
saveFile: 'Enregistrer',
|
||||
},
|
||||
|
||||
// Chat de groupe
|
||||
groupChat: {
|
||||
title: 'Chat de groupe',
|
||||
createRoom: 'Creer un salon',
|
||||
joinByCode: 'Rejoindre avec un code',
|
||||
roomName: 'Nom du salon',
|
||||
roomNamePlaceholder: 'Entrez le nom du salon',
|
||||
inviteCode: "Code d'invitation",
|
||||
autoGenerate: 'Generer automatiquement',
|
||||
noRooms: 'Aucun salon pour le moment',
|
||||
selectOrCreate: 'Selectionnez ou creez un salon pour commencer a discuter',
|
||||
agents: 'Agents',
|
||||
addAgent: 'Ajouter un agent',
|
||||
selectProfile: 'Selectionnez un profil',
|
||||
agentAdded: 'Agent ajoute',
|
||||
agentAlreadyInRoom: "L'agent est deja dans ce salon",
|
||||
noAgents: 'Aucun agent dans ce salon',
|
||||
members: 'Membres',
|
||||
roomCreated: 'Salon cree',
|
||||
roomDeleted: 'Salon supprime',
|
||||
deleteRoomConfirm: 'Supprimer ce salon ?',
|
||||
you: 'Vous',
|
||||
joined: 'Vous avez rejoint le salon',
|
||||
joinFailed: 'Echec de la connexion au salon',
|
||||
inputPlaceholder: 'Tapez un message... (Entree pour envoyer)',
|
||||
enterCode: "Entrez le code d'invitation",
|
||||
yourName: 'Votre nom',
|
||||
yourNamePlaceholder: "Entrez votre nom d'affichage",
|
||||
yourDescription: 'Description (facultatif)',
|
||||
yourDescriptionPlaceholder: 'Decrivez-vous aux autres...',
|
||||
agentName: 'Nom de l\'agent',
|
||||
agentNamePlaceholder: 'Nom personnalise (vide = nom du profil)',
|
||||
agentDesc: 'Description de l\'agent',
|
||||
agentDescPlaceholder: 'Decrivez le role de cet agent...',
|
||||
agentReplying: 'est en train de répondre...',
|
||||
agentCompressing: 'compresse le contexte...',
|
||||
compressionSettings: 'Paramètres de compression',
|
||||
triggerTokens: 'Seuil de tokens',
|
||||
triggerTokensDesc: 'Seuil de tokens pour déclencher la compression',
|
||||
maxHistoryTokens: 'Max tokens historique',
|
||||
maxHistoryTokensDesc: 'Maximum de tokens pour le contexte compressé',
|
||||
tailMessageCount: 'Messages récents',
|
||||
tailMessageCountDesc: 'Nombre de messages récents à conserver',
|
||||
compressionConfig: 'Config. compression',
|
||||
compressNow: 'Comprimer maintenant',
|
||||
compressingInProgress: 'Compression en cours',
|
||||
compressionSaved: 'Configuration enregistrée',
|
||||
},
|
||||
|
||||
// Telechargement
|
||||
download: {
|
||||
downloading: 'Telechargement...',
|
||||
|
||||
@@ -48,6 +48,7 @@ export default {
|
||||
update: '更新',
|
||||
create: '作成',
|
||||
saveFailed: '保存に失敗しました',
|
||||
deleteFailed: '削除に失敗しました',
|
||||
ok: 'OK',
|
||||
copied: 'コピーしました',
|
||||
copy: 'コピー',
|
||||
@@ -76,6 +77,8 @@ export default {
|
||||
channels: 'チャンネル',
|
||||
terminal: 'ターミナル',
|
||||
files: 'ファイル',
|
||||
groupChat: 'グループチャット',
|
||||
groupConversation: '会話',
|
||||
settings: '設定',
|
||||
connected: '接続済み',
|
||||
disconnected: '未接続',
|
||||
@@ -579,6 +582,55 @@ export default {
|
||||
saveFile: '保存',
|
||||
},
|
||||
|
||||
// グループチャット
|
||||
groupChat: {
|
||||
title: 'グループチャット',
|
||||
createRoom: 'ルームを作成',
|
||||
joinByCode: 'コードで参加',
|
||||
roomName: 'ルーム名',
|
||||
roomNamePlaceholder: 'ルーム名を入力',
|
||||
inviteCode: '招待コード',
|
||||
autoGenerate: '自動生成',
|
||||
noRooms: 'ルームがありません',
|
||||
selectOrCreate: 'ルームを選択または作成してチャットを開始',
|
||||
agents: 'エージェント',
|
||||
addAgent: 'エージェントを追加',
|
||||
selectProfile: 'プロファイルを選択',
|
||||
agentAdded: 'エージェントが追加されました',
|
||||
agentAlreadyInRoom: 'このエージェントは既にルームにいます',
|
||||
noAgents: 'このルームにエージェントはいません',
|
||||
members: 'メンバー',
|
||||
roomCreated: 'ルームが作成されました',
|
||||
roomDeleted: 'ルームを削除しました',
|
||||
deleteRoomConfirm: 'このルームを削除しますか?',
|
||||
you: 'あなた',
|
||||
joined: 'ルームに参加しました',
|
||||
joinFailed: 'ルームへの参加に失敗しました',
|
||||
inputPlaceholder: 'メッセージを入力... (Enterで送信)',
|
||||
enterCode: '招待コードを入力',
|
||||
yourName: 'あなたの名前',
|
||||
yourNamePlaceholder: '表示名を入力',
|
||||
yourDescription: '自己紹介(任意)',
|
||||
yourDescriptionPlaceholder: '自分について教えてください...',
|
||||
agentName: 'エージェント名',
|
||||
agentNamePlaceholder: 'カスタム名(空欄ならプロファイル名)',
|
||||
agentDesc: 'エージェントの説明',
|
||||
agentDescPlaceholder: 'このエージェントの役割を説明...',
|
||||
agentReplying: 'が返信中...',
|
||||
agentCompressing: 'がコンテキストを圧縮中...',
|
||||
compressionSettings: '圧縮設定',
|
||||
triggerTokens: '圧縮トリガートークン数',
|
||||
triggerTokensDesc: 'このトークン数を超えるとコンテキスト圧縮がトリガーされます',
|
||||
maxHistoryTokens: '最大履歴トークン数',
|
||||
maxHistoryTokensDesc: '圧縮後のLLM送信最大トークン数',
|
||||
tailMessageCount: '末尾メッセージ数',
|
||||
tailMessageCountDesc: '圧縮後にそのまま保持する最近のメッセージ数',
|
||||
compressionConfig: '圧縮設定',
|
||||
compressNow: '今すぐ圧縮',
|
||||
compressingInProgress: '圧縮中です、お待ちください',
|
||||
compressionSaved: '圧縮設定を保存しました',
|
||||
},
|
||||
|
||||
// ダウンロード
|
||||
download: {
|
||||
downloading: 'ダウンロード中...',
|
||||
|
||||
@@ -48,6 +48,7 @@ export default {
|
||||
update: '업데이트',
|
||||
create: '생성',
|
||||
saveFailed: '저장 실패',
|
||||
deleteFailed: '삭제 실패',
|
||||
ok: '확인',
|
||||
copied: '복사됨',
|
||||
copy: '복사',
|
||||
@@ -76,6 +77,8 @@ export default {
|
||||
channels: '채널',
|
||||
terminal: '터미널',
|
||||
files: '파일',
|
||||
groupChat: '그룹 채팅',
|
||||
groupConversation: '대화',
|
||||
settings: '설정',
|
||||
connected: '연결됨',
|
||||
disconnected: '연결 끊김',
|
||||
@@ -579,6 +582,55 @@ export default {
|
||||
saveFile: '저장',
|
||||
},
|
||||
|
||||
// 그룹 채팅
|
||||
groupChat: {
|
||||
title: '그룹 채팅',
|
||||
createRoom: '방 만들기',
|
||||
joinByCode: '코드로 참여',
|
||||
roomName: '방 이름',
|
||||
roomNamePlaceholder: '방 이름을 입력하세요',
|
||||
inviteCode: '초대 코드',
|
||||
autoGenerate: '자동 생성',
|
||||
noRooms: '아직 방이 없습니다',
|
||||
selectOrCreate: '방을 선택하거나 만들어 채팅을 시작하세요',
|
||||
agents: '에이전트',
|
||||
addAgent: '에이전트 추가',
|
||||
selectProfile: '프로필 선택',
|
||||
agentAdded: '에이전트가 추가되었습니다',
|
||||
agentAlreadyInRoom: '해당 에이전트가 이미 방에 있습니다',
|
||||
noAgents: '이 방에 에이전트가 없습니다',
|
||||
members: '멤버',
|
||||
roomCreated: '방이 생성되었습니다',
|
||||
roomDeleted: '방이 삭제되었습니다',
|
||||
deleteRoomConfirm: '이 방을 삭제하시겠습니까?',
|
||||
you: '나',
|
||||
joined: '방에 참여했습니다',
|
||||
joinFailed: '방 참여에 실패했습니다',
|
||||
inputPlaceholder: '메시지를 입력하세요... (Enter로 전송)',
|
||||
enterCode: '초대 코드를 입력하세요',
|
||||
yourName: '이름',
|
||||
yourNamePlaceholder: '표시 이름을 입력하세요',
|
||||
yourDescription: '설명 (선택)',
|
||||
yourDescriptionPlaceholder: '자신을 소개해 주세요...',
|
||||
agentName: '에이전트 이름',
|
||||
agentNamePlaceholder: '사용자 지정 이름 (빈칸=프로필 이름)',
|
||||
agentDesc: '에이전트 설명',
|
||||
agentDescPlaceholder: '이 에이전트가 하는 일을 설명...',
|
||||
agentReplying: '이(가) 응답 중...',
|
||||
agentCompressing: '이(가) 컨텍스트 압축 중...',
|
||||
compressionSettings: '압축 설정',
|
||||
triggerTokens: '압축 트리거 토큰',
|
||||
triggerTokensDesc: '이 토큰 수를 초과하면 컨텍스트 압축이 시작됩니다',
|
||||
maxHistoryTokens: '최대 기록 토큰',
|
||||
maxHistoryTokensDesc: '압축된 컨텍스트의 최대 토큰 수',
|
||||
tailMessageCount: '최근 메시지 수',
|
||||
tailMessageCountDesc: '압축 후 그대로 유지할 최근 메시지 수',
|
||||
compressionConfig: '압축 설정',
|
||||
compressNow: '지금 압축',
|
||||
compressingInProgress: '압축 진행 중',
|
||||
compressionSaved: '압축 설정이 저장되었습니다',
|
||||
},
|
||||
|
||||
// 다운로드
|
||||
download: {
|
||||
downloading: '다운로드 중...',
|
||||
|
||||
@@ -48,6 +48,7 @@ export default {
|
||||
update: 'Atualizar',
|
||||
create: 'Criar',
|
||||
saveFailed: 'Falha ao salvar',
|
||||
deleteFailed: 'Falha ao excluir',
|
||||
ok: 'OK',
|
||||
copied: 'Copiado',
|
||||
copy: 'Copiar',
|
||||
@@ -76,6 +77,8 @@ export default {
|
||||
channels: 'Canais',
|
||||
terminal: 'Terminal',
|
||||
files: 'Arquivos',
|
||||
groupChat: 'Chat em grupo',
|
||||
groupConversation: 'Conversa',
|
||||
settings: 'Configuracoes',
|
||||
connected: 'Conectado',
|
||||
disconnected: 'Desconectado',
|
||||
@@ -579,6 +582,55 @@ export default {
|
||||
saveFile: 'Salvar',
|
||||
},
|
||||
|
||||
// Chat em grupo
|
||||
groupChat: {
|
||||
title: 'Chat em grupo',
|
||||
createRoom: 'Criar sala',
|
||||
joinByCode: 'Entrar com codigo',
|
||||
roomName: 'Nome da sala',
|
||||
roomNamePlaceholder: 'Digite o nome da sala',
|
||||
inviteCode: 'Codigo de convite',
|
||||
autoGenerate: 'Gerar automaticamente',
|
||||
noRooms: 'Nenhuma sala ainda',
|
||||
selectOrCreate: 'Selecione ou crie uma sala para comecar a conversar',
|
||||
agents: 'Agentes',
|
||||
addAgent: 'Adicionar agente',
|
||||
selectProfile: 'Selecione um perfil',
|
||||
agentAdded: 'Agente adicionado',
|
||||
agentAlreadyInRoom: 'O agente ja esta nesta sala',
|
||||
noAgents: 'Nenhum agente nesta sala',
|
||||
members: 'Membros',
|
||||
roomCreated: 'Sala criada',
|
||||
roomDeleted: 'Sala excluída',
|
||||
deleteRoomConfirm: 'Excluir esta sala?',
|
||||
you: 'Você',
|
||||
joined: 'Entrou na sala',
|
||||
joinFailed: 'Falha ao entrar na sala',
|
||||
inputPlaceholder: 'Digite uma mensagem... (Enter para enviar)',
|
||||
enterCode: 'Digite o codigo de convite',
|
||||
yourName: 'Seu nome',
|
||||
yourNamePlaceholder: 'Digite seu nome de exibicao',
|
||||
yourDescription: 'Descricao (opcional)',
|
||||
yourDescriptionPlaceholder: 'Conte aos outros quem voce e...',
|
||||
agentName: 'Nome do agente',
|
||||
agentNamePlaceholder: 'Nome personalizado (vazio = nome do perfil)',
|
||||
agentDesc: 'Descrição do agente',
|
||||
agentDescPlaceholder: 'Descreva o que este agente faz...',
|
||||
agentReplying: 'está respondendo...',
|
||||
agentCompressing: 'está compactando contexto...',
|
||||
compressionSettings: 'Configuração de compactação',
|
||||
triggerTokens: 'Tokens de acionamento',
|
||||
triggerTokensDesc: 'Limite de tokens para acionar a compactação',
|
||||
maxHistoryTokens: 'Máx. tokens de histórico',
|
||||
maxHistoryTokensDesc: 'Máximo de tokens para o contexto compactado',
|
||||
tailMessageCount: 'Mensagens recentes',
|
||||
tailMessageCountDesc: 'Número de mensagens recentes a manter',
|
||||
compressionConfig: 'Config. de compactação',
|
||||
compressNow: 'Compactar agora',
|
||||
compressingInProgress: 'Compactação em andamento',
|
||||
compressionSaved: 'Configuração salva',
|
||||
},
|
||||
|
||||
// Download
|
||||
download: {
|
||||
downloading: 'Baixando...',
|
||||
|
||||
@@ -46,6 +46,7 @@ export default {
|
||||
save: '保存',
|
||||
saved: '已保存',
|
||||
saveFailed: '保存失败',
|
||||
deleteFailed: '删除失败',
|
||||
ok: '确定',
|
||||
copied: '已复制',
|
||||
copy: '复制',
|
||||
@@ -79,6 +80,7 @@ export default {
|
||||
channels: '频道',
|
||||
gateways: '网关',
|
||||
terminal: '终端',
|
||||
groupChat: '群聊',
|
||||
files: '文件',
|
||||
groupConversation: '对话',
|
||||
groupPlatform: '平台',
|
||||
@@ -537,6 +539,55 @@ export default {
|
||||
processExited: '进程已退出,代码 {code}',
|
||||
},
|
||||
|
||||
// 群聊
|
||||
groupChat: {
|
||||
title: '群聊',
|
||||
createRoom: '创建房间',
|
||||
joinByCode: '通过邀请码加入',
|
||||
roomName: '房间名称',
|
||||
roomNamePlaceholder: '输入房间名称',
|
||||
inviteCode: '邀请码',
|
||||
autoGenerate: '自动生成',
|
||||
noRooms: '暂无房间',
|
||||
selectOrCreate: '选择或创建一个房间开始聊天',
|
||||
agents: '智能体',
|
||||
addAgent: '添加智能体',
|
||||
selectProfile: '选择一个配置',
|
||||
agentAdded: '智能体已添加',
|
||||
agentAlreadyInRoom: '该智能体已在房间中',
|
||||
noAgents: '当前房间暂无智能体',
|
||||
members: '成员',
|
||||
roomCreated: '房间已创建',
|
||||
roomDeleted: '房间已删除',
|
||||
deleteRoomConfirm: '确定删除这个房间吗?',
|
||||
you: '你',
|
||||
joined: '已加入房间',
|
||||
joinFailed: '加入房间失败',
|
||||
inputPlaceholder: '输入消息... (Enter 发送)',
|
||||
enterCode: '输入邀请码',
|
||||
yourName: '你的名称',
|
||||
yourNamePlaceholder: '输入你的群聊昵称',
|
||||
yourDescription: '自我描述(选填)',
|
||||
yourDescriptionPlaceholder: '介绍一下你自己...',
|
||||
agentName: 'Agent 名称',
|
||||
agentNamePlaceholder: '自定义名称(留空则使用 profile 名称)',
|
||||
agentDesc: 'Agent 描述',
|
||||
agentDescPlaceholder: '描述这个 agent 的作用...',
|
||||
agentReplying: '正在回复...',
|
||||
agentCompressing: '正在压缩上下文...',
|
||||
compressionSettings: '压缩设置',
|
||||
triggerTokens: '触发压缩 Token 数',
|
||||
triggerTokensDesc: '消息 token 数超过此值时触发上下文压缩',
|
||||
maxHistoryTokens: '最大历史 Token 数',
|
||||
maxHistoryTokensDesc: '压缩后发送给 LLM 的最大 token 数',
|
||||
tailMessageCount: '保留最近消息数',
|
||||
tailMessageCountDesc: '压缩后保留最近的原始消息条数',
|
||||
compressionConfig: '压缩配置',
|
||||
compressionSaved: '压缩配置已保存',
|
||||
compressNow: '立即压缩',
|
||||
compressingInProgress: '正在压缩中,请稍后',
|
||||
},
|
||||
|
||||
// 用量统计
|
||||
usage: {
|
||||
title: '用量统计',
|
||||
|
||||
@@ -70,6 +70,11 @@ const router = createRouter({
|
||||
name: 'hermes.terminal',
|
||||
component: () => import('@/views/hermes/TerminalView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/hermes/group-chat',
|
||||
name: 'hermes.groupChat',
|
||||
component: () => import('@/views/hermes/GroupChatView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/hermes/files',
|
||||
name: 'hermes.files',
|
||||
|
||||
@@ -492,7 +492,16 @@ export const useChatStore = defineStore('chat', () => {
|
||||
// that was just created and whose first run is still in-flight. Without
|
||||
// this, refreshing mid-run would wipe the session and fall back to
|
||||
// sessions[0], which is exactly what the user reported.
|
||||
const localOnly = sessions.value.filter(s => !freshIds.has(s.id))
|
||||
// Sessions without an active in-flight run are considered deleted and
|
||||
// cleaned up along with their cached messages.
|
||||
const localOnly = sessions.value.filter(s => {
|
||||
if (freshIds.has(s.id)) return false
|
||||
if (readInFlight(s.id)) return true
|
||||
// Session no longer exists on server and no active run — clean up cache
|
||||
removeItemWithLegacy(msgsCacheKey(s.id), legacyMsgsCacheKey(s.id))
|
||||
removeItemWithLegacy(inFlightKey(s.id), legacyInFlightKey(s.id))
|
||||
return false
|
||||
})
|
||||
sessions.value = [...localOnly, ...fresh]
|
||||
persistSessionsList()
|
||||
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import {
|
||||
connectGroupChat,
|
||||
disconnectGroupChat,
|
||||
getSocket,
|
||||
getStoredUserId,
|
||||
getStoredUserName,
|
||||
type RoomInfo,
|
||||
type RoomAgent,
|
||||
type ChatMessage,
|
||||
type MemberInfo,
|
||||
createRoom,
|
||||
listRooms,
|
||||
getRoomDetail,
|
||||
joinRoomByCode,
|
||||
addAgent,
|
||||
listAgents,
|
||||
removeAgent,
|
||||
deleteRoom as deleteRoomApi,
|
||||
} from '@/api/hermes/group-chat'
|
||||
|
||||
export const useGroupChatStore = defineStore('groupChat', () => {
|
||||
// ─── State ─────────────────────────────────────────────
|
||||
const connected = ref(false)
|
||||
const currentRoomId = ref<string | null>(null)
|
||||
const rooms = ref<RoomInfo[]>([])
|
||||
const messages = ref<ChatMessage[]>([])
|
||||
const members = ref<MemberInfo[]>([])
|
||||
const agents = ref<RoomAgent[]>([])
|
||||
const roomName = ref('')
|
||||
const isJoining = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const typingUsers = ref<Map<string, { name: string; timer: ReturnType<typeof setTimeout> }>>(new Map())
|
||||
const contextStatuses = ref<Map<string, { agentName: string; status: string }>>(new Map())
|
||||
|
||||
// Computed: returns first active status for backward compat
|
||||
const contextStatus = computed(() => {
|
||||
for (const [, status] of contextStatuses.value) {
|
||||
return status
|
||||
}
|
||||
return null
|
||||
})
|
||||
const userId = ref(getStoredUserId())
|
||||
const userName = ref(getStoredUserName() || '')
|
||||
|
||||
// ─── Computed ───────────────────────────────────────────
|
||||
const sortedMessages = computed(() => {
|
||||
return [...messages.value].sort((a, b) => a.timestamp - b.timestamp)
|
||||
})
|
||||
|
||||
const memberNames = computed(() => {
|
||||
return members.value.map(m => m.name)
|
||||
})
|
||||
|
||||
const typingNames = computed(() => {
|
||||
return Array.from(typingUsers.value.values()).map(u => u.name)
|
||||
})
|
||||
|
||||
const typingText = computed(() => {
|
||||
const names = typingNames.value
|
||||
if (names.length === 0) return ''
|
||||
if (names.length === 1) return `${names[0]} is typing...`
|
||||
if (names.length === 2) return `${names[0]} and ${names[1]} are typing...`
|
||||
return `${names[0]} and ${names.length - 1} others are typing...`
|
||||
})
|
||||
|
||||
// ─── Connection ────────────────────────────────────────
|
||||
function connect() {
|
||||
const socket = connectGroupChat({
|
||||
userId: userId.value,
|
||||
userName: userName.value || undefined,
|
||||
})
|
||||
console.log('[GroupChat] connecting...', { userId: userId.value, userName: userName.value })
|
||||
|
||||
socket.on('connect', () => {
|
||||
console.log('[GroupChat] connected, socket id:', socket.id)
|
||||
connected.value = true
|
||||
error.value = null
|
||||
})
|
||||
|
||||
socket.on('disconnect', (reason) => {
|
||||
console.log('[GroupChat] disconnected:', reason)
|
||||
connected.value = false
|
||||
})
|
||||
|
||||
socket.on('connect_error', (err: Error) => {
|
||||
console.error('[GroupChat] connect_error:', err.message)
|
||||
error.value = err.message
|
||||
connected.value = false
|
||||
})
|
||||
|
||||
socket.on('message', (msg: ChatMessage) => {
|
||||
if (msg.roomId === currentRoomId.value) {
|
||||
messages.value.push(msg)
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('member_joined', (data: { roomId: string; members: MemberInfo[] }) => {
|
||||
if (data.roomId === currentRoomId.value) {
|
||||
members.value = data.members
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('member_left', (data: { roomId: string; members: MemberInfo[] }) => {
|
||||
if (data.roomId === currentRoomId.value) {
|
||||
members.value = data.members
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('typing', (data: { roomId: string; userId: string; userName: string }) => {
|
||||
if (data.roomId === currentRoomId.value && !typingUsers.value.has(data.userId)) {
|
||||
const timer = setTimeout(() => typingUsers.value.delete(data.userId), 5000)
|
||||
typingUsers.value.set(data.userId, { name: data.userName, timer })
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('stop_typing', (data: { roomId: string; userId: string }) => {
|
||||
if (data.roomId === currentRoomId.value && typingUsers.value.has(data.userId)) {
|
||||
const entry = typingUsers.value.get(data.userId)!
|
||||
clearTimeout(entry.timer)
|
||||
typingUsers.value.delete(data.userId)
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('context_status', (data: { roomId: string; agentName: string; status: string }) => {
|
||||
if (data.roomId === currentRoomId.value) {
|
||||
if (data.status === 'ready') {
|
||||
contextStatuses.value.delete(data.agentName)
|
||||
} else {
|
||||
contextStatuses.value.set(data.agentName, { agentName: data.agentName, status: data.status })
|
||||
}
|
||||
// Trigger reactivity
|
||||
contextStatuses.value = new Map(contextStatuses.value)
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('room_updated', (data: { roomId: string; totalTokens: number }) => {
|
||||
const room = rooms.value.find(r => r.id === data.roomId)
|
||||
if (room) room.totalTokens = data.totalTokens
|
||||
})
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
disconnectGroupChat()
|
||||
connected.value = false
|
||||
currentRoomId.value = null
|
||||
messages.value = []
|
||||
members.value = []
|
||||
agents.value = []
|
||||
roomName.value = ''
|
||||
typingUsers.value.clear()
|
||||
contextStatuses.value.clear()
|
||||
}
|
||||
|
||||
function setUserInfo(name: string, description: string) {
|
||||
userName.value = name
|
||||
localStorage.setItem('gc_user_name', name)
|
||||
localStorage.setItem('gc_user_description', description)
|
||||
}
|
||||
|
||||
// ─── Room Actions ──────────────────────────────────────
|
||||
async function joinRoom(roomId: string) {
|
||||
isJoining.value = true
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
const res = await getRoomDetail(roomId)
|
||||
currentRoomId.value = res.room.id
|
||||
roomName.value = res.room.name
|
||||
messages.value = res.messages
|
||||
agents.value = res.agents
|
||||
members.value = res.members || []
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
} finally {
|
||||
isJoining.value = false
|
||||
}
|
||||
|
||||
// Join via socket for real-time updates
|
||||
const socket = getSocket()
|
||||
if (socket) {
|
||||
await new Promise<void>((resolve) => {
|
||||
socket.emit('join', { roomId, name: userName.value || undefined }, (res: any) => {
|
||||
if (!res?.error) {
|
||||
members.value = res.members || []
|
||||
if (res.agents) agents.value = res.agents
|
||||
|
||||
// Restore typing state from server
|
||||
if (res.typingUsers) {
|
||||
for (const u of res.typingUsers) {
|
||||
if (!typingUsers.value.has(u.userId)) {
|
||||
const timer = setTimeout(() => typingUsers.value.delete(u.userId), 5000)
|
||||
typingUsers.value.set(u.userId, { name: u.userName, timer })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore context statuses from server
|
||||
if (res.contextStatuses) {
|
||||
contextStatuses.value = new Map(
|
||||
res.contextStatuses.map((s: any) => [s.agentName, s])
|
||||
)
|
||||
}
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage(content: string) {
|
||||
const socket = getSocket()
|
||||
if (!socket || !currentRoomId.value) return
|
||||
emitStopTyping()
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
socket!.emit('message', { roomId: currentRoomId.value, content }, (res: { id?: string; error?: string }) => {
|
||||
if (res.error) {
|
||||
reject(new Error(res.error))
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function loadRooms() {
|
||||
try {
|
||||
const res = await listRooms()
|
||||
rooms.value = res.rooms
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
}
|
||||
}
|
||||
|
||||
async function createNewRoom(name: string, inviteCode: string, agentList?: { profile: string; name?: string; description?: string; invited?: boolean }[], compression?: { triggerTokens: number; maxHistoryTokens: number; tailMessageCount: number }) {
|
||||
try {
|
||||
const res = await createRoom({
|
||||
name,
|
||||
inviteCode,
|
||||
agents: agentList,
|
||||
compression: compression || { triggerTokens: 100000, maxHistoryTokens: 32000, tailMessageCount: 20 },
|
||||
})
|
||||
rooms.value.push(res.room)
|
||||
return res
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function joinByCode(code: string) {
|
||||
try {
|
||||
const res = await joinRoomByCode(code)
|
||||
await joinRoom(res.room.id)
|
||||
return res.room
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteRoom(roomId: string) {
|
||||
try {
|
||||
await deleteRoomApi(roomId)
|
||||
rooms.value = rooms.value.filter(r => r.id !== roomId)
|
||||
if (currentRoomId.value === roomId) {
|
||||
currentRoomId.value = null
|
||||
messages.value = []
|
||||
members.value = []
|
||||
agents.value = []
|
||||
roomName.value = ''
|
||||
}
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Agent Actions ─────────────────────────────────────
|
||||
async function loadAgents(roomId: string) {
|
||||
try {
|
||||
const res = await listAgents(roomId)
|
||||
agents.value = res.agents
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
async function addAgentToRoom(roomId: string, data: { profile: string; name?: string; description?: string; invited?: boolean }) {
|
||||
try {
|
||||
const res = await addAgent(roomId, data)
|
||||
agents.value.push(res.agent)
|
||||
return res.agent
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function removeAgentFromRoom(roomId: string, agentId: string) {
|
||||
try {
|
||||
await removeAgent(roomId, agentId)
|
||||
agents.value = agents.value.filter(a => a.id !== agentId)
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Typing ────────────────────────────────────────────
|
||||
let _typingTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
function emitTyping() {
|
||||
const socket = getSocket()
|
||||
if (!socket || !currentRoomId.value) return
|
||||
socket.emit('typing', { roomId: currentRoomId.value })
|
||||
if (_typingTimer) clearTimeout(_typingTimer)
|
||||
_typingTimer = setTimeout(() => emitStopTyping(), 4000)
|
||||
}
|
||||
|
||||
function emitStopTyping() {
|
||||
const socket = getSocket()
|
||||
if (!socket || !currentRoomId.value) return
|
||||
socket.emit('stop_typing', { roomId: currentRoomId.value })
|
||||
if (_typingTimer) { clearTimeout(_typingTimer); _typingTimer = null }
|
||||
}
|
||||
|
||||
return {
|
||||
// State
|
||||
connected,
|
||||
currentRoomId,
|
||||
rooms,
|
||||
messages,
|
||||
members,
|
||||
agents,
|
||||
roomName,
|
||||
isJoining,
|
||||
error,
|
||||
contextStatus,
|
||||
contextStatuses,
|
||||
userId,
|
||||
userName,
|
||||
// Computed
|
||||
sortedMessages,
|
||||
memberNames,
|
||||
typingNames,
|
||||
typingText,
|
||||
// Actions
|
||||
connect,
|
||||
disconnect,
|
||||
setUserInfo,
|
||||
joinRoom,
|
||||
sendMessage,
|
||||
loadRooms,
|
||||
emitTyping,
|
||||
emitStopTyping,
|
||||
createNewRoom,
|
||||
joinByCode,
|
||||
deleteRoom,
|
||||
loadAgents,
|
||||
addAgentToRoom,
|
||||
removeAgentFromRoom,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
import GroupChatPanel from '@/components/hermes/group-chat/GroupChatPanel.vue'
|
||||
import { useGroupChatStore } from '@/stores/hermes/group-chat'
|
||||
|
||||
const store = useGroupChatStore()
|
||||
|
||||
onMounted(() => {
|
||||
store.connect()
|
||||
store.loadRooms()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
store.disconnect()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="group-chat-view">
|
||||
<GroupChatPanel />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.group-chat-view {
|
||||
height: calc(100 * var(--vh));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
</style>
|
||||
@@ -3,6 +3,7 @@ import { mkdir, writeFile } from 'fs/promises'
|
||||
import { basename, join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import * as hermesCli from '../../services/hermes/hermes-cli'
|
||||
import { drainPendingSessionDeletes } from '../../services/hermes/group-chat'
|
||||
import { getGatewayManagerInstance } from '../../services/gateway-bootstrap'
|
||||
import { logger } from '../../services/logger'
|
||||
|
||||
@@ -118,7 +119,17 @@ export async function switchProfile(ctx: any) {
|
||||
} catch (err: any) {
|
||||
logger.error(err, 'Ensure config failed')
|
||||
}
|
||||
ctx.body = { success: true, message: output.trim() }
|
||||
const drainResult = await drainPendingSessionDeletes(name)
|
||||
logger.info('[switchProfile] drain result for profile "%s": %d deleted, %d failed', name, drainResult.deleted.length, drainResult.failed.length)
|
||||
if (drainResult.failed.length > 0) {
|
||||
logger.warn({ profile: name, failed: drainResult.failed }, 'Failed to drain some pending session deletes after profile switch')
|
||||
}
|
||||
ctx.body = {
|
||||
success: true,
|
||||
message: output.trim(),
|
||||
drained_session_deletes: drainResult.deleted.length,
|
||||
failed_session_deletes: drainResult.failed.length,
|
||||
}
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
ctx.body = { error: err.message }
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
import { listSessionSummaries, searchSessionSummaries } from '../../db/hermes/sessions-db'
|
||||
import { deleteUsage, getUsage, getUsageBatch } from '../../db/hermes/usage-store'
|
||||
import { getModelContextLength } from '../../services/hermes/model-context'
|
||||
import type { ConversationDetail, ConversationSummary } from '../../services/hermes/conversations'
|
||||
import { getActiveProfileName } from '../../services/hermes/hermes-profile'
|
||||
import { getGroupChatServer } from '../../routes/hermes/group-chat'
|
||||
import { logger } from '../../services/logger'
|
||||
|
||||
function parseHumanOnly(value: unknown): boolean {
|
||||
@@ -20,6 +23,35 @@ function parseLimit(value: unknown): number | undefined {
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
|
||||
}
|
||||
|
||||
function getPendingDeletedSessionIds(): Set<string> {
|
||||
return getGroupChatServer()?.getStorage().getPendingDeletedSessionIds() || new Set<string>()
|
||||
}
|
||||
|
||||
function isPendingDeletedSession(sessionId: string): boolean {
|
||||
return getPendingDeletedSessionIds().has(sessionId)
|
||||
}
|
||||
|
||||
function filterPendingDeletedSessions<T extends { id: string }>(items: T[]): T[] {
|
||||
const pendingIds = getPendingDeletedSessionIds()
|
||||
if (pendingIds.size === 0) return items
|
||||
return items.filter(item => !pendingIds.has(item.id))
|
||||
}
|
||||
|
||||
function filterPendingDeletedConversationSummaries(items: ConversationSummary[]): ConversationSummary[] {
|
||||
return filterPendingDeletedSessions(items)
|
||||
}
|
||||
|
||||
function hasPendingDeletedConversation(detail: ConversationDetail): boolean {
|
||||
const pendingIds = getPendingDeletedSessionIds()
|
||||
if (pendingIds.size === 0) return false
|
||||
if (pendingIds.has(detail.session_id)) return true
|
||||
return detail.messages.some(message => pendingIds.has(message.session_id))
|
||||
}
|
||||
|
||||
function getGroupChatStorage() {
|
||||
return getGroupChatServer()?.getStorage() || null
|
||||
}
|
||||
|
||||
export async function listConversations(ctx: any) {
|
||||
const source = (ctx.query.source as string) || undefined
|
||||
const humanOnly = parseHumanOnly(ctx.query.humanOnly)
|
||||
@@ -27,14 +59,14 @@ export async function listConversations(ctx: any) {
|
||||
|
||||
try {
|
||||
const sessions = await listConversationSummariesFromDb({ source, humanOnly, limit })
|
||||
ctx.body = { sessions }
|
||||
ctx.body = { sessions: filterPendingDeletedConversationSummaries(sessions) }
|
||||
return
|
||||
} catch (err) {
|
||||
logger.warn(err, 'Hermes Conversation DB: summary query failed, falling back to CLI export')
|
||||
}
|
||||
|
||||
const sessions = await listConversationSummaries({ source, humanOnly, limit })
|
||||
ctx.body = { sessions }
|
||||
ctx.body = { sessions: filterPendingDeletedConversationSummaries(sessions) }
|
||||
}
|
||||
|
||||
export async function getConversationMessages(ctx: any) {
|
||||
@@ -43,7 +75,7 @@ export async function getConversationMessages(ctx: any) {
|
||||
|
||||
try {
|
||||
const detail = await getConversationDetailFromDb(ctx.params.id, { source, humanOnly })
|
||||
if (!detail) {
|
||||
if (!detail || hasPendingDeletedConversation(detail)) {
|
||||
ctx.status = 404
|
||||
ctx.body = { error: 'Conversation not found' }
|
||||
return
|
||||
@@ -55,7 +87,7 @@ export async function getConversationMessages(ctx: any) {
|
||||
}
|
||||
|
||||
const detail = await getConversationDetail(ctx.params.id, { source, humanOnly })
|
||||
if (!detail) {
|
||||
if (!detail || hasPendingDeletedConversation(detail)) {
|
||||
ctx.status = 404
|
||||
ctx.body = { error: 'Conversation not found' }
|
||||
return
|
||||
@@ -69,14 +101,14 @@ export async function list(ctx: any) {
|
||||
|
||||
try {
|
||||
const sessions = await listSessionSummaries(source, limit && limit > 0 ? limit : 2000)
|
||||
ctx.body = { sessions }
|
||||
ctx.body = { sessions: filterPendingDeletedSessions(sessions) }
|
||||
return
|
||||
} catch (err) {
|
||||
logger.warn(err, 'Hermes Session DB: summary query failed, falling back to CLI')
|
||||
}
|
||||
|
||||
const sessions = await hermesCli.listSessions(source, limit)
|
||||
ctx.body = { sessions }
|
||||
ctx.body = { sessions: filterPendingDeletedSessions(sessions) }
|
||||
}
|
||||
|
||||
export async function search(ctx: any) {
|
||||
@@ -88,7 +120,7 @@ export async function search(ctx: any) {
|
||||
|
||||
try {
|
||||
const results = await searchSessionSummaries(q, source, limit && limit > 0 ? limit : 20)
|
||||
ctx.body = { results }
|
||||
ctx.body = { results: filterPendingDeletedSessions(results) }
|
||||
} catch (err) {
|
||||
logger.error(err, 'Hermes Session DB: search failed')
|
||||
ctx.status = 500
|
||||
@@ -97,6 +129,12 @@ export async function search(ctx: any) {
|
||||
}
|
||||
|
||||
export async function get(ctx: any) {
|
||||
if (isPendingDeletedSession(ctx.params.id)) {
|
||||
ctx.status = 404
|
||||
ctx.body = { error: 'Session not found' }
|
||||
return
|
||||
}
|
||||
|
||||
const session = await hermesCli.getSession(ctx.params.id)
|
||||
if (!session) {
|
||||
ctx.status = 404
|
||||
@@ -107,14 +145,44 @@ export async function get(ctx: any) {
|
||||
}
|
||||
|
||||
export async function remove(ctx: any) {
|
||||
const ok = await hermesCli.deleteSession(ctx.params.id)
|
||||
const sessionId = ctx.params.id
|
||||
const storage = getGroupChatStorage()
|
||||
const currentProfile = getActiveProfileName()
|
||||
const mapped = storage?.getSessionProfile(sessionId) || null
|
||||
|
||||
logger.info('[remove] sessionId=%s, currentProfile=%s, mapped=%j', sessionId, currentProfile, mapped)
|
||||
|
||||
if (!mapped) {
|
||||
logger.info('[remove] no mapping found, deleting directly')
|
||||
const ok = await hermesCli.deleteSession(sessionId)
|
||||
if (!ok) {
|
||||
ctx.status = 500
|
||||
ctx.body = { error: 'Failed to delete session' }
|
||||
return
|
||||
}
|
||||
deleteUsage(ctx.params.id)
|
||||
deleteUsage(sessionId)
|
||||
ctx.body = { ok: true }
|
||||
return
|
||||
}
|
||||
|
||||
if (mapped.profile_name === currentProfile) {
|
||||
logger.info('[remove] same profile, deleting directly')
|
||||
const ok = await hermesCli.deleteSession(sessionId)
|
||||
if (!ok) {
|
||||
ctx.status = 500
|
||||
ctx.body = { error: 'Failed to delete session' }
|
||||
return
|
||||
}
|
||||
storage?.deleteSessionProfile(sessionId)
|
||||
deleteUsage(sessionId)
|
||||
ctx.body = { ok: true }
|
||||
return
|
||||
}
|
||||
|
||||
logger.info('[remove] cross-profile detected, enqueued deferred delete for profile=%s', mapped.profile_name)
|
||||
storage?.enqueuePendingSessionDelete(sessionId, mapped.profile_name)
|
||||
deleteUsage(sessionId)
|
||||
ctx.body = { ok: true, deferred: true }
|
||||
}
|
||||
|
||||
export async function usageBatch(ctx: any) {
|
||||
|
||||
@@ -159,20 +159,73 @@ function containsCjk(text: string): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
function isNumericQuery(text: string): boolean {
|
||||
return /^\d+(?:\s+\d+)*$/.test(text.trim())
|
||||
function escapeLikePattern(value: string): string {
|
||||
return value.replace(/[\\%_]/g, (match) => `\\${match}`)
|
||||
}
|
||||
|
||||
function hasUnsafeChars(text: string): boolean {
|
||||
return /[^\w\s\u4e00-\u9fff\u3400-\u4dbf\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(text)
|
||||
function buildLikePattern(value: string): string {
|
||||
return `%${escapeLikePattern(value)}%`
|
||||
}
|
||||
|
||||
function runLikeContentSearch(
|
||||
function normalizeTitleLikeQuery(query: string): string {
|
||||
const tokens = query.match(/"[^"]*"\*?|\S+/g)
|
||||
if (!tokens) return query
|
||||
|
||||
const normalizedTokens = tokens
|
||||
.map((token) => {
|
||||
let value = token.endsWith('*') ? token.slice(0, -1) : token
|
||||
if (value.startsWith('"') && value.endsWith('"')) {
|
||||
value = value.slice(1, -1)
|
||||
}
|
||||
return value
|
||||
})
|
||||
.filter(Boolean)
|
||||
|
||||
return normalizedTokens.join(' ').trim() || query
|
||||
}
|
||||
|
||||
function shouldUseLiteralContentSearch(query: string): boolean {
|
||||
const trimmed = query.trim()
|
||||
if (!trimmed) return false
|
||||
if (/[^\p{L}\p{N}\s"*.-]/u.test(trimmed)) return true
|
||||
|
||||
const tokens = trimmed.match(/"[^"]*"\*?|\S+/g)
|
||||
if (!tokens) return true
|
||||
|
||||
for (const token of tokens) {
|
||||
if (/^(AND|OR|NOT)$/i.test(token)) continue
|
||||
|
||||
const raw = token.endsWith('*') ? token.slice(0, -1) : token
|
||||
if (!raw) return true
|
||||
|
||||
if (raw.startsWith('"') && raw.endsWith('"')) {
|
||||
const inner = raw.slice(1, -1)
|
||||
if (!inner.trim()) return true
|
||||
if (!/^[\p{L}\p{N}\s.-]+$/u.test(inner)) return true
|
||||
if ((inner.includes('.') || inner.includes('-')) && !/^[\p{L}\p{N}]+(?:[.-][\p{L}\p{N}]+)*(?:\s+[\p{L}\p{N}]+(?:[.-][\p{L}\p{N}]+)*)*$/u.test(inner)) return true
|
||||
continue
|
||||
}
|
||||
|
||||
if (raw.includes('.') || raw.includes('-')) {
|
||||
if (!/^[\p{L}\p{N}]+(?:[.-][\p{L}\p{N}]+)*$/u.test(raw)) return true
|
||||
continue
|
||||
}
|
||||
|
||||
if (!/^[\p{L}\p{N}]+$/u.test(raw)) return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function runLiteralContentSearch(
|
||||
db: { prepare: (sql: string) => { all: (...params: any[]) => Record<string, unknown>[] } },
|
||||
source: string | undefined,
|
||||
query: string,
|
||||
limit: number,
|
||||
): Record<string, unknown>[] {
|
||||
const likeBase = buildBaseSessionSql(source)
|
||||
const loweredQuery = query.toLowerCase()
|
||||
const likePattern = buildLikePattern(loweredQuery)
|
||||
const likeSql = `
|
||||
WITH base AS (
|
||||
${likeBase.sql}
|
||||
@@ -182,17 +235,17 @@ function runLikeContentSearch(
|
||||
m.id AS matched_message_id,
|
||||
substr(
|
||||
m.content,
|
||||
max(1, instr(m.content, ?) - 40),
|
||||
max(1, instr(LOWER(m.content), ?) - 40),
|
||||
120
|
||||
) AS snippet,
|
||||
0 AS rank
|
||||
FROM base
|
||||
JOIN messages m ON m.session_id = base.id
|
||||
WHERE m.content LIKE ?
|
||||
WHERE LOWER(m.content) LIKE ? ESCAPE '\\'
|
||||
ORDER BY base.last_active DESC, m.timestamp DESC
|
||||
LIMIT ?
|
||||
`
|
||||
const likeStatement = db.prepare(likeSql)
|
||||
return likeStatement.all(...likeBase.params, query, `%${query}%`) as Record<string, unknown>[]
|
||||
return db.prepare(likeSql).all(...likeBase.params, loweredQuery, likePattern, limit * 4) as Record<string, unknown>[]
|
||||
}
|
||||
|
||||
function sanitizeFtsQuery(query: string): string {
|
||||
@@ -208,7 +261,7 @@ function sanitizeFtsQuery(query: string): string {
|
||||
sanitized = sanitized.replace(/(^|\s)\*/g, '$1')
|
||||
sanitized = sanitized.trim().replace(/^(AND|OR|NOT)\b\s*/i, '')
|
||||
sanitized = sanitized.trim().replace(/\s+(AND|OR|NOT)\s*$/i, '')
|
||||
sanitized = sanitized.replace(/\b(\w+(?:[.-]\w+)+)\b/g, '"$1"')
|
||||
sanitized = sanitized.replace(/\b([\p{L}\p{N}]+(?:[.-][\p{L}\p{N}]+)+)\b/gu, '"$1"')
|
||||
|
||||
for (let i = 0; i < quotedParts.length; i += 1) {
|
||||
sanitized = sanitized.replace(`\u0000Q${i}\u0000`, quotedParts[i])
|
||||
@@ -218,7 +271,7 @@ function sanitizeFtsQuery(query: string): string {
|
||||
}
|
||||
|
||||
function toPrefixQuery(query: string): string {
|
||||
const tokens = query.match(/"[^"]*"|\S+/g)
|
||||
const tokens = query.match(/"[^"]*"\*?|\S+/g)
|
||||
if (!tokens) return ''
|
||||
return tokens
|
||||
.map((token) => {
|
||||
@@ -282,6 +335,8 @@ export async function searchSessionSummaries(
|
||||
const db = new DatabaseSync(sessionDbPath(), { open: true, readOnly: true })
|
||||
const normalized = sanitizeFtsQuery(trimmed)
|
||||
const prefixQuery = toPrefixQuery(normalized)
|
||||
const titlePattern = buildLikePattern(normalizeTitleLikeQuery(trimmed).toLowerCase())
|
||||
const useLiteralContentSearch = containsCjk(trimmed) || shouldUseLiteralContentSearch(trimmed)
|
||||
let titleRows: Record<string, unknown>[] = []
|
||||
|
||||
try {
|
||||
@@ -301,13 +356,13 @@ export async function searchSessionSummaries(
|
||||
END AS snippet,
|
||||
0 AS rank
|
||||
FROM base
|
||||
WHERE LOWER(COALESCE(base.title, '')) LIKE ?
|
||||
WHERE LOWER(COALESCE(base.title, '')) LIKE ? ESCAPE '\\'
|
||||
ORDER BY base.last_active DESC
|
||||
LIMIT ?
|
||||
`
|
||||
|
||||
const titleStatement = db.prepare(titleSql)
|
||||
titleRows = titleStatement.all(...titleBase.params, `%${trimmed.toLowerCase()}%`, limit) as Record<string, unknown>[]
|
||||
titleRows = titleStatement.all(...titleBase.params, titlePattern, limit) as Record<string, unknown>[]
|
||||
|
||||
const contentSql = `
|
||||
WITH base AS (
|
||||
@@ -326,7 +381,9 @@ export async function searchSessionSummaries(
|
||||
LIMIT ?
|
||||
`
|
||||
|
||||
const contentRows = prefixQuery
|
||||
const contentRows = useLiteralContentSearch
|
||||
? runLiteralContentSearch(db, source, trimmed, limit)
|
||||
: prefixQuery
|
||||
? (db.prepare(contentSql).all(...contentBase.params, prefixQuery, limit * 4) as Record<string, unknown>[])
|
||||
: []
|
||||
|
||||
@@ -351,19 +408,7 @@ export async function searchSessionSummaries(
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
if (containsCjk(normalized)) {
|
||||
const likeRows = runLikeContentSearch(db, source, trimmed)
|
||||
const merged = new Map<string, HermesSessionSearchRow>()
|
||||
for (const row of likeRows) {
|
||||
const mapped = mapSearchRow(row)
|
||||
if (!merged.has(mapped.id)) {
|
||||
merged.set(mapped.id, mapped)
|
||||
}
|
||||
}
|
||||
return [...merged.values()].slice(0, limit)
|
||||
}
|
||||
|
||||
if (isNumericQuery(trimmed) || hasUnsafeChars(trimmed)) {
|
||||
const likeRows = runLikeContentSearch(db, source, trimmed)
|
||||
const likeRows = runLiteralContentSearch(db, source, trimmed, limit)
|
||||
const merged = new Map<string, HermesSessionSearchRow>()
|
||||
for (const row of titleRows) {
|
||||
const mapped = mapSearchRow(row)
|
||||
@@ -375,7 +420,12 @@ export async function searchSessionSummaries(
|
||||
merged.set(mapped.id, mapped)
|
||||
}
|
||||
}
|
||||
return [...merged.values()].slice(0, limit)
|
||||
const items = [...merged.values()]
|
||||
items.sort((a, b) => {
|
||||
if (a.rank !== b.rank) return a.rank - b.rank
|
||||
return b.last_active - a.last_active
|
||||
})
|
||||
return items.slice(0, limit)
|
||||
}
|
||||
|
||||
throw new Error(`Failed to search sessions: ${message}`)
|
||||
|
||||
@@ -9,11 +9,13 @@ import { mkdir } from 'fs/promises'
|
||||
import { readFileSync } from 'fs'
|
||||
import { config } from './config'
|
||||
import { getToken, requireAuth } from './services/auth'
|
||||
import { initGatewayManager } from './services/gateway-bootstrap'
|
||||
import { initGatewayManager, getGatewayManagerInstance } from './services/gateway-bootstrap'
|
||||
import { bindShutdown } from './services/shutdown'
|
||||
import { setupTerminalWebSocket } from './routes/hermes/terminal'
|
||||
import { startVersionCheck } from './routes/health'
|
||||
import { registerRoutes } from './routes'
|
||||
import { setGroupChatServer } from './routes/hermes/group-chat'
|
||||
import { GroupChatServer } from './services/hermes/group-chat'
|
||||
import { logger } from './services/logger'
|
||||
|
||||
// Injected by esbuild at build time; fallback to reading package.json in dev mode
|
||||
@@ -85,6 +87,19 @@ export async function bootstrap() {
|
||||
setupTerminalWebSocket(server)
|
||||
console.log('[bootstrap] terminal websocket setup')
|
||||
|
||||
// Group chat Socket.IO (must be after server is created)
|
||||
const groupChatServer = new GroupChatServer(server)
|
||||
setGroupChatServer(groupChatServer)
|
||||
groupChatServer.setGatewayManager(getGatewayManagerInstance())
|
||||
|
||||
// Catch-all: destroy upgrade requests not handled by terminal or Socket.IO
|
||||
server.on('upgrade', (req: any, socket: any) => {
|
||||
const url = new URL(req.url || '', `http://${req.headers.host}`)
|
||||
if (url.pathname !== '/api/hermes/terminal' && !url.pathname.startsWith('/socket.io/')) {
|
||||
socket.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
server.on('listening', () => {
|
||||
const interfaces = os.networkInterfaces()
|
||||
const localIp = Object.values(interfaces).flat().find(i => i?.family === 'IPv4' && !i?.internal)?.address || 'localhost'
|
||||
@@ -93,6 +108,9 @@ export async function bootstrap() {
|
||||
console.log(`Log: ~/.hermes-web-ui/logs/server.log`)
|
||||
logger.info('Server: http://localhost:%d (LAN: http://%s:%d)', config.port, localIp, config.port)
|
||||
logger.info('Upstream: %s', config.upstream)
|
||||
|
||||
// Restore group chat agents after server is ready
|
||||
groupChatServer.restoreWhenReady()
|
||||
})
|
||||
|
||||
server.on('error', (err: any) => {
|
||||
@@ -100,7 +118,7 @@ export async function bootstrap() {
|
||||
logger.error({ err }, 'Server error')
|
||||
})
|
||||
|
||||
bindShutdown(server)
|
||||
bindShutdown(server, groupChatServer)
|
||||
startVersionCheck()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import Router from '@koa/router'
|
||||
import type { GroupChatServer } from '../../services/hermes/group-chat'
|
||||
|
||||
export const groupChatRoutes = new Router()
|
||||
|
||||
let chatServer: GroupChatServer | null = null
|
||||
|
||||
export function setGroupChatServer(server: GroupChatServer) {
|
||||
chatServer = server
|
||||
}
|
||||
|
||||
export function getGroupChatServer(): GroupChatServer | null {
|
||||
return chatServer
|
||||
}
|
||||
|
||||
function generateId(): string {
|
||||
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
}
|
||||
|
||||
// Create room
|
||||
groupChatRoutes.post('/api/hermes/group-chat/rooms', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const { name, inviteCode, agents, compression } = ctx.request.body as {
|
||||
name?: string
|
||||
inviteCode?: string
|
||||
agents?: { profile: string; name?: string; description?: string; invited?: boolean }[]
|
||||
compression?: { triggerTokens?: number; maxHistoryTokens?: number; tailMessageCount?: number }
|
||||
}
|
||||
if (!name || !inviteCode) {
|
||||
ctx.status = 400
|
||||
ctx.body = { error: 'name and inviteCode are required' }
|
||||
return
|
||||
}
|
||||
|
||||
const roomId = generateId()
|
||||
const storage = chatServer.getStorage()
|
||||
storage.saveRoom(roomId, name, inviteCode, compression)
|
||||
|
||||
// Save agents to DB and auto-connect via Socket.IO
|
||||
const addedAgents = []
|
||||
for (const a of agents || []) {
|
||||
const agentId = generateId()
|
||||
const agent = storage.addRoomAgent(roomId, agentId, a.profile, a.name || a.profile, a.description || '', a.invited ? 1 : 0)
|
||||
addedAgents.push(agent)
|
||||
|
||||
try {
|
||||
const client = await chatServer.agentClients.createAgent({
|
||||
profile: agent.profile,
|
||||
name: agent.name,
|
||||
description: agent.description,
|
||||
invited: agent.invited,
|
||||
})
|
||||
await chatServer.agentClients.addAgentToRoom(roomId, client)
|
||||
} catch (err: any) {
|
||||
console.error(`[GroupChat] Failed to connect agent ${a.profile} to room ${roomId}: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const room = storage.getRoom(roomId)
|
||||
ctx.body = { room, agents: addedAgents }
|
||||
})
|
||||
|
||||
// Get room detail and messages
|
||||
groupChatRoutes.get('/api/hermes/group-chat/rooms/:roomId', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const room = chatServer.getStorage().getRoom(ctx.params.roomId)
|
||||
if (!room) {
|
||||
ctx.status = 404
|
||||
ctx.body = { error: 'Room not found' }
|
||||
return
|
||||
}
|
||||
|
||||
const messages = chatServer.getStorage().getMessages(ctx.params.roomId)
|
||||
const agents = chatServer.getStorage().getRoomAgents(ctx.params.roomId)
|
||||
const members = chatServer.getStorage().getRoomMembers(ctx.params.roomId)
|
||||
ctx.body = { room, messages, agents, members }
|
||||
})
|
||||
|
||||
// List rooms
|
||||
groupChatRoutes.get('/api/hermes/group-chat/rooms', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const rooms = chatServer.getStorage().getAllRooms()
|
||||
ctx.body = { rooms }
|
||||
})
|
||||
|
||||
// Get room by invite code
|
||||
groupChatRoutes.get('/api/hermes/group-chat/rooms/join/:code', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const room = chatServer.getStorage().getRoomByInviteCode(ctx.params.code)
|
||||
if (!room) {
|
||||
ctx.status = 404
|
||||
ctx.body = { error: 'Room not found' }
|
||||
return
|
||||
}
|
||||
|
||||
ctx.body = { room }
|
||||
})
|
||||
|
||||
// Update room invite code
|
||||
groupChatRoutes.put('/api/hermes/group-chat/rooms/:roomId/invite-code', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const { inviteCode } = ctx.request.body as { inviteCode?: string }
|
||||
if (!inviteCode) {
|
||||
ctx.status = 400
|
||||
ctx.body = { error: 'inviteCode is required' }
|
||||
return
|
||||
}
|
||||
|
||||
chatServer.getStorage().updateRoomInviteCode(ctx.params.roomId, inviteCode)
|
||||
ctx.body = { success: true }
|
||||
})
|
||||
|
||||
// Add agent to room
|
||||
groupChatRoutes.post('/api/hermes/group-chat/rooms/:roomId/agents', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const { profile, name, description, invited } = ctx.request.body as { profile?: string; name?: string; description?: string; invited?: boolean }
|
||||
if (!profile) {
|
||||
ctx.status = 400
|
||||
ctx.body = { error: 'profile is required' }
|
||||
return
|
||||
}
|
||||
|
||||
// Prevent duplicate agent in same room
|
||||
const existing = chatServer.getStorage().getRoomAgents(ctx.params.roomId)
|
||||
if (existing.find(a => a.profile === profile)) {
|
||||
ctx.status = 409
|
||||
ctx.body = { error: 'Agent already in room' }
|
||||
return
|
||||
}
|
||||
|
||||
const agentId = generateId()
|
||||
const agent = chatServer.getStorage().addRoomAgent(ctx.params.roomId, agentId, profile, name || profile, description || '', invited ? 1 : 0)
|
||||
|
||||
// Auto-connect agent via Socket.IO
|
||||
try {
|
||||
const client = await chatServer.agentClients.createAgent({
|
||||
profile: agent.profile,
|
||||
name: agent.name,
|
||||
description: agent.description,
|
||||
invited: agent.invited,
|
||||
})
|
||||
await chatServer.agentClients.addAgentToRoom(ctx.params.roomId, client)
|
||||
} catch (err: any) {
|
||||
console.error(`[GroupChat] Failed to connect agent ${profile} to room ${ctx.params.roomId}: ${err.message}`)
|
||||
}
|
||||
|
||||
ctx.body = { agent }
|
||||
})
|
||||
|
||||
// List agents in room
|
||||
groupChatRoutes.get('/api/hermes/group-chat/rooms/:roomId/agents', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const agents = chatServer.getStorage().getRoomAgents(ctx.params.roomId)
|
||||
ctx.body = { agents }
|
||||
})
|
||||
|
||||
// Remove agent from room
|
||||
groupChatRoutes.delete('/api/hermes/group-chat/rooms/:roomId/agents/:agentId', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
chatServer.getStorage().removeRoomAgent(ctx.params.agentId)
|
||||
chatServer.agentClients.removeAgentFromRoom(ctx.params.roomId, ctx.params.agentId)
|
||||
ctx.body = { success: true }
|
||||
})
|
||||
|
||||
// Delete room
|
||||
groupChatRoutes.delete('/api/hermes/group-chat/rooms/:roomId', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const roomId = ctx.params.roomId
|
||||
// Disconnect all agents in room
|
||||
chatServer.agentClients.disconnectRoom(roomId)
|
||||
// Delete all data
|
||||
chatServer.getStorage().deleteRoom(roomId)
|
||||
ctx.body = { success: true }
|
||||
})
|
||||
|
||||
// Update room compression config
|
||||
groupChatRoutes.put('/api/hermes/group-chat/rooms/:roomId/config', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const roomId = ctx.params.roomId
|
||||
const { triggerTokens, maxHistoryTokens, tailMessageCount } = ctx.request.body as {
|
||||
triggerTokens?: number
|
||||
maxHistoryTokens?: number
|
||||
tailMessageCount?: number
|
||||
}
|
||||
|
||||
chatServer.getStorage().updateRoomConfig(roomId, { triggerTokens, maxHistoryTokens, tailMessageCount })
|
||||
const room = chatServer.getStorage().getRoom(roomId)
|
||||
ctx.body = { room }
|
||||
})
|
||||
|
||||
// Force compress a room's context
|
||||
groupChatRoutes.post('/api/hermes/group-chat/rooms/:roomId/compress', async (ctx) => {
|
||||
if (!chatServer) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Group chat not initialized' }
|
||||
return
|
||||
}
|
||||
|
||||
const roomId = ctx.params.roomId
|
||||
if (!chatServer.getStorage().getRoom(roomId)) {
|
||||
ctx.status = 404
|
||||
ctx.body = { error: 'Room not found' }
|
||||
return
|
||||
}
|
||||
|
||||
const engine = chatServer.getContextEngine()
|
||||
if (!engine) {
|
||||
ctx.status = 503
|
||||
ctx.body = { error: 'Context engine not available' }
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await engine.forceCompress(roomId)
|
||||
ctx.body = { success: true, summary: result }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
ctx.body = { error: err.message }
|
||||
}
|
||||
})
|
||||
@@ -122,7 +122,6 @@ export function setupTerminalWebSocket(httpServer: HttpServer) {
|
||||
httpServer.on('upgrade', async (req, socket, head) => {
|
||||
const url = new URL(req.url || '', `http://${req.headers.host}`)
|
||||
if (url.pathname !== '/api/hermes/terminal') {
|
||||
socket.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileRoutes } from './hermes/files'
|
||||
import { downloadRoutes } from './hermes/download'
|
||||
import { jobRoutes } from './hermes/jobs'
|
||||
import { proxyRoutes, proxyMiddleware } from './hermes/proxy'
|
||||
import { groupChatRoutes, setGroupChatServer } from './hermes/group-chat'
|
||||
|
||||
/**
|
||||
* Register all routes on the Koa app.
|
||||
@@ -55,6 +56,7 @@ export function registerRoutes(app: any, requireAuth: (ctx: Context, next: Next)
|
||||
app.use(nousAuthRoutes.routes())
|
||||
app.use(gatewayRoutes.routes())
|
||||
app.use(weixinRoutes.routes())
|
||||
app.use(groupChatRoutes.routes()) // Must be before proxy
|
||||
app.use(fileRoutes.routes()) // Must be before proxy (proxy catch-all matches everything)
|
||||
app.use(downloadRoutes.routes()) // Must be before proxy
|
||||
app.use(jobRoutes.routes()) // Must be before proxy
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
import type {
|
||||
StoredMessage,
|
||||
CompressionConfig,
|
||||
CompressedContext,
|
||||
BuildContextInput,
|
||||
MessageFetcher,
|
||||
GatewayCaller,
|
||||
SessionCleaner,
|
||||
} from './types'
|
||||
import { DEFAULT_COMPRESSION_CONFIG } from './types'
|
||||
import { GatewaySummarizer } from './gateway-client'
|
||||
import { buildAgentInstructions, buildSummarizationSystemPrompt } from './prompt'
|
||||
|
||||
export class ContextEngine {
|
||||
private config: CompressionConfig
|
||||
private messageFetcher: MessageFetcher
|
||||
private gatewayCaller: GatewayCaller
|
||||
/** Per-room compression lock to prevent concurrent snapshot overwrites */
|
||||
private _compressLocks = new Map<string, Promise<void>>()
|
||||
private _upstream = ''
|
||||
private _apiKey: string | null = null
|
||||
|
||||
constructor(opts: {
|
||||
config?: Partial<CompressionConfig>
|
||||
messageFetcher: MessageFetcher
|
||||
gatewayCaller?: GatewayCaller
|
||||
sessionCleaner?: SessionCleaner
|
||||
}) {
|
||||
this.config = { ...DEFAULT_COMPRESSION_CONFIG, ...opts.config }
|
||||
this.messageFetcher = opts.messageFetcher
|
||||
this.gatewayCaller = opts.gatewayCaller || new GatewaySummarizer(this.config.summarizationTimeoutMs)
|
||||
this.sessionCleaner = opts.sessionCleaner
|
||||
}
|
||||
|
||||
private sessionCleaner?: SessionCleaner
|
||||
|
||||
setUpstream(upstream: string, apiKey: string | null): void {
|
||||
this._upstream = upstream
|
||||
this._apiKey = apiKey
|
||||
}
|
||||
|
||||
/**
|
||||
* Build context for an agent reply.
|
||||
*
|
||||
* Flow:
|
||||
* 1. Read persisted snapshot (summary + lastMessageId) from SQLite
|
||||
* 2. If snapshot exists:
|
||||
* a. Collect new messages after lastMessageId
|
||||
* b. Estimate tokens = summary + new messages
|
||||
* c. Under threshold → return as-is
|
||||
* d. Over threshold → incremental compress, update snapshot, return
|
||||
* 3. If no snapshot:
|
||||
* a. Estimate tokens for all messages
|
||||
* b. Under threshold → return all verbatim
|
||||
* c. Over threshold → full compress, save snapshot, return
|
||||
*/
|
||||
async buildContext(input: BuildContextInput): Promise<CompressedContext> {
|
||||
// Serialize compression per room to prevent concurrent snapshot overwrites
|
||||
const existing = this._compressLocks.get(input.roomId)
|
||||
if (existing) {
|
||||
await existing
|
||||
}
|
||||
let resolveLock!: () => void
|
||||
const lock = new Promise<void>(r => { resolveLock = r })
|
||||
this._compressLocks.set(input.roomId, lock)
|
||||
try {
|
||||
return await this._buildContextImpl(input)
|
||||
} finally {
|
||||
resolveLock()
|
||||
this._compressLocks.delete(input.roomId)
|
||||
}
|
||||
}
|
||||
|
||||
private async _buildContextImpl(input: BuildContextInput): Promise<CompressedContext> {
|
||||
const config = { ...this.config, ...input.compression }
|
||||
const allMessages = this.messageFetcher.getMessages(input.roomId)
|
||||
// Filter out messages newer than the current one
|
||||
const messages = allMessages.filter(m => m.timestamp <= input.currentMessage.timestamp)
|
||||
const total = messages.length
|
||||
|
||||
console.log(`[ContextEngine] buildContext START — room=${input.roomId}, agent=${input.agentName}, totalMessagesInDb=${allMessages.length}, afterFilter=${total}`)
|
||||
|
||||
const instructions = buildAgentInstructions({
|
||||
agentName: input.agentName,
|
||||
roomName: input.roomName,
|
||||
agentDescription: input.agentDescription,
|
||||
memberNames: input.memberNames,
|
||||
members: input.members,
|
||||
})
|
||||
|
||||
const meta: CompressedContext['meta'] = {
|
||||
totalMessages: total,
|
||||
verbatimCount: 0,
|
||||
hadSnapshot: false,
|
||||
compressed: false,
|
||||
summaryTokenEstimate: 0,
|
||||
}
|
||||
|
||||
const snapshot = this.messageFetcher.getContextSnapshot(input.roomId)
|
||||
console.log(`[ContextEngine] snapshot=${snapshot ? `EXISTS (lastMsgId=${snapshot.lastMessageId}, summaryLen=${snapshot.summary.length})` : 'NONE'}`)
|
||||
|
||||
// ── Path A: Snapshot exists — incremental ────────────
|
||||
if (snapshot) {
|
||||
meta.hadSnapshot = true
|
||||
|
||||
// Find the position of lastMessageId in messages
|
||||
const snapshotIdx = messages.findIndex(m => m.id === snapshot.lastMessageId)
|
||||
// Collect messages after the snapshot position
|
||||
const newMessages = snapshotIdx >= 0
|
||||
? messages.slice(snapshotIdx + 1)
|
||||
: messages.filter(m => m.timestamp > snapshot.lastMessageTimestamp)
|
||||
|
||||
const summaryTokens = this.countTokens(snapshot.summary)
|
||||
const newTokens = this.estimateTokensFromMessages(newMessages)
|
||||
const totalTokens = summaryTokens + newTokens
|
||||
|
||||
meta.verbatimCount = newMessages.length
|
||||
meta.summaryTokenEstimate = summaryTokens
|
||||
|
||||
console.log(`[ContextEngine] [Path A] snapshotIdx=${snapshotIdx}, newMessages=${newMessages.length}, summaryTokens=~${summaryTokens}, newTokens=~${newTokens}, totalTokens=~${totalTokens}, threshold=${config.triggerTokens}`)
|
||||
console.log(`[ContextEngine] [Path A] EXISTING SUMMARY (${snapshot.summary.length} chars):`, snapshot.summary.slice(0, 300))
|
||||
if (newMessages.length > 0) {
|
||||
console.log(`[ContextEngine] [Path A] NEW MESSAGES (${newMessages.length}):`, newMessages.map(m => `[${m.senderName}]: ${m.content.slice(0, 80)}`).join(' | '))
|
||||
}
|
||||
|
||||
// Under threshold — return summary + new messages directly
|
||||
if (totalTokens <= config.triggerTokens) {
|
||||
console.log(`[ContextEngine] [Path A] UNDER threshold — return summary + ${newMessages.length} verbatim msgs directly`)
|
||||
const history = this.buildHistory(snapshot.summary, newMessages, input.agentSocketId)
|
||||
this.logHistory('Path A (no compress)', history)
|
||||
return { conversationHistory: history, instructions, meta }
|
||||
}
|
||||
|
||||
// Over threshold — incremental compress
|
||||
console.log(`[ContextEngine] [Path A] OVER threshold — starting INCREMENTAL compression of ${newMessages.length} msgs...`)
|
||||
console.log(`[ContextEngine] [Path A] CONTEXT BEFORE COMPRESSION: summary(${snapshot.summary.length} chars) + ${newMessages.length} new msgs`)
|
||||
meta.compressed = true
|
||||
|
||||
const t0 = Date.now()
|
||||
const result = await this.summarize(
|
||||
input.roomId,
|
||||
newMessages,
|
||||
input.upstream,
|
||||
input.apiKey,
|
||||
snapshot.summary,
|
||||
)
|
||||
const elapsed = Date.now() - t0
|
||||
|
||||
if (result.summary) {
|
||||
const lastMsg = newMessages[newMessages.length - 1]
|
||||
this.messageFetcher.saveContextSnapshot(input.roomId, result.summary, lastMsg.id, lastMsg.timestamp)
|
||||
|
||||
meta.summaryTokenEstimate = this.countTokens(result.summary)
|
||||
console.log(`[ContextEngine] [Path A] incremental compression DONE in ${elapsed}ms, newSummaryLen=${result.summary.length}, newLastMsgId=${lastMsg.id}`)
|
||||
console.log(`[ContextEngine] [Path A] NEW SUMMARY (${result.summary.length} chars):`, result.summary.slice(0, 300))
|
||||
const history = this.buildHistory(result.summary, newMessages, input.agentSocketId)
|
||||
this.logHistory('Path A (after incremental compress)', history)
|
||||
if (result.sessionId) this.sessionCleaner?.(result.sessionId)
|
||||
return { conversationHistory: history, instructions, meta }
|
||||
}
|
||||
|
||||
// Compression failed — degrade
|
||||
console.warn(`[ContextEngine] [Path A] incremental compression FAILED (${elapsed}ms) — degrading to summary + trimmed verbatim`)
|
||||
const history = this.buildHistory(snapshot.summary, newMessages, input.agentSocketId)
|
||||
this.trimToBudget(history, summaryTokens, config.maxHistoryTokens)
|
||||
return { conversationHistory: history, instructions, meta }
|
||||
}
|
||||
|
||||
// ── Path B: No snapshot — full context ───────────────
|
||||
const totalTokens = this.estimateTokensFromMessages(messages)
|
||||
meta.verbatimCount = total
|
||||
|
||||
console.log(`[ContextEngine] [Path B] no snapshot, totalMessages=${total}, totalTokens=~${totalTokens}, threshold=${config.triggerTokens}`)
|
||||
|
||||
// Under threshold — pass all messages verbatim
|
||||
if (totalTokens <= config.triggerTokens) {
|
||||
console.log(`[ContextEngine] [Path B] UNDER threshold — return all ${total} msgs verbatim`)
|
||||
const history = messages.map(m => this.mapToHistory(m, input.agentSocketId))
|
||||
this.logHistory('Path B (no compress)', history)
|
||||
return { conversationHistory: history, instructions, meta }
|
||||
}
|
||||
|
||||
// Over threshold — full compress
|
||||
console.log(`[ContextEngine] [Path B] OVER threshold — starting FULL compression of ${total} msgs...`)
|
||||
console.log(`[ContextEngine] [Path B] CONTEXT BEFORE COMPRESSION: ${total} msgs, ~${totalTokens} tokens`)
|
||||
meta.compressed = true
|
||||
|
||||
const t0 = Date.now()
|
||||
const result = await this.summarize(
|
||||
input.roomId,
|
||||
messages,
|
||||
input.upstream,
|
||||
input.apiKey,
|
||||
)
|
||||
const elapsed = Date.now() - t0
|
||||
|
||||
if (result.summary) {
|
||||
// Keep recent tail messages verbatim, compress the rest
|
||||
const { tailMessageCount } = config
|
||||
const toCompress = messages.length > tailMessageCount ? messages.slice(0, -tailMessageCount) : messages
|
||||
const tail = messages.length > tailMessageCount ? messages.slice(-tailMessageCount) : []
|
||||
const lastCompressedMsg = toCompress[toCompress.length - 1]
|
||||
|
||||
this.messageFetcher.saveContextSnapshot(input.roomId, result.summary, lastCompressedMsg.id, lastCompressedMsg.timestamp)
|
||||
|
||||
meta.summaryTokenEstimate = this.countTokens(result.summary)
|
||||
console.log(`[ContextEngine] [Path B] full compression DONE in ${elapsed}ms, summaryLen=${result.summary.length}, compressed=${toCompress.length} msgs, keptTail=${tail.length} msgs, savedLastMsgId=${lastCompressedMsg.id}`)
|
||||
console.log(`[ContextEngine] [Path B] COMPRESSED SUMMARY (${result.summary.length} chars):`, result.summary.slice(0, 300))
|
||||
const history = this.buildHistory(result.summary, tail, input.agentSocketId)
|
||||
this.logHistory('Path B (after full compress)', history)
|
||||
if (result.sessionId) this.sessionCleaner?.(result.sessionId)
|
||||
return { conversationHistory: history, instructions, meta }
|
||||
}
|
||||
|
||||
// Compression failed — degrade
|
||||
console.warn(`[ContextEngine] [Path B] full compression FAILED (${elapsed}ms) — degrading to trimmed verbatim`)
|
||||
const history = messages.map(m => this.mapToHistory(m, input.agentSocketId))
|
||||
this.trimToBudget(history, 0, config.maxHistoryTokens)
|
||||
meta.verbatimCount = history.length
|
||||
return { conversationHistory: history, instructions, meta }
|
||||
}
|
||||
|
||||
invalidateRoom(roomId: string): void {
|
||||
this.messageFetcher.deleteContextSnapshot(roomId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Force compress all messages in a room (full compression).
|
||||
* Used when user manually triggers compression.
|
||||
*/
|
||||
async forceCompress(roomId: string): Promise<string> {
|
||||
const allMessages = this.messageFetcher.getMessages(roomId)
|
||||
if (allMessages.length === 0) return ''
|
||||
|
||||
const config = { ...this.config }
|
||||
console.log(`[ContextEngine] forceCompress room=${roomId}, messages=${allMessages.length}`)
|
||||
|
||||
const t0 = Date.now()
|
||||
const result = await this.summarize(roomId, allMessages, this._upstream, this._apiKey)
|
||||
const elapsed = Date.now() - t0
|
||||
|
||||
if (result.summary) {
|
||||
const { tailMessageCount } = config
|
||||
const toCompress = allMessages.length > tailMessageCount ? allMessages.slice(0, -tailMessageCount) : allMessages
|
||||
const tail = allMessages.length > tailMessageCount ? allMessages.slice(-tailMessageCount) : []
|
||||
const lastCompressedMsg = toCompress[toCompress.length - 1]
|
||||
|
||||
this.messageFetcher.saveContextSnapshot(roomId, result.summary, lastCompressedMsg.id, lastCompressedMsg.timestamp)
|
||||
console.log(`[ContextEngine] forceCompress DONE in ${elapsed}ms`)
|
||||
if (result.sessionId) this.sessionCleaner?.(result.sessionId)
|
||||
return result.summary
|
||||
}
|
||||
|
||||
throw new Error('Compression failed')
|
||||
}
|
||||
|
||||
// ─── Private ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Build history array: optional summary prefix + verbatim messages.
|
||||
*/
|
||||
private buildHistory(
|
||||
summary: string,
|
||||
messages: StoredMessage[],
|
||||
agentSocketId: string,
|
||||
): Array<{ role: 'user' | 'assistant'; content: string }> {
|
||||
const history: Array<{ role: 'user' | 'assistant'; content: string }> = []
|
||||
|
||||
if (summary) {
|
||||
history.push(
|
||||
{ role: 'user', content: '[Previous conversation summary]\n' + summary },
|
||||
{ role: 'assistant', content: 'I have reviewed the conversation history and understand the context.' },
|
||||
)
|
||||
}
|
||||
|
||||
history.push(...messages.map(m => this.mapToHistory(m, agentSocketId)))
|
||||
return history
|
||||
}
|
||||
|
||||
/**
|
||||
* Summarize messages. If previousSummary is provided, do incremental update.
|
||||
*/
|
||||
private async summarize(
|
||||
roomId: string,
|
||||
messages: StoredMessage[],
|
||||
upstream: string,
|
||||
apiKey: string | null,
|
||||
previousSummary?: string,
|
||||
): Promise<{ summary: string | null; sessionId: string | null }> {
|
||||
if (messages.length === 0 && !previousSummary) return { summary: null, sessionId: null }
|
||||
|
||||
try {
|
||||
const result = await this.gatewayCaller.summarize(
|
||||
upstream,
|
||||
apiKey,
|
||||
buildSummarizationSystemPrompt(),
|
||||
messages,
|
||||
previousSummary,
|
||||
)
|
||||
return { summary: result.summary, sessionId: result.sessionId }
|
||||
} catch (err: any) {
|
||||
console.warn(`[ContextEngine] Summarization failed for room ${roomId}: ${err.message}`)
|
||||
return { summary: null, sessionId: null }
|
||||
} finally {
|
||||
// Session cleanup handled here if sessionCleaner is provided
|
||||
}
|
||||
}
|
||||
|
||||
private mapToHistory(
|
||||
msg: StoredMessage,
|
||||
agentSocketId: string,
|
||||
): { role: 'user' | 'assistant'; content: string } {
|
||||
if (msg.senderId === agentSocketId) {
|
||||
return { role: 'assistant', content: msg.content }
|
||||
}
|
||||
return { role: 'user', content: `[${msg.senderName}]: ${msg.content}` }
|
||||
}
|
||||
|
||||
private trimToBudget(
|
||||
history: Array<{ role: 'user' | 'assistant'; content: string }>,
|
||||
summaryTokens: number,
|
||||
maxTokens: number,
|
||||
): void {
|
||||
let totalTokens = summaryTokens + this.estimateTokens(history)
|
||||
while (totalTokens > maxTokens && history.length > 0) {
|
||||
history.pop()
|
||||
totalTokens = summaryTokens + this.estimateTokens(history)
|
||||
}
|
||||
}
|
||||
|
||||
private estimateTokens(history: Array<{ role: string; content: string }>): number {
|
||||
const text = history.map(m => m.content).join('')
|
||||
return this.countTokens(text)
|
||||
}
|
||||
|
||||
private estimateTokensFromMessages(messages: StoredMessage[]): number {
|
||||
const text = messages.map(m => m.content + m.senderName).join('')
|
||||
return this.countTokens(text)
|
||||
}
|
||||
|
||||
/** Estimate tokens distinguishing CJK (~1.5 tok/char) from Latin (~0.25 tok/char) */
|
||||
private countTokens(text: string): number {
|
||||
const cjk = (text.match(/[\u2e80-\u9fff\uac00-\ud7af\u3000-\u303f\uff00-\uffef]/g) || []).length
|
||||
const other = text.length - cjk
|
||||
return Math.ceil(cjk * 1.5 + other / 4)
|
||||
}
|
||||
|
||||
/** Log assembled history for debugging */
|
||||
private logHistory(label: string, history: Array<{ role: string; content: string }>): void {
|
||||
const totalTokens = this.estimateTokens(history)
|
||||
console.log(`[ContextEngine] ASSEMBLED HISTORY (${label}): ${history.length} entries, ~${totalTokens} tokens`)
|
||||
for (const entry of history) {
|
||||
const preview = entry.content.length > 150 ? entry.content.slice(0, 150) + '...' : entry.content
|
||||
console.log(` [${entry.role}] ${preview}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { EventSource } from 'eventsource'
|
||||
import type { StoredMessage, GatewayCaller } from './types'
|
||||
import {
|
||||
buildSummarizationSystemPrompt,
|
||||
buildFullSummaryPrompt,
|
||||
buildIncrementalUpdatePrompt,
|
||||
} from './prompt'
|
||||
|
||||
/**
|
||||
* Calls Hermes /v1/runs to produce LLM-generated summaries.
|
||||
* Uses non-streaming EventSource to wait for run.completed.
|
||||
*/
|
||||
export class GatewaySummarizer implements GatewayCaller {
|
||||
private timeoutMs: number
|
||||
|
||||
constructor(timeoutMs = 30_000) {
|
||||
this.timeoutMs = timeoutMs
|
||||
}
|
||||
|
||||
async summarize(
|
||||
upstream: string,
|
||||
apiKey: string | null,
|
||||
systemPrompt: string,
|
||||
messages: StoredMessage[],
|
||||
previousSummary?: string,
|
||||
): Promise<{ summary: string; sessionId: string }> {
|
||||
// Build conversation_history from messages
|
||||
const history: Array<{ role: string; content: string }> = messages.map(m => ({
|
||||
role: 'user',
|
||||
content: `[${m.senderName}]: ${m.content}`,
|
||||
}))
|
||||
|
||||
// Inject previous summary for incremental update
|
||||
if (previousSummary) {
|
||||
history.unshift(
|
||||
{ role: 'user', content: `[Previous summary]\n${previousSummary}` },
|
||||
{ role: 'assistant', content: 'Understood, I will update the summary.' },
|
||||
)
|
||||
}
|
||||
|
||||
const userPrompt = previousSummary
|
||||
? buildIncrementalUpdatePrompt()
|
||||
: buildFullSummaryPrompt()
|
||||
|
||||
const sessionId = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
|
||||
// POST /v1/runs
|
||||
const res = await fetch(`${upstream}/v1/runs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
input: userPrompt,
|
||||
instructions: systemPrompt || buildSummarizationSystemPrompt(),
|
||||
conversation_history: history,
|
||||
session_id: sessionId,
|
||||
}),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Summarization run failed: ${res.status}`)
|
||||
}
|
||||
|
||||
const { run_id } = await res.json() as { run_id: string }
|
||||
|
||||
try {
|
||||
const output = await this.pollForResult(upstream, apiKey, run_id)
|
||||
return { summary: output, sessionId }
|
||||
} finally {
|
||||
// Note: session cleanup is handled by the caller (compressor.ts)
|
||||
}
|
||||
}
|
||||
|
||||
private pollForResult(upstream: string, apiKey: string | null, runId: string): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
source.close()
|
||||
reject(new Error('Summarization timed out'))
|
||||
}, this.timeoutMs)
|
||||
|
||||
const eventsUrl = new URL(`${upstream}/v1/runs/${runId}/events`)
|
||||
if (apiKey) eventsUrl.searchParams.set('token', apiKey)
|
||||
|
||||
const source = new EventSource(eventsUrl.toString())
|
||||
|
||||
source.onmessage = (event: MessageEvent) => {
|
||||
try {
|
||||
const parsed = JSON.parse(event.data)
|
||||
if (parsed.event === 'run.completed') {
|
||||
clearTimeout(timer)
|
||||
source.close()
|
||||
const output = parsed.output
|
||||
if (!output || typeof output !== 'string' || output.trim() === '') {
|
||||
reject(new Error('Empty summarization response'))
|
||||
return
|
||||
}
|
||||
resolve(output.trim())
|
||||
} else if (parsed.event === 'run.failed') {
|
||||
clearTimeout(timer)
|
||||
source.close()
|
||||
reject(new Error(parsed.error || 'Summarization run failed'))
|
||||
}
|
||||
} catch { /* ignore parse errors for non-JSON events */ }
|
||||
}
|
||||
|
||||
source.onerror = () => {
|
||||
clearTimeout(timer)
|
||||
source.close()
|
||||
reject(new Error('Summarization SSE connection error'))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export { ContextEngine } from './compressor'
|
||||
export { GatewaySummarizer } from './gateway-client'
|
||||
export { buildAgentInstructions, buildSummarizationSystemPrompt, buildFullSummaryPrompt, buildIncrementalUpdatePrompt } from './prompt'
|
||||
export { DEFAULT_COMPRESSION_CONFIG } from './types'
|
||||
export type {
|
||||
StoredMessage,
|
||||
CompressionConfig,
|
||||
CompressedContext,
|
||||
ContextSnapshot,
|
||||
MessageFetcher,
|
||||
GatewayCaller,
|
||||
BuildContextInput,
|
||||
} from './types'
|
||||
@@ -0,0 +1,82 @@
|
||||
// ─── Agent Identity Instructions ────────────────────────────
|
||||
|
||||
import type { MemberInfo } from './types'
|
||||
|
||||
interface AgentInstructionsParams {
|
||||
agentName: string
|
||||
roomName: string
|
||||
agentDescription: string
|
||||
memberNames: string[]
|
||||
members: MemberInfo[]
|
||||
}
|
||||
|
||||
export function buildAgentInstructions(params: AgentInstructionsParams): string {
|
||||
let memberSection: string
|
||||
if (params.members.length > 0) {
|
||||
memberSection = params.members
|
||||
.map(m => m.description ? `- ${m.name}: ${m.description}` : `- ${m.name}`)
|
||||
.join('\n')
|
||||
} else if (params.memberNames.length > 0) {
|
||||
memberSection = params.memberNames.map(n => `- ${n}`).join('\n')
|
||||
} else {
|
||||
memberSection = '- 未知'
|
||||
}
|
||||
|
||||
return `你是"${params.agentName}",群聊房间"${params.roomName}"中的 AI 助手。
|
||||
|
||||
你的角色:${params.agentDescription}
|
||||
|
||||
当前房间成员:
|
||||
${memberSection}
|
||||
|
||||
规则:
|
||||
- 有人用 @${params.agentName} 提及你时才需要回复,重点回应提及你的人。
|
||||
- 回答简洁、对群聊有帮助。
|
||||
- 不要假装是人类,需要时明确表明自己是 AI。
|
||||
- 对话历史中包含多个人的消息,每条消息前标有发送者名字。
|
||||
- 对话开头可能包含之前的对话摘要,用于提供更早的上下文。
|
||||
- 回复最新一条提及你的消息。
|
||||
- 如果需要其他 agent 协作或明确回复某个人,使用 @名字 来提及对方。
|
||||
- 自行判断对话是否已经结束——如果问题已解决、达成共识、或对方只是陈述不需要回复,则不要再 @任何人,直接结束回复,避免产生无意义的循环对话。`
|
||||
}
|
||||
|
||||
// ─── Summarization Prompts ─────────────────────────────────
|
||||
|
||||
export function buildSummarizationSystemPrompt(): string {
|
||||
return `你是一个群聊对话的摘要助手。请创建一份结构化摘要,帮助 AI 助手快速理解完整的对话上下文并智能回复。
|
||||
|
||||
使用以下格式:
|
||||
|
||||
当前话题:
|
||||
- 现在在聊什么,目标是什么
|
||||
|
||||
已知结论:
|
||||
- 已达成哪些共识,哪些问题已经回答过
|
||||
|
||||
待回复消息:
|
||||
- 还剩谁的问题没回,下一步要做什么
|
||||
|
||||
关键人物:
|
||||
- 人名、角色、引用关系
|
||||
|
||||
重要上下文:
|
||||
- 不要丢时间线和立场变化
|
||||
- 少写废话,多保留"可行动信息"
|
||||
- 重点保留:谁说了什么、结论是什么、下一步是什么
|
||||
- 关键的 URL、代码片段、错误信息、约束条件
|
||||
|
||||
规则:
|
||||
- 基于事实,不要编造信息。
|
||||
- 保持简洁(500 字以内)。
|
||||
- 聚焦于帮助 AI 回复下一条消息的可行动信息。
|
||||
- 使用与对话相同的语言。
|
||||
- 不要回复对话内容,只输出摘要。`
|
||||
}
|
||||
|
||||
export function buildFullSummaryPrompt(): string {
|
||||
return '请对上方对话创建一份简洁的摘要。只输出摘要内容。'
|
||||
}
|
||||
|
||||
export function buildIncrementalUpdatePrompt(): string {
|
||||
return '对话自上次摘要后有了新的内容。请更新摘要,整合新消息。保持相同格式,更新所有部分。只输出更新后的摘要。'
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { SummaryCacheEntry } from './types'
|
||||
|
||||
const MAX_ENTRIES = 200
|
||||
|
||||
export class SummaryCache {
|
||||
private cache = new Map<string, SummaryCacheEntry>()
|
||||
private ttlMs: number
|
||||
|
||||
constructor(ttlMs = 120_000) {
|
||||
this.ttlMs = ttlMs
|
||||
}
|
||||
|
||||
get(roomId: string): SummaryCacheEntry | undefined {
|
||||
const entry = this.cache.get(roomId)
|
||||
if (!entry) return undefined
|
||||
if (Date.now() - entry.createdAt >= this.ttlMs) {
|
||||
this.cache.delete(roomId)
|
||||
return undefined
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
set(roomId: string, entry: SummaryCacheEntry): void {
|
||||
if (this.cache.size >= MAX_ENTRIES) {
|
||||
let oldestKey = ''
|
||||
let oldestTime = Infinity
|
||||
for (const [k, v] of this.cache) {
|
||||
if (v.createdAt < oldestTime) {
|
||||
oldestTime = v.createdAt
|
||||
oldestKey = k
|
||||
}
|
||||
}
|
||||
if (oldestKey) this.cache.delete(oldestKey)
|
||||
}
|
||||
this.cache.set(roomId, entry)
|
||||
}
|
||||
|
||||
invalidate(roomId: string): void {
|
||||
this.cache.delete(roomId)
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cache.clear()
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.cache.size
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// ─── Message Types ──────────────────────────────────────────
|
||||
|
||||
/** Raw message from SQLite messages table */
|
||||
export interface StoredMessage {
|
||||
id: string
|
||||
roomId: string
|
||||
senderId: string
|
||||
senderName: string
|
||||
content: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
// ─── Compression Config ────────────────────────────────────
|
||||
|
||||
export interface CompressionConfig {
|
||||
/** Token threshold to trigger compression (estimate all messages) */
|
||||
triggerTokens: number
|
||||
/** Max tokens for the final compressed context sent to LLM */
|
||||
maxHistoryTokens: number
|
||||
/** Number of recent messages to keep verbatim after compression */
|
||||
tailMessageCount: number
|
||||
/** Characters per token for estimation */
|
||||
charsPerToken: number
|
||||
/** Timeout for summarization LLM call in ms */
|
||||
summarizationTimeoutMs: number
|
||||
}
|
||||
|
||||
export const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {
|
||||
triggerTokens: 100_000,
|
||||
maxHistoryTokens: 32_000,
|
||||
tailMessageCount: 20,
|
||||
charsPerToken: 4,
|
||||
summarizationTimeoutMs: 30_000,
|
||||
}
|
||||
|
||||
// ─── Compression Output ────────────────────────────────────
|
||||
|
||||
export interface CompressedContext {
|
||||
conversationHistory: Array<{ role: 'user' | 'assistant'; content: string }>
|
||||
instructions: string
|
||||
meta: {
|
||||
totalMessages: number
|
||||
verbatimCount: number
|
||||
hadSnapshot: boolean
|
||||
compressed: boolean
|
||||
summaryTokenEstimate: number
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Context Snapshot (persisted in SQLite) ────────────────
|
||||
|
||||
export interface ContextSnapshot {
|
||||
roomId: string
|
||||
summary: string
|
||||
lastMessageId: string
|
||||
lastMessageTimestamp: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
// ─── Summary Cache ──────────────────────────────────────────
|
||||
|
||||
export interface SummaryCacheEntry {
|
||||
summary: string
|
||||
lastMessageId: string
|
||||
lastMessageTimestamp: number
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
// ─── Dependency Injection ──────────────────────────────────
|
||||
|
||||
export interface MessageFetcher {
|
||||
getMessages(roomId: string, limit?: number): StoredMessage[]
|
||||
getContextSnapshot(roomId: string): ContextSnapshot | null
|
||||
saveContextSnapshot(roomId: string, summary: string, lastMessageId: string, lastMessageTimestamp: number): void
|
||||
deleteContextSnapshot(roomId: string): void
|
||||
}
|
||||
|
||||
export interface GatewayCaller {
|
||||
summarize(
|
||||
upstream: string,
|
||||
apiKey: string | null,
|
||||
systemPrompt: string,
|
||||
messages: StoredMessage[],
|
||||
previousSummary?: string,
|
||||
): Promise<{ summary: string; sessionId: string }>
|
||||
}
|
||||
|
||||
export type SessionCleaner = (sessionId: string) => void
|
||||
|
||||
// ─── Build Context Input ───────────────────────────────────
|
||||
|
||||
export interface MemberInfo {
|
||||
userId: string
|
||||
name: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface BuildContextInput {
|
||||
roomId: string
|
||||
agentId: string
|
||||
agentName: string
|
||||
agentDescription: string
|
||||
agentSocketId: string
|
||||
roomName: string
|
||||
memberNames: string[]
|
||||
members: MemberInfo[]
|
||||
upstream: string
|
||||
apiKey: string | null
|
||||
currentMessage: StoredMessage
|
||||
compression?: Partial<CompressionConfig>
|
||||
}
|
||||
@@ -0,0 +1,669 @@
|
||||
import { io, Socket } from 'socket.io-client'
|
||||
import { EventSource } from 'eventsource'
|
||||
import { getToken } from '../../../services/auth'
|
||||
import type { GatewayManager } from '../gateway-manager'
|
||||
import { deleteSession as hermesDeleteSession } from '../hermes-cli'
|
||||
import { getActiveProfileName } from '../hermes-profile'
|
||||
import { logger } from '../../../services/logger'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────
|
||||
|
||||
interface AgentConfig {
|
||||
profile: string
|
||||
name: string
|
||||
description: string
|
||||
invited: number
|
||||
}
|
||||
|
||||
interface MessageData {
|
||||
id: string
|
||||
roomId: string
|
||||
senderId: string
|
||||
senderName: string
|
||||
content: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
interface MemberData {
|
||||
id: string
|
||||
name: string
|
||||
joinedAt: number
|
||||
}
|
||||
|
||||
interface JoinResult {
|
||||
roomId: string
|
||||
roomName: string
|
||||
members: MemberData[]
|
||||
messages: MessageData[]
|
||||
rooms: string[]
|
||||
}
|
||||
|
||||
export interface AgentEventHandler {
|
||||
onMessage?: (data: { roomId: string; msg: MessageData }) => void
|
||||
onTyping?: (data: { roomId: string; userId: string; userName: string }) => void
|
||||
onStopTyping?: (data: { roomId: string; userId: string; userName: string }) => void
|
||||
onMemberJoined?: (data: { roomId: string; memberId: string; memberName: string; members: MemberData[] }) => void
|
||||
onMemberLeft?: (data: { roomId: string; memberId: string; memberName: string; members: MemberData[] }) => void
|
||||
}
|
||||
|
||||
// ─── Agent Client (single connection) ─────────────────────────
|
||||
|
||||
class AgentClient {
|
||||
readonly agentId: string
|
||||
readonly profile: string
|
||||
readonly name: string
|
||||
readonly description: string
|
||||
private socket: Socket | null = null
|
||||
private joinedRooms = new Set<string>()
|
||||
private handlers: AgentEventHandler
|
||||
private _reconnecting = false
|
||||
private gatewayManager: GatewayManager | null = null
|
||||
private contextEngine: any = null
|
||||
private storage: any = null
|
||||
|
||||
constructor(config: AgentConfig, handlers: AgentEventHandler = {}) {
|
||||
this.agentId = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
this.profile = config.profile
|
||||
this.name = config.name
|
||||
this.description = config.description
|
||||
this.handlers = handlers
|
||||
}
|
||||
|
||||
get connected(): boolean {
|
||||
return this.socket?.connected ?? false
|
||||
}
|
||||
|
||||
get id(): string | undefined {
|
||||
return this.socket?.id
|
||||
}
|
||||
|
||||
setGatewayManager(manager: GatewayManager): void {
|
||||
this.gatewayManager = manager
|
||||
}
|
||||
|
||||
setContextEngine(engine: any): void {
|
||||
this.contextEngine = engine
|
||||
}
|
||||
|
||||
setStorage(storage: any): void {
|
||||
this.storage = storage
|
||||
}
|
||||
|
||||
async connect(port = 8648): Promise<void> {
|
||||
const token = await getToken()
|
||||
|
||||
this.socket = io(`http://127.0.0.1:${port}/group-chat`, {
|
||||
auth: {
|
||||
token: token || undefined,
|
||||
name: this.name,
|
||||
},
|
||||
transports: ['websocket'],
|
||||
reconnection: true,
|
||||
reconnectionAttempts: Infinity,
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 30000,
|
||||
})
|
||||
|
||||
this.bindEvents()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error('Connection timeout')), 10000)
|
||||
|
||||
this.socket!.on('connect', () => {
|
||||
clearTimeout(timeout)
|
||||
logger.debug(`[AgentClient] ${this.name} connected, socket id: ${this.socket!.id}`)
|
||||
resolve()
|
||||
})
|
||||
|
||||
this.socket!.on('connect_error', (err) => {
|
||||
clearTimeout(timeout)
|
||||
logger.error(err, `[AgentClient] ${this.name} connect_error`)
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
if (this.socket) {
|
||||
this.socket.disconnect()
|
||||
this.socket = null
|
||||
this.joinedRooms.clear()
|
||||
}
|
||||
}
|
||||
|
||||
async joinRoom(roomId: string): Promise<JoinResult> {
|
||||
this.ensureConnected()
|
||||
return new Promise((resolve, reject) => {
|
||||
this.socket!.emit('join', { roomId }, (res: JoinResult | { error: string }) => {
|
||||
if ('error' in res) {
|
||||
reject(new Error(res.error))
|
||||
} else {
|
||||
this.joinedRooms.add(roomId)
|
||||
resolve(res)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
sendMessage(roomId: string, content: string): Promise<string> {
|
||||
this.ensureConnected()
|
||||
return new Promise((resolve, reject) => {
|
||||
this.socket!.emit('message', { roomId, content }, (res: { id?: string; error?: string }) => {
|
||||
if (res.error) {
|
||||
reject(new Error(res.error))
|
||||
} else {
|
||||
resolve(res.id!)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
startTyping(roomId: string): void {
|
||||
this.ensureConnected()
|
||||
this.socket!.emit('typing', { roomId })
|
||||
}
|
||||
|
||||
stopTyping(roomId: string): void {
|
||||
this.ensureConnected()
|
||||
this.socket!.emit('stop_typing', { roomId })
|
||||
}
|
||||
|
||||
emitContextStatus(roomId: string, status: 'compressing' | 'replying' | 'ready'): void {
|
||||
this.ensureConnected()
|
||||
this.socket!.emit('context_status', { roomId, agentName: this.name, status })
|
||||
}
|
||||
|
||||
getJoinedRooms(): string[] {
|
||||
return Array.from(this.joinedRooms)
|
||||
}
|
||||
|
||||
private ensureConnected(): void {
|
||||
if (!this.socket?.connected) {
|
||||
throw new Error(`Agent "${this.name}" is not connected`)
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteSession(sessionId: string): Promise<void> {
|
||||
try {
|
||||
const sessionProfile = this.storage?.getSessionProfile?.(sessionId)
|
||||
const currentProfile = getActiveProfileName()
|
||||
|
||||
if (sessionProfile && sessionProfile.profile_name !== currentProfile) {
|
||||
// Cross-profile: enqueue deferred delete, don't switch profile
|
||||
this.storage?.enqueuePendingSessionDelete?.(sessionId, sessionProfile.profile_name)
|
||||
logger.info(`[AgentClients] ${this.name}: cross-profile deferred delete session ${sessionId} (session=${sessionProfile.profile_name}, active=${currentProfile})`)
|
||||
return
|
||||
}
|
||||
|
||||
// Same profile or no mapping: delete directly
|
||||
const ok = await hermesDeleteSession(sessionId)
|
||||
if (ok) {
|
||||
this.storage?.deleteSessionProfile?.(sessionId)
|
||||
}
|
||||
logger.debug(`[AgentClients] ${this.name}: delete session ${sessionId} (profile=${this.profile}) → ${ok ? 'ok' : 'failed'}`)
|
||||
} catch (err: any) {
|
||||
logger.warn(`[AgentClients] ${this.name}: failed to delete session ${sessionId}: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Hermes Gateway Integration ────────────────────────────
|
||||
|
||||
/**
|
||||
* Handle an @mention from the server side.
|
||||
* Called by AgentClients.processMentions() — no socket round-trip needed.
|
||||
* onStatus is called to report context compression progress.
|
||||
*/
|
||||
async replyToMention(
|
||||
roomId: string,
|
||||
msg: { content: string; senderName: string; senderId: string; timestamp: number },
|
||||
onStatus?: (status: 'compressing' | 'replying' | 'ready') => void,
|
||||
): Promise<void> {
|
||||
logger.debug(`[AgentClients] ${this.name} mentioned by ${msg.senderName}: "${msg.content.slice(0, 50)}"`)
|
||||
if (!this.gatewayManager) {
|
||||
logger.debug(`[AgentClients] ${this.name}: gatewayManager is null, skipping`)
|
||||
return
|
||||
}
|
||||
|
||||
const upstream = this.gatewayManager.getUpstream(this.profile)
|
||||
const apiKey = this.gatewayManager.getApiKey(this.profile)
|
||||
logger.debug(`[AgentClients] ${this.name}: upstream=${upstream}, profile=${this.profile}`)
|
||||
if (!upstream) {
|
||||
logger.error(`[AgentClients] ${this.name}: no gateway upstream for profile "${this.profile}"`)
|
||||
return
|
||||
}
|
||||
|
||||
const sessionId = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
|
||||
try {
|
||||
// Notify room that agent is typing
|
||||
this.startTyping(roomId)
|
||||
|
||||
// Build compressed context if context engine is available
|
||||
let conversationHistory: Array<{ role: string; content: string }> = []
|
||||
let instructions: string | undefined
|
||||
|
||||
if (this.contextEngine && this.storage) {
|
||||
try {
|
||||
logger.debug(`[AgentClients] ${this.name}: building context...`)
|
||||
onStatus?.('compressing')
|
||||
// Get room members with descriptions for context
|
||||
const roomMembers: Array<{ userId: string; name: string; description: string }> = this.storage.getRoomMembers(roomId) || []
|
||||
const memberNames = roomMembers.map((m: any) => m.name)
|
||||
const members = roomMembers.map((m: any) => ({ userId: m.userId, name: m.name, description: m.description }))
|
||||
|
||||
// Get room compression config
|
||||
const roomInfo = this.storage.getRoom(roomId)
|
||||
const compression = roomInfo ? {
|
||||
triggerTokens: roomInfo.triggerTokens,
|
||||
maxHistoryTokens: roomInfo.maxHistoryTokens,
|
||||
tailMessageCount: roomInfo.tailMessageCount,
|
||||
} : undefined
|
||||
|
||||
const ctx = await this.contextEngine.buildContext({
|
||||
roomId,
|
||||
agentId: this.agentId,
|
||||
agentName: this.name,
|
||||
agentDescription: this.description,
|
||||
agentSocketId: this.socket?.id || '',
|
||||
roomName: roomId,
|
||||
memberNames,
|
||||
members,
|
||||
upstream,
|
||||
apiKey,
|
||||
currentMessage: msg,
|
||||
compression,
|
||||
})
|
||||
conversationHistory = ctx.conversationHistory
|
||||
instructions = ctx.instructions
|
||||
logger.debug(`[AgentClients] ${this.name}: context built — historyLen=${conversationHistory.length}, meta=%j`, ctx.meta)
|
||||
onStatus?.('replying')
|
||||
} catch (err: any) {
|
||||
logger.warn(`[AgentClients] ${this.name}: context engine failed: ${err.message}`)
|
||||
onStatus?.('replying')
|
||||
// Degrade: continue without context
|
||||
}
|
||||
}
|
||||
|
||||
// Strip @mention from input — agent already knows it was mentioned
|
||||
const input = msg.content.replace(new RegExp(`@${this.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*`, 'gi'), '').trim() || msg.content
|
||||
|
||||
// Start a run on Hermes gateway
|
||||
const runRes = await fetch(`${upstream}/v1/runs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
input,
|
||||
session_id: sessionId,
|
||||
...(conversationHistory.length > 0 ? { conversation_history: conversationHistory } : {}),
|
||||
...(instructions ? { instructions } : {}),
|
||||
}),
|
||||
signal: AbortSignal.timeout(120000),
|
||||
})
|
||||
|
||||
if (!runRes.ok) {
|
||||
const text = await runRes.text().catch(() => '')
|
||||
logger.error(`[AgentClients] ${this.name}: gateway run failed (${runRes.status}): ${text}`)
|
||||
this.stopTyping(roomId)
|
||||
return
|
||||
}
|
||||
|
||||
const runData = await runRes.json() as any
|
||||
const run_id = runData.run_id
|
||||
logger.debug(`[AgentClients] ${this.name}: run started, response=%j`, runData)
|
||||
if (!run_id) {
|
||||
logger.error(`[AgentClients] ${this.name}: no run_id in response`)
|
||||
this.stopTyping(roomId)
|
||||
return
|
||||
}
|
||||
|
||||
// Save session-to-profile mapping after gateway confirms the run
|
||||
const actualSessionId = runData.session_id || sessionId
|
||||
if (!this.storage) {
|
||||
logger.warn(`[AgentClients] ${this.name}: storage is null, cannot save session profile for ${actualSessionId}`)
|
||||
} else {
|
||||
this.storage.saveSessionProfile(actualSessionId, roomId, this.agentId, this.profile)
|
||||
logger.debug(`[AgentClients] ${this.name}: saved session profile ${actualSessionId} → profile=${this.profile}`)
|
||||
}
|
||||
|
||||
// Stream events from Hermes
|
||||
const eventsUrl = new URL(`${upstream}/v1/runs/${run_id}/events`)
|
||||
if (apiKey) eventsUrl.searchParams.set('token', apiKey)
|
||||
logger.debug(`[AgentClients] ${this.name}: streaming events from ${eventsUrl}`)
|
||||
const source = new EventSource(eventsUrl.toString())
|
||||
|
||||
let fullContent = ''
|
||||
|
||||
source.onmessage = (e: any) => {
|
||||
try {
|
||||
const parsed = JSON.parse(e.data)
|
||||
logger.debug(`[AgentClients] ${this.name}: event=${parsed.event}`)
|
||||
|
||||
if (parsed.event === 'run.completed') {
|
||||
source.close()
|
||||
logger.debug(`[AgentClients] ${this.name}: run completed, content length=${fullContent.length}`)
|
||||
if (fullContent) {
|
||||
this.stopTyping(roomId)
|
||||
this.sendMessage(roomId, fullContent)
|
||||
}
|
||||
this.deleteSession(actualSessionId).catch(() => { })
|
||||
onStatus?.('ready')
|
||||
return
|
||||
}
|
||||
|
||||
if (parsed.event === 'run.failed') {
|
||||
source.close()
|
||||
logger.error(`[AgentClients] ${this.name}: run failed`)
|
||||
this.stopTyping(roomId)
|
||||
this.deleteSession(actualSessionId).catch(() => { })
|
||||
onStatus?.('ready')
|
||||
return
|
||||
}
|
||||
|
||||
// Accumulate message deltas
|
||||
if (parsed.event === 'message.delta' && parsed.delta) {
|
||||
fullContent += parsed.delta
|
||||
}
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
}
|
||||
|
||||
source.onerror = (err: any) => {
|
||||
logger.error(err, `[AgentClients] ${this.name}: EventSource error`)
|
||||
source.close()
|
||||
this.stopTyping(roomId)
|
||||
this.deleteSession(actualSessionId).catch(() => { })
|
||||
onStatus?.('ready')
|
||||
}
|
||||
} catch (err: any) {
|
||||
logger.error(`[AgentClients] ${this.name}: error handling message: ${err.message}`)
|
||||
this.stopTyping(roomId)
|
||||
this.deleteSession(sessionId).catch(() => { })
|
||||
onStatus?.('ready')
|
||||
}
|
||||
}
|
||||
|
||||
private bindEvents(): void {
|
||||
const s = this.socket!
|
||||
|
||||
s.on('typing', (data: any) => {
|
||||
this.handlers.onTyping?.(data)
|
||||
})
|
||||
|
||||
s.on('stop_typing', (data: any) => {
|
||||
this.handlers.onStopTyping?.(data)
|
||||
})
|
||||
|
||||
s.on('member_joined', (data: any) => {
|
||||
this.handlers.onMemberJoined?.(data)
|
||||
})
|
||||
|
||||
s.on('member_left', (data: any) => {
|
||||
this.handlers.onMemberLeft?.(data)
|
||||
})
|
||||
|
||||
// Auto rejoin rooms on reconnect
|
||||
s.io.on('reconnect', async () => {
|
||||
if (this._reconnecting) return
|
||||
this._reconnecting = true
|
||||
logger.info(`[AgentClients] ${this.name} reconnecting, rejoining ${this.joinedRooms.size} rooms...`)
|
||||
const rooms = Array.from(this.joinedRooms)
|
||||
for (const roomId of rooms) {
|
||||
try {
|
||||
await this.joinRoom(roomId)
|
||||
} catch (err: any) {
|
||||
logger.error(`[AgentClients] ${this.name} failed to rejoin room ${roomId}: ${err.message}`)
|
||||
}
|
||||
}
|
||||
this._reconnecting = false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ─── AgentClients (roomId -> agents) ──────────────────────────
|
||||
|
||||
export class AgentClients {
|
||||
private rooms = new Map<string, Map<string, AgentClient>>()
|
||||
private _gatewayManager: GatewayManager | null = null
|
||||
private _contextEngine: any = null
|
||||
private _storage: any = null
|
||||
|
||||
// Per-room processing lock + mention queue
|
||||
private _processingRooms = new Set<string>()
|
||||
private _mentionQueue = new Map<string, Array<{ agent: AgentClient; msg: { content: string; senderName: string; senderId: string; timestamp: number } }>>()
|
||||
|
||||
/**
|
||||
* Create an agent client and connect it to the server.
|
||||
* The agent will NOT auto-join any room — call addAgentToRoom separately.
|
||||
*/
|
||||
async createAgent(config: AgentConfig, handlers?: AgentEventHandler, port?: number): Promise<AgentClient> {
|
||||
const client = new AgentClient(config, handlers)
|
||||
await client.connect(port)
|
||||
|
||||
// Auto-apply stored references (fixes propagation for agents created after set*)
|
||||
if (this._gatewayManager) client.setGatewayManager(this._gatewayManager)
|
||||
if (this._contextEngine) client.setContextEngine(this._contextEngine)
|
||||
if (this._storage) client.setStorage(this._storage)
|
||||
|
||||
logger.info(`[AgentClients] Connected: ${client.name} (${client.agentId})`)
|
||||
return client
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect an agent to a room.
|
||||
*/
|
||||
async addAgentToRoom(roomId: string, client: AgentClient): Promise<JoinResult> {
|
||||
let room = this.rooms.get(roomId)
|
||||
if (!room) {
|
||||
room = new Map()
|
||||
this.rooms.set(roomId, room)
|
||||
}
|
||||
|
||||
room.set(client.agentId, client)
|
||||
const result = await client.joinRoom(roomId)
|
||||
logger.info(`[AgentClients] ${client.name} joined room: ${roomId}`)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an agent from a room and disconnect it.
|
||||
*/
|
||||
removeAgentFromRoom(roomId: string, agentId: string): void {
|
||||
const room = this.rooms.get(roomId)
|
||||
if (!room) return
|
||||
|
||||
const client = room.get(agentId)
|
||||
if (client) {
|
||||
client.disconnect()
|
||||
room.delete(agentId)
|
||||
logger.info(`[AgentClients] ${client.name} left room: ${roomId}`)
|
||||
|
||||
// Invalidate context engine cache for this agent
|
||||
if (this._contextEngine) {
|
||||
try { this._contextEngine.invalidateRoom(roomId) } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
if (room.size === 0) {
|
||||
this.rooms.delete(roomId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all agents in a room.
|
||||
*/
|
||||
getAgents(roomId: string): AgentClient[] {
|
||||
const room = this.rooms.get(roomId)
|
||||
return room ? Array.from(room.values()) : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific agent in a room.
|
||||
*/
|
||||
getAgent(roomId: string, agentId: string): AgentClient | undefined {
|
||||
return this.rooms.get(roomId)?.get(agentId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all room IDs that have agents.
|
||||
*/
|
||||
getRoomIds(): string[] {
|
||||
return Array.from(this.rooms.keys())
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message from a specific agent in a room.
|
||||
*/
|
||||
async sendMessage(roomId: string, agentId: string, content: string): Promise<string> {
|
||||
const client = this.getAgent(roomId, agentId)
|
||||
if (!client) {
|
||||
throw new Error(`Agent "${agentId}" not found in room "${roomId}"`)
|
||||
}
|
||||
return client.sendMessage(roomId, content)
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast a message from all agents in a room.
|
||||
*/
|
||||
async broadcastFromRoom(roomId: string, content: string): Promise<string[]> {
|
||||
const agents = this.getAgents(roomId)
|
||||
return Promise.all(agents.map((agent) => agent.sendMessage(roomId, content)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect all agents in a room.
|
||||
*/
|
||||
disconnectRoom(roomId: string): void {
|
||||
const room = this.rooms.get(roomId)
|
||||
if (!room) return
|
||||
|
||||
room.forEach((client) => client.disconnect())
|
||||
this.rooms.delete(roomId)
|
||||
logger.info(`[AgentClients] All agents disconnected from room: ${roomId}`)
|
||||
|
||||
// Invalidate context engine cache for this room
|
||||
if (this._contextEngine) {
|
||||
try { this._contextEngine.invalidateRoom(roomId) } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect all agents in all rooms.
|
||||
*/
|
||||
disconnectAll(): void {
|
||||
this.rooms.forEach((room) => {
|
||||
room.forEach((client) => client.disconnect())
|
||||
})
|
||||
this.rooms.clear()
|
||||
logger.info('[AgentClients] All agents disconnected')
|
||||
}
|
||||
|
||||
/**
|
||||
* Set gateway manager for all existing and future agents.
|
||||
*/
|
||||
setGatewayManager(manager: GatewayManager): void {
|
||||
this._gatewayManager = manager
|
||||
this.rooms.forEach((room) => {
|
||||
room.forEach((client) => client.setGatewayManager(manager))
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Set context engine for all existing and future agents.
|
||||
*/
|
||||
setContextEngine(engine: any): void {
|
||||
this._contextEngine = engine
|
||||
this.rooms.forEach((room) => {
|
||||
room.forEach((client) => client.setContextEngine(engine))
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Set message storage for all existing and future agents.
|
||||
*/
|
||||
setStorage(storage: any): void {
|
||||
this._storage = storage
|
||||
this.rooms.forEach((room) => {
|
||||
room.forEach((client) => client.setStorage(storage))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Server-side: parse @mentions and forward to matching agents directly.
|
||||
* If the room is already processing (compressing/replying), queue the mention.
|
||||
*/
|
||||
async processMentions(roomId: string, msg: { content: string; senderName: string; senderId: string; timestamp: number }): Promise<void> {
|
||||
if (!this._gatewayManager) return
|
||||
|
||||
const content = msg.content.toLowerCase()
|
||||
const agents = this.getAgents(roomId)
|
||||
|
||||
const mentioned = agents.filter(a => content.includes(`@${a.name.toLowerCase()}`))
|
||||
if (mentioned.length === 0) return
|
||||
|
||||
logger.debug(`[AgentClients] ${mentioned.map(a => a.name).join(', ')} mentioned by ${msg.senderName}`)
|
||||
|
||||
for (const agent of mentioned) {
|
||||
this._processAgentMention(roomId, agent, msg).catch((err) => {
|
||||
logger.error(`[AgentClients] error processing mention for ${agent.name}: ${err.message}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single agent mention with status reporting and queue drain.
|
||||
*/
|
||||
private async _processAgentMention(
|
||||
roomId: string,
|
||||
agent: AgentClient,
|
||||
msg: { content: string; senderName: string; senderId: string; timestamp: number },
|
||||
): Promise<void> {
|
||||
const agentKey = `${roomId}:${agent.name}`
|
||||
if (this._processingRooms.has(agentKey)) {
|
||||
// Queue for this specific agent
|
||||
let queue = this._mentionQueue.get(agentKey)
|
||||
if (!queue) {
|
||||
queue = []
|
||||
this._mentionQueue.set(agentKey, queue)
|
||||
}
|
||||
queue.push({ agent, msg })
|
||||
logger.debug(`[AgentClients] agent ${agent.name} is processing, queued mention in room ${roomId}`)
|
||||
return
|
||||
}
|
||||
|
||||
this._processingRooms.add(agentKey)
|
||||
const onStatus = (status: 'compressing' | 'replying' | 'ready') => {
|
||||
agent.emitContextStatus(roomId, status)
|
||||
logger.debug(`[AgentClients] room ${roomId} agent ${agent.name} status: ${status}`)
|
||||
}
|
||||
|
||||
try {
|
||||
await agent.replyToMention(roomId, msg, onStatus)
|
||||
} finally {
|
||||
this._processingRooms.delete(agentKey)
|
||||
await this._drainQueue(agentKey, roomId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain queued mentions for a room after processing completes.
|
||||
*/
|
||||
private async _drainQueue(agentKey: string, roomId: string): Promise<void> {
|
||||
const queue = this._mentionQueue.get(agentKey)
|
||||
if (!queue || queue.length === 0) return
|
||||
|
||||
this._mentionQueue.delete(agentKey)
|
||||
logger.debug(`[AgentClients] draining ${queue.length} queued mention(s) for ${agentKey}`)
|
||||
|
||||
// Process the last queued mention only (most recent, discards stale intermediate ones)
|
||||
const last = queue[queue.length - 1]
|
||||
this._processingRooms.add(agentKey)
|
||||
this._processAgentMention(roomId, last.agent, last.msg).catch((err) => {
|
||||
logger.error(`[AgentClients] error processing queued mention: ${err.message}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,866 @@
|
||||
import { Server, Socket, Namespace } from 'socket.io'
|
||||
import type { Server as HttpServer } from 'http'
|
||||
import { getToken } from '../../../services/auth'
|
||||
import { logger } from '../../../services/logger'
|
||||
import { getDb, ensureTable } from '../../../db'
|
||||
import { AgentClients } from './agent-clients'
|
||||
import { deleteSession as hermesDeleteSession } from '../hermes-cli'
|
||||
import { ContextEngine } from '../context-engine/compressor'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────
|
||||
|
||||
interface ChatMessage {
|
||||
id: string
|
||||
roomId: string
|
||||
senderId: string
|
||||
senderName: string
|
||||
content: string
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
interface RoomAgent {
|
||||
id: string
|
||||
roomId: string
|
||||
agentId: string
|
||||
profile: string
|
||||
name: string
|
||||
description: string
|
||||
invited: number
|
||||
}
|
||||
|
||||
interface Member {
|
||||
id: string
|
||||
userId: string
|
||||
name: string
|
||||
description: string
|
||||
joinedAt: number
|
||||
online: boolean
|
||||
socketId: string
|
||||
}
|
||||
|
||||
// ─── SQLite Storage (global DB) ──────────────────────────────
|
||||
|
||||
const GC_PENDING_SESSION_DELETES_SCHEMA: Record<string, string> = {
|
||||
session_id: 'TEXT PRIMARY KEY',
|
||||
profile_name: 'TEXT NOT NULL',
|
||||
status: "TEXT NOT NULL DEFAULT 'pending'",
|
||||
attempt_count: 'INTEGER NOT NULL DEFAULT 0',
|
||||
last_error: 'TEXT',
|
||||
created_at: 'INTEGER NOT NULL',
|
||||
updated_at: 'INTEGER NOT NULL',
|
||||
next_attempt_at: 'INTEGER NOT NULL DEFAULT 0',
|
||||
}
|
||||
|
||||
const GC_SESSION_PROFILES_SCHEMA: Record<string, string> = {
|
||||
session_id: 'TEXT PRIMARY KEY',
|
||||
room_id: 'TEXT NOT NULL',
|
||||
agent_id: 'TEXT NOT NULL',
|
||||
profile_name: 'TEXT NOT NULL',
|
||||
created_at: 'INTEGER NOT NULL',
|
||||
}
|
||||
|
||||
const GC_ROOMS_SCHEMA: Record<string, string> = {
|
||||
id: 'TEXT PRIMARY KEY',
|
||||
name: 'TEXT NOT NULL',
|
||||
inviteCode: 'TEXT UNIQUE',
|
||||
triggerTokens: 'INTEGER NOT NULL DEFAULT 100000',
|
||||
maxHistoryTokens: 'INTEGER NOT NULL DEFAULT 32000',
|
||||
tailMessageCount: 'INTEGER NOT NULL DEFAULT 20',
|
||||
totalTokens: 'INTEGER NOT NULL DEFAULT 0',
|
||||
}
|
||||
|
||||
const GC_MESSAGES_SCHEMA: Record<string, string> = {
|
||||
id: 'TEXT PRIMARY KEY',
|
||||
roomId: 'TEXT NOT NULL',
|
||||
senderId: 'TEXT NOT NULL',
|
||||
senderName: 'TEXT NOT NULL',
|
||||
content: 'TEXT NOT NULL',
|
||||
timestamp: 'INTEGER NOT NULL',
|
||||
}
|
||||
|
||||
const GC_ROOM_AGENTS_SCHEMA: Record<string, string> = {
|
||||
id: 'TEXT PRIMARY KEY',
|
||||
roomId: 'TEXT NOT NULL',
|
||||
agentId: 'TEXT NOT NULL',
|
||||
profile: 'TEXT NOT NULL',
|
||||
name: 'TEXT NOT NULL',
|
||||
description: "TEXT NOT NULL DEFAULT ''",
|
||||
invited: 'INTEGER NOT NULL DEFAULT 0',
|
||||
}
|
||||
|
||||
const GC_CONTEXT_SNAPSHOTS_SCHEMA: Record<string, string> = {
|
||||
roomId: 'TEXT PRIMARY KEY',
|
||||
summary: 'TEXT NOT NULL DEFAULT \'\'',
|
||||
lastMessageId: 'TEXT NOT NULL',
|
||||
lastMessageTimestamp: 'INTEGER NOT NULL',
|
||||
updatedAt: 'INTEGER NOT NULL',
|
||||
}
|
||||
|
||||
const GC_ROOM_MEMBERS_SCHEMA: Record<string, string> = {
|
||||
id: 'TEXT PRIMARY KEY',
|
||||
roomId: 'TEXT NOT NULL',
|
||||
userId: 'TEXT NOT NULL',
|
||||
userName: 'TEXT NOT NULL',
|
||||
description: "TEXT NOT NULL DEFAULT ''",
|
||||
joinedAt: 'INTEGER NOT NULL',
|
||||
updatedAt: 'INTEGER NOT NULL',
|
||||
}
|
||||
|
||||
let _tablesEnsured = false
|
||||
|
||||
interface PendingSessionDelete {
|
||||
session_id: string
|
||||
profile_name: string
|
||||
status: string
|
||||
attempt_count: number
|
||||
last_error: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
next_attempt_at: number
|
||||
}
|
||||
|
||||
interface GroupChatSessionProfile {
|
||||
session_id: string
|
||||
room_id: string
|
||||
agent_id: string
|
||||
profile_name: string
|
||||
created_at: number
|
||||
}
|
||||
|
||||
export interface PendingSessionDeleteDrainResult {
|
||||
deleted: string[]
|
||||
failed: Array<{ sessionId: string; error: string }>
|
||||
}
|
||||
|
||||
class ChatStorage {
|
||||
private db() { return getDb() }
|
||||
|
||||
init(): void {
|
||||
if (_tablesEnsured) return
|
||||
const db = this.db()
|
||||
if (!db) return
|
||||
ensureTable('gc_rooms', GC_ROOMS_SCHEMA)
|
||||
ensureTable('gc_messages', GC_MESSAGES_SCHEMA)
|
||||
ensureTable('gc_room_agents', GC_ROOM_AGENTS_SCHEMA)
|
||||
ensureTable('gc_context_snapshots', GC_CONTEXT_SNAPSHOTS_SCHEMA)
|
||||
ensureTable('gc_room_members', GC_ROOM_MEMBERS_SCHEMA)
|
||||
ensureTable('gc_pending_session_deletes', GC_PENDING_SESSION_DELETES_SCHEMA)
|
||||
ensureTable('gc_session_profiles', GC_SESSION_PROFILES_SCHEMA)
|
||||
// Indexes (safe to run multiple times — CREATE INDEX IF NOT EXISTS)
|
||||
try { db.exec('CREATE INDEX IF NOT EXISTS idx_gc_messages_room ON gc_messages(roomId, timestamp)') } catch { /* ignore */ }
|
||||
try { db.exec('CREATE INDEX IF NOT EXISTS idx_gc_room_agents_room ON gc_room_agents(roomId)') } catch { /* ignore */ }
|
||||
try { db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_gc_room_members_unique ON gc_room_members(roomId, userId)') } catch { /* ignore */ }
|
||||
try { db.exec('CREATE INDEX IF NOT EXISTS idx_gc_pending_session_deletes_profile ON gc_pending_session_deletes(profile_name, status, next_attempt_at, created_at)') } catch { /* ignore */ }
|
||||
try { db.exec('CREATE INDEX IF NOT EXISTS idx_gc_session_profiles_profile ON gc_session_profiles(profile_name, created_at)') } catch { /* ignore */ }
|
||||
_tablesEnsured = true
|
||||
}
|
||||
|
||||
saveSessionProfile(sessionId: string, roomId: string, agentId: string, profileName: string): void {
|
||||
this.db()?.prepare(
|
||||
'INSERT INTO gc_session_profiles (session_id, room_id, agent_id, profile_name, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET room_id = excluded.room_id, agent_id = excluded.agent_id, profile_name = excluded.profile_name'
|
||||
).run(sessionId, roomId, agentId, profileName, Date.now())
|
||||
}
|
||||
|
||||
getSessionProfile(sessionId: string): GroupChatSessionProfile | null {
|
||||
return (this.db()?.prepare(
|
||||
'SELECT session_id, room_id, agent_id, profile_name, created_at FROM gc_session_profiles WHERE session_id = ?'
|
||||
).get(sessionId) as GroupChatSessionProfile | undefined) ?? null
|
||||
}
|
||||
|
||||
deleteSessionProfile(sessionId: string): void {
|
||||
this.db()?.prepare('DELETE FROM gc_session_profiles WHERE session_id = ?').run(sessionId)
|
||||
}
|
||||
|
||||
listPendingSessionDeletes(profileName: string, limit = 50): PendingSessionDelete[] {
|
||||
const rows = this.db()?.prepare(
|
||||
`SELECT session_id, profile_name, status, attempt_count, last_error, created_at, updated_at, next_attempt_at
|
||||
FROM gc_pending_session_deletes
|
||||
WHERE profile_name = ? AND status = 'pending' AND next_attempt_at <= ?
|
||||
ORDER BY created_at ASC
|
||||
LIMIT ?`
|
||||
).all(profileName, Date.now(), limit) || []
|
||||
return rows.map((row: any) => ({
|
||||
session_id: String(row.session_id || ''),
|
||||
profile_name: String(row.profile_name || ''),
|
||||
status: String(row.status || 'pending'),
|
||||
attempt_count: Number(row.attempt_count || 0),
|
||||
last_error: row.last_error == null ? null : String(row.last_error),
|
||||
created_at: Number(row.created_at || 0),
|
||||
updated_at: Number(row.updated_at || 0),
|
||||
next_attempt_at: Number(row.next_attempt_at || 0),
|
||||
}))
|
||||
}
|
||||
|
||||
enqueuePendingSessionDelete(sessionId: string, profileName: string): void {
|
||||
const now = Date.now()
|
||||
this.db()?.prepare(
|
||||
`INSERT INTO gc_pending_session_deletes (session_id, profile_name, status, attempt_count, last_error, created_at, updated_at, next_attempt_at)
|
||||
VALUES (?, ?, 'pending', 0, NULL, ?, ?, 0)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
profile_name = excluded.profile_name,
|
||||
status = 'pending',
|
||||
updated_at = excluded.updated_at,
|
||||
next_attempt_at = 0`
|
||||
).run(sessionId, profileName, now, now)
|
||||
}
|
||||
|
||||
claimPendingSessionDeletes(profileName: string, limit = 50): PendingSessionDelete[] {
|
||||
const rows = this.listPendingSessionDeletes(profileName, limit)
|
||||
if (rows.length === 0) return []
|
||||
const now = Date.now()
|
||||
const stmt = this.db()?.prepare(
|
||||
`UPDATE gc_pending_session_deletes
|
||||
SET status = 'processing', updated_at = ?
|
||||
WHERE session_id = ? AND status = 'pending'`
|
||||
)
|
||||
const claimed: PendingSessionDelete[] = []
|
||||
for (const row of rows) {
|
||||
const result = stmt?.run(now, row.session_id)
|
||||
if (result?.changes) {
|
||||
claimed.push({ ...row, status: 'processing', updated_at: now })
|
||||
}
|
||||
}
|
||||
return claimed
|
||||
}
|
||||
|
||||
markPendingSessionDeleteFailed(sessionId: string, error: string): void {
|
||||
const now = Date.now()
|
||||
this.db()?.prepare(
|
||||
`UPDATE gc_pending_session_deletes
|
||||
SET status = 'pending',
|
||||
attempt_count = attempt_count + 1,
|
||||
last_error = ?,
|
||||
updated_at = ?,
|
||||
next_attempt_at = ?
|
||||
WHERE session_id = ?`
|
||||
).run(error, now, now + 60_000, sessionId)
|
||||
}
|
||||
|
||||
removePendingSessionDelete(sessionId: string): void {
|
||||
this.db()?.prepare('DELETE FROM gc_pending_session_deletes WHERE session_id = ?').run(sessionId)
|
||||
}
|
||||
|
||||
getPendingDeletedSessionIds(): Set<string> {
|
||||
const rows = (this.db()?.prepare(
|
||||
`SELECT session_id FROM gc_pending_session_deletes WHERE status IN ('pending', 'processing')`
|
||||
).all() || []) as Array<{ session_id: string }>
|
||||
return new Set(rows.map(row => row.session_id))
|
||||
}
|
||||
|
||||
// ─── Rooms ────────────────────────────────────────────────
|
||||
|
||||
getRoom(roomId: string): { id: string; name: string; inviteCode: string | null; triggerTokens: number; maxHistoryTokens: number; tailMessageCount: number; totalTokens: number } | undefined {
|
||||
return this.db()?.prepare('SELECT id, name, inviteCode, triggerTokens, maxHistoryTokens, tailMessageCount, totalTokens FROM gc_rooms WHERE id = ?').get(roomId) as any
|
||||
}
|
||||
|
||||
getRoomByInviteCode(code: string): { id: string; name: string; inviteCode: string | null; triggerTokens: number; maxHistoryTokens: number; tailMessageCount: number; totalTokens: number } | undefined {
|
||||
return this.db()?.prepare('SELECT id, name, inviteCode, triggerTokens, maxHistoryTokens, tailMessageCount, totalTokens FROM gc_rooms WHERE inviteCode = ?').get(code) as any
|
||||
}
|
||||
|
||||
getAllRooms(): { id: string; name: string; inviteCode: string | null; triggerTokens: number; maxHistoryTokens: number; tailMessageCount: number; totalTokens: number }[] {
|
||||
return (this.db()?.prepare('SELECT id, name, inviteCode, triggerTokens, maxHistoryTokens, tailMessageCount, totalTokens FROM gc_rooms ORDER BY id').all() || []) as any[]
|
||||
}
|
||||
|
||||
saveRoom(id: string, name: string, inviteCode?: string, config?: { triggerTokens?: number; maxHistoryTokens?: number; tailMessageCount?: number }): void {
|
||||
this.db()?.prepare(
|
||||
'INSERT OR IGNORE INTO gc_rooms (id, name, inviteCode, triggerTokens, maxHistoryTokens, tailMessageCount) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run(id, name, inviteCode || null, config?.triggerTokens ?? 100000, config?.maxHistoryTokens ?? 32000, config?.tailMessageCount ?? 20)
|
||||
}
|
||||
|
||||
updateRoomConfig(roomId: string, config: { triggerTokens?: number; maxHistoryTokens?: number; tailMessageCount?: number }): void {
|
||||
const sets: string[] = []
|
||||
const vals: any[] = []
|
||||
if (config.triggerTokens !== undefined) { sets.push('triggerTokens = ?'); vals.push(config.triggerTokens) }
|
||||
if (config.maxHistoryTokens !== undefined) { sets.push('maxHistoryTokens = ?'); vals.push(config.maxHistoryTokens) }
|
||||
if (config.tailMessageCount !== undefined) { sets.push('tailMessageCount = ?'); vals.push(config.tailMessageCount) }
|
||||
if (sets.length === 0) return
|
||||
vals.push(roomId)
|
||||
this.db()?.prepare(`UPDATE gc_rooms SET ${sets.join(', ')} WHERE id = ?`).run(...vals)
|
||||
}
|
||||
|
||||
updateRoomInviteCode(roomId: string, inviteCode: string): void {
|
||||
this.db()?.prepare('UPDATE gc_rooms SET inviteCode = ? WHERE id = ?').run(inviteCode, roomId)
|
||||
}
|
||||
|
||||
updateRoomTotalTokens(roomId: string, tokens: number): void {
|
||||
this.db()?.prepare('UPDATE gc_rooms SET totalTokens = ? WHERE id = ?').run(tokens, roomId)
|
||||
}
|
||||
|
||||
estimateTokens(text: string): number {
|
||||
const cjk = (text.match(/[\u2e80-\u9fff\uac00-\ud7af\u3000-\u303f\uff00-\uffef]/g) || []).length
|
||||
const other = text.length - cjk
|
||||
return Math.ceil(cjk * 1.5 + other / 4)
|
||||
}
|
||||
|
||||
// ─── Messages ─────────────────────────────────────────────
|
||||
|
||||
getMessages(roomId: string, limit = 500): ChatMessage[] {
|
||||
const rows = (this.db()?.prepare(
|
||||
'SELECT id, roomId, senderId, senderName, content, timestamp FROM gc_messages WHERE roomId = ? ORDER BY timestamp DESC LIMIT ?'
|
||||
).all(roomId, limit) || []) as any[]
|
||||
return rows.reverse()
|
||||
}
|
||||
|
||||
addMessage(msg: ChatMessage): void {
|
||||
this.db()?.prepare(
|
||||
'INSERT INTO gc_messages (id, roomId, senderId, senderName, content, timestamp) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run(msg.id, msg.roomId, msg.senderId, msg.senderName, msg.content, msg.timestamp)
|
||||
}
|
||||
|
||||
pruneMessages(roomId: string, keep = 500): void {
|
||||
const db = this.db()
|
||||
if (!db) return
|
||||
const count = (db.prepare('SELECT COUNT(*) as c FROM gc_messages WHERE roomId = ?').get(roomId) as any)?.c
|
||||
if (count > keep) {
|
||||
const cutoff = db.prepare(
|
||||
'SELECT timestamp FROM gc_messages WHERE roomId = ? ORDER BY timestamp DESC LIMIT 1 OFFSET ?'
|
||||
).get(roomId, keep - 1) as any
|
||||
if (cutoff) {
|
||||
const result = db.prepare('DELETE FROM gc_messages WHERE roomId = ? AND timestamp < ?').run(roomId, cutoff.timestamp)
|
||||
logger.info(`[GroupChat] pruned ${result.changes} messages from room ${roomId} (had ${count}, keeping ${keep})`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Room Agents ──────────────────────────────────────────
|
||||
|
||||
getRoomAgents(roomId: string): RoomAgent[] {
|
||||
return (this.db()?.prepare(
|
||||
'SELECT id, roomId, agentId, profile, name, description, invited FROM gc_room_agents WHERE roomId = ?'
|
||||
).all(roomId) || []) as unknown as RoomAgent[]
|
||||
}
|
||||
|
||||
addRoomAgent(roomId: string, agentId: string, profile: string, name: string, description: string, invited: number): RoomAgent {
|
||||
const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
this.db()?.prepare(
|
||||
'INSERT INTO gc_room_agents (id, roomId, agentId, profile, name, description, invited) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(id, roomId, agentId, profile, name, description, invited)
|
||||
return { id, roomId, agentId, profile, name, description, invited }
|
||||
}
|
||||
|
||||
removeRoomAgent(agentId: string): void {
|
||||
this.db()?.prepare('DELETE FROM gc_room_agents WHERE id = ?').run(agentId)
|
||||
}
|
||||
|
||||
// ─── Context Snapshots ──────────────────────────────────
|
||||
|
||||
getContextSnapshot(roomId: string): { roomId: string; summary: string; lastMessageId: string; lastMessageTimestamp: number; updatedAt: number } | null {
|
||||
return (this.db()?.prepare(
|
||||
'SELECT roomId, summary, lastMessageId, lastMessageTimestamp, updatedAt FROM gc_context_snapshots WHERE roomId = ?'
|
||||
).get(roomId) as any) ?? null
|
||||
}
|
||||
|
||||
saveContextSnapshot(roomId: string, summary: string, lastMessageId: string, lastMessageTimestamp: number): void {
|
||||
this.db()?.prepare(
|
||||
'INSERT INTO gc_context_snapshots (roomId, summary, lastMessageId, lastMessageTimestamp, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(roomId) DO UPDATE SET summary = excluded.summary, lastMessageId = excluded.lastMessageId, lastMessageTimestamp = excluded.lastMessageTimestamp, updatedAt = excluded.updatedAt'
|
||||
).run(roomId, summary, lastMessageId, lastMessageTimestamp, Date.now())
|
||||
}
|
||||
|
||||
deleteContextSnapshot(roomId: string): void {
|
||||
this.db()?.prepare('DELETE FROM gc_context_snapshots WHERE roomId = ?').run(roomId)
|
||||
}
|
||||
|
||||
deleteRoom(roomId: string): void {
|
||||
const db = this.db()
|
||||
if (!db) return
|
||||
db.prepare('DELETE FROM gc_messages WHERE roomId = ?').run(roomId)
|
||||
db.prepare('DELETE FROM gc_room_agents WHERE roomId = ?').run(roomId)
|
||||
db.prepare('DELETE FROM gc_room_members WHERE roomId = ?').run(roomId)
|
||||
db.prepare('DELETE FROM gc_context_snapshots WHERE roomId = ?').run(roomId)
|
||||
db.prepare('DELETE FROM gc_rooms WHERE id = ?').run(roomId)
|
||||
}
|
||||
|
||||
// ─── Room Members ──────────────────────────────────────
|
||||
|
||||
getRoomMembers(roomId: string): { id: string; userId: string; name: string; description: string; joinedAt: number }[] {
|
||||
return (this.db()?.prepare(
|
||||
'SELECT id, userId, userName as name, description, joinedAt FROM gc_room_members WHERE roomId = ? ORDER BY joinedAt'
|
||||
).all(roomId) || []) as unknown as { id: string; userId: string; name: string; description: string; joinedAt: number }[]
|
||||
}
|
||||
|
||||
addRoomMember(roomId: string, userId: string, userName: string, description: string): void {
|
||||
const existing = this.getMemberByUserId(roomId, userId)
|
||||
if (existing) {
|
||||
// Update name/description on rejoin, refresh updatedAt
|
||||
this.db()?.prepare(
|
||||
'UPDATE gc_room_members SET userName = ?, description = ?, updatedAt = ? WHERE roomId = ? AND userId = ?'
|
||||
).run(userName, description, Date.now(), roomId, userId)
|
||||
return
|
||||
}
|
||||
const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
const now = Date.now()
|
||||
this.db()?.prepare(
|
||||
'INSERT INTO gc_room_members (id, roomId, userId, userName, description, joinedAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(id, roomId, userId, userName, description, now, now)
|
||||
}
|
||||
|
||||
getMemberByUserId(roomId: string, userId: string): Member | null {
|
||||
return (this.db()?.prepare(
|
||||
'SELECT id, userId, userName as name, description, joinedAt FROM gc_room_members WHERE roomId = ? AND userId = ?'
|
||||
).get(roomId, userId) as any) ?? null
|
||||
}
|
||||
|
||||
updateMemberActivity(roomId: string, userId: string): void {
|
||||
this.db()?.prepare(
|
||||
'UPDATE gc_room_members SET updatedAt = ? WHERE roomId = ? AND userId = ?'
|
||||
).run(Date.now(), roomId, userId)
|
||||
}
|
||||
}
|
||||
|
||||
export async function drainPendingSessionDeletes(profileName: string): Promise<PendingSessionDeleteDrainResult> {
|
||||
const storage = new ChatStorage()
|
||||
storage.init()
|
||||
const claimed = storage.claimPendingSessionDeletes(profileName)
|
||||
const result: PendingSessionDeleteDrainResult = { deleted: [], failed: [] }
|
||||
|
||||
for (const item of claimed) {
|
||||
try {
|
||||
const ok = await hermesDeleteSession(item.session_id)
|
||||
if (!ok) {
|
||||
throw new Error('Failed to delete session')
|
||||
}
|
||||
storage.removePendingSessionDelete(item.session_id)
|
||||
storage.deleteSessionProfile(item.session_id)
|
||||
result.deleted.push(item.session_id)
|
||||
} catch (err: any) {
|
||||
const message = err?.message || 'Failed to delete session'
|
||||
storage.markPendingSessionDeleteFailed(item.session_id, message)
|
||||
result.failed.push({ sessionId: item.session_id, error: message })
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// ─── ChatRoom (in-memory, for online members) ─────────────────
|
||||
|
||||
class ChatRoom {
|
||||
readonly id: string
|
||||
name: string
|
||||
readonly members = new Map<string, Member>()
|
||||
|
||||
constructor(id: string, name?: string) {
|
||||
this.id = id
|
||||
this.name = name || id
|
||||
}
|
||||
|
||||
addOrUpdateMember(socketId: string, userId: string, name: string, description: string): Member {
|
||||
const existing = this.members.get(userId)
|
||||
if (existing) {
|
||||
existing.name = name
|
||||
existing.description = description
|
||||
existing.online = true
|
||||
existing.socketId = socketId
|
||||
return existing
|
||||
}
|
||||
const member: Member = { id: socketId, userId, name, description, joinedAt: Date.now(), online: true, socketId }
|
||||
this.members.set(userId, member)
|
||||
return member
|
||||
}
|
||||
|
||||
removeMember(socketId: string): void {
|
||||
for (const member of this.members.values()) {
|
||||
if (member.socketId === socketId) {
|
||||
member.online = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getMembersList(): Member[] {
|
||||
return Array.from(this.members.values())
|
||||
}
|
||||
|
||||
getOnlineMemberBySocketId(socketId: string): Member | undefined {
|
||||
for (const member of this.members.values()) {
|
||||
if (member.socketId === socketId && member.online) return member
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
hasOnlineMember(socketId: string): boolean {
|
||||
return this.getOnlineMemberBySocketId(socketId) !== undefined
|
||||
}
|
||||
}
|
||||
|
||||
// ─── GroupChat Server ────────────────────────────────────────
|
||||
|
||||
export class GroupChatServer {
|
||||
private io: Server
|
||||
private nsp: Namespace
|
||||
private storage: ChatStorage
|
||||
private rooms = new Map<string, ChatRoom>()
|
||||
/** Map: socket.id → persistent userId */
|
||||
private socketUserMap = new Map<string, string>()
|
||||
/** Map: userId → { name, description } (from auth) */
|
||||
private userInfoMap = new Map<string, { name: string; description: string }>()
|
||||
readonly agentClients = new AgentClients()
|
||||
private _contextEngine: ContextEngine | null = null
|
||||
private _restoreScheduled = false
|
||||
/** roomId -> (userId -> { userName, timer }) */
|
||||
private typingState = new Map<string, Map<string, { userName: string; timer: ReturnType<typeof setTimeout> }>>()
|
||||
/** roomId -> (agentName -> { agentName, status }) */
|
||||
private contextStatusState = new Map<string, Map<string, { agentName: string; status: string }>>()
|
||||
|
||||
setGatewayManager(manager: any): void {
|
||||
this.agentClients.setGatewayManager(manager)
|
||||
if (this._contextEngine && manager) {
|
||||
this._contextEngine.setUpstream(manager.getUpstream(''), manager.getApiKey(''))
|
||||
}
|
||||
}
|
||||
|
||||
constructor(httpServer: HttpServer) {
|
||||
this.storage = new ChatStorage()
|
||||
this.storage.init()
|
||||
|
||||
this.io = new Server(httpServer, {
|
||||
cors: { origin: '*' }
|
||||
})
|
||||
this.nsp = this.io.of('/group-chat')
|
||||
this.nsp.use(this.authMiddleware.bind(this))
|
||||
this.nsp.on('connection', this.onConnection.bind(this))
|
||||
|
||||
// Restore persisted rooms into memory
|
||||
this.storage.getAllRooms().forEach((row) => {
|
||||
this.rooms.set(row.id, new ChatRoom(row.id, row.name))
|
||||
})
|
||||
|
||||
logger.info('[GroupChat] Socket.IO ready at /group-chat')
|
||||
|
||||
// Initialize context engine for group chat compression
|
||||
const contextEngine = new ContextEngine({
|
||||
messageFetcher: this.storage,
|
||||
sessionCleaner: async (sessionId: string) => {
|
||||
try {
|
||||
await hermesDeleteSession(sessionId)
|
||||
} catch (err: any) {
|
||||
logger.warn(`[GroupChat] failed to delete compression session ${sessionId}: ${err.message}`)
|
||||
}
|
||||
},
|
||||
})
|
||||
this.agentClients.setContextEngine(contextEngine)
|
||||
this.agentClients.setStorage(this.storage)
|
||||
this._contextEngine = contextEngine
|
||||
|
||||
// Restore agent connections — call restoreAgents() after server is listening
|
||||
this._restoreScheduled = false
|
||||
}
|
||||
|
||||
getIO(): Server {
|
||||
return this.io
|
||||
}
|
||||
|
||||
getStorage(): ChatStorage {
|
||||
return this.storage
|
||||
}
|
||||
|
||||
getContextEngine(): ContextEngine | null {
|
||||
return this._contextEngine || null
|
||||
}
|
||||
|
||||
getRoomIds(): string[] {
|
||||
return Array.from(this.rooms.keys())
|
||||
}
|
||||
|
||||
// ─── Restore Agents ─────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Restore persisted agent connections. Safe to call multiple times;
|
||||
* will only execute once.
|
||||
*/
|
||||
async restoreWhenReady(): Promise<void> {
|
||||
if (this._restoreScheduled) return
|
||||
this._restoreScheduled = true
|
||||
await this.restoreAgents()
|
||||
}
|
||||
|
||||
private async restoreAgents(): Promise<void> {
|
||||
const rooms = this.storage.getAllRooms()
|
||||
let total = 0
|
||||
|
||||
for (const room of rooms) {
|
||||
const agents = this.storage.getRoomAgents(room.id)
|
||||
for (const agent of agents) {
|
||||
try {
|
||||
const client = await this.agentClients.createAgent({
|
||||
profile: agent.profile,
|
||||
name: agent.name,
|
||||
description: agent.description,
|
||||
invited: agent.invited,
|
||||
})
|
||||
await this.agentClients.addAgentToRoom(room.id, client)
|
||||
total++
|
||||
} catch (err: any) {
|
||||
logger.error(`[GroupChat] Failed to restore agent ${agent.name} in room ${room.id}: ${err.message}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (total > 0) {
|
||||
logger.info(`[GroupChat] Restored ${total} agent(s) across ${rooms.length} room(s)`)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Auth ───────────────────────────────────────────────────
|
||||
|
||||
private async authMiddleware(socket: Socket, next: (err?: Error) => void): Promise<void> {
|
||||
const authToken = await getToken()
|
||||
const token = socket.handshake.auth.token || socket.handshake.query.token || ''
|
||||
if (authToken) {
|
||||
if (token !== authToken) {
|
||||
return next(new Error('Unauthorized'))
|
||||
}
|
||||
}
|
||||
next()
|
||||
}
|
||||
|
||||
// ─── Connection ─────────────────────────────────────────────
|
||||
|
||||
private onConnection(socket: Socket): void {
|
||||
const auth = socket.handshake.auth as { userId?: string; name?: string; description?: string }
|
||||
const userId = auth.userId || socket.id
|
||||
const userName = auth.name || `User-${userId.slice(0, 6)}`
|
||||
const description = auth.description || ''
|
||||
|
||||
this.socketUserMap.set(socket.id, userId)
|
||||
this.userInfoMap.set(userId, { name: userName, description })
|
||||
|
||||
logger.debug(`[GroupChat] Connected: ${userName} (socket=${socket.id}, user=${userId})`)
|
||||
|
||||
socket.on('join', (data: { roomId?: string; name?: string }, ack?: (response?: unknown) => void) => this.handleJoin(socket, data, ack))
|
||||
socket.on('message', (data: { roomId?: string; content: string }, ack?: (response?: unknown) => void) => this.handleMessage(socket, data, ack))
|
||||
socket.on('typing', (data: { roomId?: string }) => this.handleTyping(socket, data))
|
||||
socket.on('stop_typing', (data: { roomId?: string }) => this.handleStopTyping(socket, data))
|
||||
socket.on('context_status', (data: { roomId?: string; agentName?: string; status?: string }) => this.handleContextStatus(socket, data))
|
||||
socket.on('disconnect', () => this.handleDisconnect(socket))
|
||||
}
|
||||
|
||||
// ─── Handlers ───────────────────────────────────────────────
|
||||
|
||||
private handleJoin(socket: Socket, data: { roomId?: string; name?: string; description?: string }, ack?: (res: any) => void): void {
|
||||
const socketId = socket.id
|
||||
const userId = this.socketUserMap.get(socketId) || socketId
|
||||
const userInfo = this.userInfoMap.get(userId) || { name: `User-${userId.slice(0, 6)}`, description: '' }
|
||||
const userName = data.name || userInfo.name
|
||||
const description = data.description || userInfo.description
|
||||
|
||||
// Update stored user info
|
||||
this.userInfoMap.set(userId, { name: userName, description })
|
||||
|
||||
const roomId = data.roomId || 'general'
|
||||
let room = this.rooms.get(roomId)
|
||||
if (!room) {
|
||||
room = new ChatRoom(roomId)
|
||||
this.rooms.set(roomId, room)
|
||||
this.storage.saveRoom(roomId, roomId)
|
||||
}
|
||||
|
||||
// Persist member to SQLite
|
||||
this.storage.addRoomMember(roomId, userId, userName, description)
|
||||
|
||||
// Add to in-memory online members (keyed by userId)
|
||||
room.addOrUpdateMember(socketId, userId, userName, description)
|
||||
socket.join(roomId)
|
||||
|
||||
socket.to(roomId).emit('member_joined', {
|
||||
roomId,
|
||||
memberId: userId,
|
||||
memberName: userName,
|
||||
members: room.getMembersList(),
|
||||
})
|
||||
|
||||
// Load history from SQLite
|
||||
const messages = this.storage.getMessages(roomId)
|
||||
const agents = this.storage.getRoomAgents(roomId)
|
||||
|
||||
ack?.({
|
||||
roomId,
|
||||
roomName: room.name,
|
||||
members: room.getMembersList(),
|
||||
messages,
|
||||
agents,
|
||||
rooms: this.getRoomIds(),
|
||||
typingUsers: this.getTypingUsers(roomId),
|
||||
contextStatuses: this.getContextStatuses(roomId),
|
||||
})
|
||||
|
||||
logger.debug(`[GroupChat] ${userName} (user=${userId}) joined room: ${roomId}`)
|
||||
}
|
||||
|
||||
private handleMessage(socket: Socket, data: { roomId?: string; content: string }, ack?: (res: any) => void): void {
|
||||
const socketId = socket.id
|
||||
const roomId = data.roomId || 'general'
|
||||
const room = this.rooms.get(roomId)
|
||||
|
||||
if (!room || !room.hasOnlineMember(socketId)) {
|
||||
ack?.({ error: 'Not in room' })
|
||||
return
|
||||
}
|
||||
|
||||
const member = room.getOnlineMemberBySocketId(socketId)
|
||||
const userId = member?.userId || socketId
|
||||
const userName = member?.name || `User-${socketId.slice(0, 6)}`
|
||||
|
||||
const msg: ChatMessage = {
|
||||
id: this.generateId(),
|
||||
roomId,
|
||||
senderId: userId,
|
||||
senderName: userName,
|
||||
content: data.content,
|
||||
timestamp: Date.now(),
|
||||
}
|
||||
|
||||
this.storage.addMessage(msg)
|
||||
this.storage.pruneMessages(roomId)
|
||||
|
||||
// Recalculate total tokens for the room
|
||||
const messages = this.storage.getMessages(roomId)
|
||||
const totalTokens = this.storage.estimateTokens(messages.map(m => m.content + m.senderName).join(''))
|
||||
this.storage.updateRoomTotalTokens(roomId, totalTokens)
|
||||
|
||||
this.nsp.to(roomId).emit('message', msg)
|
||||
this.nsp.to(roomId).emit('room_updated', { roomId, totalTokens })
|
||||
ack?.({ id: msg.id })
|
||||
|
||||
// Server-side @mention routing — parse mentions and invoke agents directly
|
||||
this.agentClients.processMentions(roomId, {
|
||||
content: msg.content,
|
||||
senderName: msg.senderName,
|
||||
senderId: msg.senderId,
|
||||
timestamp: msg.timestamp,
|
||||
}).catch((err) => {
|
||||
logger.error(`[GroupChat] processMentions error: ${err.message}`)
|
||||
})
|
||||
}
|
||||
|
||||
private handleTyping(socket: Socket, data: { roomId?: string }): void {
|
||||
const roomId = data.roomId || 'general'
|
||||
const userId = this.socketUserMap.get(socket.id) || socket.id
|
||||
const userName = this.userInfoMap.get(userId)?.name || `User-${socket.id.slice(0, 6)}`
|
||||
|
||||
// Track typing state for rejoin recovery
|
||||
let roomTyping = this.typingState.get(roomId)
|
||||
if (!roomTyping) {
|
||||
roomTyping = new Map()
|
||||
this.typingState.set(roomId, roomTyping)
|
||||
}
|
||||
const existing = roomTyping.get(userId)
|
||||
if (existing) clearTimeout(existing.timer)
|
||||
roomTyping.set(userId, {
|
||||
userName,
|
||||
timer: setTimeout(() => {
|
||||
roomTyping!.delete(userId)
|
||||
if (roomTyping!.size === 0) this.typingState.delete(roomId)
|
||||
}, 30000),
|
||||
})
|
||||
|
||||
socket.to(roomId).emit('typing', {
|
||||
roomId,
|
||||
userId,
|
||||
userName,
|
||||
})
|
||||
}
|
||||
|
||||
private handleStopTyping(socket: Socket, data: { roomId?: string }): void {
|
||||
const roomId = data.roomId || 'general'
|
||||
const userId = this.socketUserMap.get(socket.id) || socket.id
|
||||
|
||||
// Remove from typing state
|
||||
const roomTyping = this.typingState.get(roomId)
|
||||
if (roomTyping) {
|
||||
const entry = roomTyping.get(userId)
|
||||
if (entry) clearTimeout(entry.timer)
|
||||
roomTyping.delete(userId)
|
||||
if (roomTyping.size === 0) this.typingState.delete(roomId)
|
||||
}
|
||||
|
||||
socket.to(roomId).emit('stop_typing', {
|
||||
roomId,
|
||||
userId,
|
||||
})
|
||||
}
|
||||
|
||||
private handleContextStatus(socket: Socket, data: { roomId?: string; agentName?: string; status?: string }): void {
|
||||
const roomId = data.roomId || 'general'
|
||||
const agentName = data.agentName || ''
|
||||
const status = data.status || ''
|
||||
|
||||
if (!agentName) return
|
||||
|
||||
let roomStatuses = this.contextStatusState.get(roomId)
|
||||
if (!roomStatuses) {
|
||||
roomStatuses = new Map()
|
||||
this.contextStatusState.set(roomId, roomStatuses)
|
||||
}
|
||||
|
||||
if (status === 'ready') {
|
||||
roomStatuses.delete(agentName)
|
||||
if (roomStatuses.size === 0) this.contextStatusState.delete(roomId)
|
||||
} else {
|
||||
roomStatuses.set(agentName, { agentName, status })
|
||||
}
|
||||
|
||||
// Relay to all other sockets in the room
|
||||
socket.to(roomId).emit('context_status', {
|
||||
roomId,
|
||||
agentName,
|
||||
status,
|
||||
})
|
||||
}
|
||||
|
||||
private handleDisconnect(socket: Socket): void {
|
||||
const socketId = socket.id
|
||||
const userId = this.socketUserMap.get(socketId)
|
||||
const userName = userId ? this.userInfoMap.get(userId)?.name : undefined
|
||||
|
||||
logger.debug(`[GroupChat] Disconnected: ${userName || socketId} (socket=${socketId}, user=${userId || socketId})`)
|
||||
|
||||
// Clean up typing state for this socket
|
||||
for (const [roomId, roomTyping] of this.typingState) {
|
||||
const entry = roomTyping.get(userId || socketId)
|
||||
if (entry) {
|
||||
clearTimeout(entry.timer)
|
||||
roomTyping.delete(userId || socketId)
|
||||
if (roomTyping.size === 0) this.typingState.delete(roomId)
|
||||
}
|
||||
}
|
||||
|
||||
this.leaveAllRooms(socket, socketId)
|
||||
this.socketUserMap.delete(socketId)
|
||||
// Don't delete userInfoMap — it persists across reconnects
|
||||
}
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────
|
||||
|
||||
private getTypingUsers(roomId: string): Array<{ userId: string; userName: string }> {
|
||||
const roomTyping = this.typingState.get(roomId)
|
||||
if (!roomTyping) return []
|
||||
return Array.from(roomTyping.entries()).map(([userId, entry]) => ({ userId, userName: entry.userName }))
|
||||
}
|
||||
|
||||
private getContextStatuses(roomId: string): Array<{ agentName: string; status: string }> {
|
||||
const roomStatuses = this.contextStatusState.get(roomId)
|
||||
if (!roomStatuses) return []
|
||||
return Array.from(roomStatuses.values())
|
||||
}
|
||||
|
||||
private leaveAllRooms(socket: Socket, socketId: string): void {
|
||||
this.rooms.forEach((room, rid) => {
|
||||
if (room.hasOnlineMember(socketId)) {
|
||||
const member = room.getOnlineMemberBySocketId(socketId)
|
||||
room.removeMember(socketId)
|
||||
socket.leave(rid)
|
||||
this.nsp.to(rid).emit('member_left', {
|
||||
roomId: rid,
|
||||
memberId: member?.userId || socketId,
|
||||
memberName: member?.name || `User-${socketId.slice(0, 6)}`,
|
||||
members: room.getMembersList(),
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private generateId(): string {
|
||||
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
|
||||
}
|
||||
}
|
||||
@@ -36,5 +36,5 @@ export const logger = pino({
|
||||
level: process.env.LOG_LEVEL || 'info',
|
||||
}, pino.destination({
|
||||
dest: logFile,
|
||||
sync: false,
|
||||
sync: true,
|
||||
}))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { logger } from './logger'
|
||||
|
||||
export function bindShutdown(server: any): void {
|
||||
export function bindShutdown(server: any, groupChatServer?: any): void {
|
||||
let isShuttingDown = false
|
||||
|
||||
const shutdown = async (signal: string) => {
|
||||
@@ -10,6 +10,13 @@ export function bindShutdown(server: any): void {
|
||||
logger.info('Shutting down (%s)...', signal)
|
||||
|
||||
try {
|
||||
// Disconnect Socket.IO before HTTP server to prevent hanging
|
||||
if (groupChatServer) {
|
||||
groupChatServer.agentClients.disconnectAll()
|
||||
groupChatServer.getIO().close()
|
||||
logger.info('Socket.IO closed')
|
||||
}
|
||||
|
||||
if (server) {
|
||||
await new Promise<void>((resolve) => {
|
||||
server.close(() => {
|
||||
|
||||
@@ -14,12 +14,12 @@ await esbuild.build({
|
||||
target: 'node23',
|
||||
format: 'cjs',
|
||||
outfile: resolve(rootDir, 'dist/server/index.js'),
|
||||
external: ['node-pty', 'node:sqlite'],
|
||||
external: ['node-pty', 'node:sqlite', 'socket.io'],
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(version),
|
||||
},
|
||||
sourcemap: true,
|
||||
minify: false,
|
||||
treeShaking: false,
|
||||
minify: true,
|
||||
treeShaking: true,
|
||||
logLevel: 'info',
|
||||
})
|
||||
|
||||
@@ -94,6 +94,8 @@ describe('Chat Store', () => {
|
||||
window.localStorage.setItem(ACTIVE_SESSION_KEY, 'local-1')
|
||||
window.localStorage.setItem(SESSIONS_CACHE_KEY, JSON.stringify([cachedSession]))
|
||||
window.localStorage.setItem(sessionMessagesKey('local-1'), JSON.stringify(cachedMessages))
|
||||
// Mark local-1 as in-flight so loadSessions preserves it
|
||||
window.localStorage.setItem(inFlightKey('local-1'), JSON.stringify({ runId: 'run-1', startedAt: Date.now() }))
|
||||
|
||||
mockSessionsApi.fetchSessions.mockResolvedValue([makeSummary('remote-1', 'Remote Session')])
|
||||
mockSessionsApi.fetchSession.mockResolvedValue(null)
|
||||
|
||||
@@ -8,6 +8,15 @@ vi.mock('vue-i18n', () => ({
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('naive-ui', () => ({
|
||||
useMessage: () => ({
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
import MarkdownRenderer from '@/components/hermes/chat/MarkdownRenderer.vue'
|
||||
|
||||
describe('MarkdownRenderer', () => {
|
||||
|
||||
@@ -8,6 +8,15 @@ vi.mock('vue-i18n', () => ({
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('naive-ui', () => ({
|
||||
useMessage: () => ({
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
import MessageItem from '@/components/hermes/chat/MessageItem.vue'
|
||||
import type { Message } from '@/stores/hermes/chat'
|
||||
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SummaryCache } from '../../packages/server/src/services/hermes/context-engine/summary-cache'
|
||||
import {
|
||||
buildAgentInstructions,
|
||||
buildSummarizationSystemPrompt,
|
||||
buildFullSummaryPrompt,
|
||||
buildIncrementalUpdatePrompt,
|
||||
} from '../../packages/server/src/services/hermes/context-engine/prompt'
|
||||
import { ContextEngine } from '../../packages/server/src/services/hermes/context-engine/compressor'
|
||||
import type { StoredMessage, MessageFetcher, GatewayCaller } from '../../packages/server/src/services/hermes/context-engine/types'
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────
|
||||
|
||||
function makeMessage(overrides: Partial<StoredMessage> = {}): StoredMessage {
|
||||
return {
|
||||
id: 'msg-1',
|
||||
roomId: 'room-1',
|
||||
senderId: 'user-1',
|
||||
senderName: 'Alice',
|
||||
content: 'Hello world',
|
||||
timestamp: 1000,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeMessages(count: number, roomId = 'room-1', startTimestamp = 1000): StoredMessage[] {
|
||||
return Array.from({ length: count }, (_, i) => makeMessage({
|
||||
id: `msg-${i}`,
|
||||
roomId,
|
||||
senderId: i % 3 === 0 ? 'agent-socket' : `user-${i}`,
|
||||
senderName: i % 3 === 0 ? 'Claude' : `User${i}`,
|
||||
content: `Message ${i} with some content`,
|
||||
timestamp: startTimestamp + i * 1000,
|
||||
}))
|
||||
}
|
||||
|
||||
// ─── SummaryCache ─────────────────────────────────────────────
|
||||
|
||||
describe('SummaryCache', () => {
|
||||
it('stores and retrieves entries', () => {
|
||||
const cache = new SummaryCache(60_000)
|
||||
cache.set('room-1', {
|
||||
summary: 'Summary text',
|
||||
lastMessageId: 'msg-10',
|
||||
lastMessageTimestamp: 5000,
|
||||
createdAt: Date.now(),
|
||||
})
|
||||
const entry = cache.get('room-1')
|
||||
expect(entry).toBeDefined()
|
||||
expect(entry!.summary).toBe('Summary text')
|
||||
})
|
||||
|
||||
it('returns undefined for expired entries', () => {
|
||||
const cache = new SummaryCache(100) // 100ms TTL
|
||||
cache.set('room-1', {
|
||||
summary: 'Old summary',
|
||||
lastMessageId: 'msg-5',
|
||||
lastMessageTimestamp: 5000,
|
||||
createdAt: Date.now() - 200, // created 200ms ago
|
||||
})
|
||||
expect(cache.get('room-1')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('invalidates entries for a room', () => {
|
||||
const cache = new SummaryCache(60_000)
|
||||
cache.set('room-1', { summary: 'A', lastMessageId: 'msg-1', lastMessageTimestamp: 1000, createdAt: Date.now() })
|
||||
cache.set('room-2', { summary: 'C', lastMessageId: 'msg-3', lastMessageTimestamp: 3000, createdAt: Date.now() })
|
||||
|
||||
cache.invalidate('room-1')
|
||||
expect(cache.get('room-1')).toBeUndefined()
|
||||
expect(cache.get('room-2')).toBeDefined()
|
||||
})
|
||||
|
||||
it('enforces max entry limit', () => {
|
||||
const cache = new SummaryCache(60_000)
|
||||
// Fill cache beyond limit (internal MAX_ENTRIES = 200)
|
||||
for (let i = 0; i < 210; i++) {
|
||||
cache.set(`room-${i}`, {
|
||||
summary: `Summary ${i}`,
|
||||
lastMessageId: `msg-${i}`,
|
||||
lastMessageTimestamp: i * 1000,
|
||||
createdAt: Date.now() - (210 - i), // earlier entries have older createdAt
|
||||
})
|
||||
}
|
||||
// Cache should not exceed 200 entries
|
||||
expect(cache.size).toBeLessThanOrEqual(200)
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Prompts ──────────────────────────────────────────────────
|
||||
|
||||
describe('prompts', () => {
|
||||
it('builds agent instructions with all fields', () => {
|
||||
const result = buildAgentInstructions({
|
||||
agentName: 'Claude',
|
||||
roomName: 'general',
|
||||
agentDescription: 'AI coding assistant',
|
||||
memberNames: ['Alice', 'Bob', 'Claude'],
|
||||
members: [
|
||||
{ userId: 'u1', name: 'Alice', description: 'dev' },
|
||||
{ userId: 'u2', name: 'Bob', description: 'designer' },
|
||||
{ userId: 'u3', name: 'Claude', description: '' },
|
||||
],
|
||||
})
|
||||
expect(result).toContain('"Claude"')
|
||||
expect(result).toContain('general')
|
||||
expect(result).toContain('AI coding assistant')
|
||||
expect(result).toContain('Alice')
|
||||
expect(result).toContain('Bob')
|
||||
expect(result).toContain('@Claude')
|
||||
})
|
||||
|
||||
it('builds agent instructions with empty member list', () => {
|
||||
const result = buildAgentInstructions({
|
||||
agentName: 'GPT',
|
||||
roomName: 'dev',
|
||||
agentDescription: 'Helper',
|
||||
memberNames: [],
|
||||
members: [],
|
||||
})
|
||||
expect(result).toContain('"GPT"')
|
||||
expect(result).toContain('未知')
|
||||
})
|
||||
|
||||
it('builds agent instructions using memberNames when members is empty', () => {
|
||||
const result = buildAgentInstructions({
|
||||
agentName: 'GPT',
|
||||
roomName: 'dev',
|
||||
agentDescription: 'Helper',
|
||||
memberNames: ['Alice', 'Bob'],
|
||||
members: [],
|
||||
})
|
||||
expect(result).toContain('Alice')
|
||||
expect(result).toContain('Bob')
|
||||
})
|
||||
|
||||
it('builds summarization system prompt', () => {
|
||||
const result = buildSummarizationSystemPrompt()
|
||||
expect(result).toContain('摘要')
|
||||
})
|
||||
|
||||
it('builds full summary prompt', () => {
|
||||
const result = buildFullSummaryPrompt()
|
||||
expect(result).toContain('摘要')
|
||||
})
|
||||
|
||||
it('builds incremental update prompt', () => {
|
||||
const result = buildIncrementalUpdatePrompt()
|
||||
expect(result).toContain('更新')
|
||||
})
|
||||
})
|
||||
|
||||
// ─── ContextEngine.buildContext ────────────────────────────────
|
||||
|
||||
describe('ContextEngine.buildContext', () => {
|
||||
let mockSummarize = vi.fn().mockResolvedValue({ summary: 'Summary of conversation.', sessionId: 'comp-1' })
|
||||
const mockGatewayCaller: GatewayCaller = {
|
||||
summarize: mockSummarize,
|
||||
}
|
||||
|
||||
let mockFetcher: MessageFetcher
|
||||
let engine: ContextEngine
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockFetcher = {
|
||||
getMessages: vi.fn().mockReturnValue([]),
|
||||
getContextSnapshot: vi.fn().mockReturnValue(null),
|
||||
saveContextSnapshot: vi.fn(),
|
||||
deleteContextSnapshot: vi.fn(),
|
||||
}
|
||||
engine = new ContextEngine({
|
||||
config: { maxHistoryTokens: 4000, tailMessageCount: 10, triggerTokens: 100_000, charsPerToken: 4, summarizationTimeoutMs: 30_000 },
|
||||
messageFetcher: mockFetcher,
|
||||
gatewayCaller: { summarize: mockSummarize },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns all messages as history when under threshold', async () => {
|
||||
const messages = makeMessages(10) // 10 messages, under trigger threshold
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
const result = await engine.buildContext({
|
||||
roomId: 'room-1',
|
||||
agentId: 'agent-1',
|
||||
agentName: 'Claude',
|
||||
agentDescription: 'Helper',
|
||||
agentSocketId: 'agent-socket',
|
||||
roomName: 'general',
|
||||
memberNames: ['Alice'],
|
||||
members: [{ userId: 'u1', name: 'Alice', description: '' }],
|
||||
upstream: 'http://localhost:8642',
|
||||
apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
})
|
||||
|
||||
expect(result.meta.totalMessages).toBe(10)
|
||||
expect(result.meta.compressed).toBe(false)
|
||||
expect(result.conversationHistory).toHaveLength(10)
|
||||
expect(result.instructions).toContain('Claude')
|
||||
// No LLM call for short conversations
|
||||
expect(mockSummarize).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('splits into head/tail and compresses middle when over threshold', async () => {
|
||||
const messages = makeMessages(20)
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
const result = await engine.buildContext({
|
||||
roomId: 'room-1',
|
||||
agentId: 'agent-1',
|
||||
agentName: 'Claude',
|
||||
agentDescription: 'Helper',
|
||||
agentSocketId: 'agent-socket',
|
||||
roomName: 'general',
|
||||
memberNames: [],
|
||||
members: [],
|
||||
upstream: 'http://localhost:8642',
|
||||
apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
compression: { triggerTokens: 10 }, // Force compression with tiny threshold
|
||||
})
|
||||
|
||||
expect(result.meta.totalMessages).toBe(20)
|
||||
expect(result.meta.compressed).toBe(true)
|
||||
expect(mockSummarize).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('uses cache hit when available and no new messages', async () => {
|
||||
const messages = makeMessages(20)
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
// First call — creates snapshot (with forced compression)
|
||||
await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
compression: { triggerTokens: 10 },
|
||||
})
|
||||
|
||||
// Verify snapshot was saved
|
||||
expect(mockFetcher.saveContextSnapshot).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Simulate that the snapshot now exists in storage
|
||||
const savedSnapshot = mockFetcher.saveContextSnapshot.mock.calls[0]
|
||||
mockFetcher.getContextSnapshot = vi.fn().mockReturnValue({
|
||||
roomId: 'room-1',
|
||||
summary: savedSnapshot[1],
|
||||
lastMessageId: savedSnapshot[2],
|
||||
lastMessageTimestamp: savedSnapshot[3],
|
||||
updatedAt: Date.now(),
|
||||
})
|
||||
|
||||
// Second call — cache hit (snapshot exists, same messages)
|
||||
const result2 = await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
})
|
||||
|
||||
expect(result2.meta.hadSnapshot).toBe(true)
|
||||
// Only one LLM call (from the first buildContext)
|
||||
expect(mockSummarize).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does incremental update when cache hit with new messages', async () => {
|
||||
const messages = makeMessages(20)
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
// First call — full compression (with forced compression)
|
||||
await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
compression: { triggerTokens: 10 },
|
||||
})
|
||||
|
||||
// Simulate that the snapshot now exists in storage
|
||||
const savedSnapshot = mockFetcher.saveContextSnapshot.mock.calls[0]
|
||||
mockFetcher.getContextSnapshot = vi.fn().mockReturnValue({
|
||||
roomId: 'room-1',
|
||||
summary: savedSnapshot[1],
|
||||
lastMessageId: savedSnapshot[2],
|
||||
lastMessageTimestamp: savedSnapshot[3],
|
||||
updatedAt: Date.now(),
|
||||
})
|
||||
|
||||
expect(mockSummarize).toHaveBeenCalledTimes(1)
|
||||
// First call: no previousSummary (4 args, index 4 is undefined)
|
||||
const firstCallArgs = mockSummarize.mock.calls[0]
|
||||
expect(firstCallArgs[4]).toBeUndefined() // previousSummary not passed
|
||||
|
||||
// Insert a new message
|
||||
const middleInsert = makeMessage({
|
||||
id: 'msg-new', roomId: 'room-1', senderId: 'user-99',
|
||||
senderName: 'NewUser', content: 'New middle message', timestamp: 12000,
|
||||
})
|
||||
const updatedMessages = [...messages.slice(0, 9), middleInsert, ...messages.slice(9)]
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(updatedMessages)
|
||||
|
||||
// Second call — incremental update
|
||||
await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: updatedMessages[updatedMessages.length - 1],
|
||||
compression: { triggerTokens: 10 },
|
||||
})
|
||||
|
||||
expect(mockSummarize).toHaveBeenCalledTimes(2)
|
||||
// Second call: has previousSummary
|
||||
const secondCallArgs = mockSummarize.mock.calls[1]
|
||||
expect(secondCallArgs[4]).toBe('Summary of conversation.')
|
||||
})
|
||||
|
||||
it('falls back to no-summary on LLM failure', async () => {
|
||||
mockSummarize.mockRejectedValue(new Error('LLM timeout'))
|
||||
|
||||
const messages = makeMessages(20)
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
const result = await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
compression: { triggerTokens: 10 },
|
||||
})
|
||||
|
||||
// Should not throw, and should still return history
|
||||
expect(result.conversationHistory.length).toBeGreaterThan(0)
|
||||
// No summary pair in the output
|
||||
expect(result.conversationHistory[0]?.content).not.toContain('Previous conversation summary')
|
||||
})
|
||||
|
||||
it('trims tail when over token budget', async () => {
|
||||
const engine = new ContextEngine({
|
||||
config: {
|
||||
maxHistoryTokens: 50, // very small budget
|
||||
tailMessageCount: 10,
|
||||
triggerTokens: 10, // force compression
|
||||
charsPerToken: 4,
|
||||
summarizationTimeoutMs: 30_000,
|
||||
},
|
||||
messageFetcher: mockFetcher,
|
||||
gatewayCaller: { summarize: mockSummarize },
|
||||
})
|
||||
|
||||
const messages = makeMessages(20)
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
const result = await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
})
|
||||
|
||||
// History should be trimmed to fit within 50 tokens
|
||||
const totalChars = result.conversationHistory.reduce((sum, m) => sum + m.content.length, 0)
|
||||
const estimatedTokens = Math.ceil(totalChars / 4)
|
||||
expect(estimatedTokens).toBeLessThanOrEqual(50)
|
||||
})
|
||||
|
||||
it('maps agent messages to assistant role', async () => {
|
||||
const messages = [
|
||||
makeMessage({ senderId: 'user-1', senderName: 'Alice', content: 'Hello', timestamp: 1000 }),
|
||||
makeMessage({ senderId: 'agent-socket', senderName: 'Claude', content: 'Hi there', timestamp: 2000 }),
|
||||
]
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
const result = await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
})
|
||||
|
||||
// First message from user → 'user' role with name prefix
|
||||
expect(result.conversationHistory[0].role).toBe('user')
|
||||
expect(result.conversationHistory[0].content).toContain('[Alice]')
|
||||
|
||||
// Second message from agent → 'assistant' role, no prefix
|
||||
expect(result.conversationHistory[1].role).toBe('assistant')
|
||||
expect(result.conversationHistory[1].content).toBe('Hi there')
|
||||
})
|
||||
|
||||
it('maps other messages to user role with name prefix', async () => {
|
||||
const messages = [
|
||||
makeMessage({ senderId: 'user-2', senderName: 'Bob', content: 'Hey', timestamp: 1000 }),
|
||||
]
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
const result = await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
})
|
||||
|
||||
expect(result.conversationHistory[0].role).toBe('user')
|
||||
expect(result.conversationHistory[0].content).toBe('[Bob]: Hey')
|
||||
})
|
||||
|
||||
it('generates instructions with agent identity', async () => {
|
||||
const messages = makeMessages(1)
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
const result = await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: 'Code helper', agentSocketId: 'agent-socket', roomName: 'dev',
|
||||
memberNames: ['Alice', 'Bob'],
|
||||
members: [
|
||||
{ userId: 'u1', name: 'Alice', description: 'dev' },
|
||||
{ userId: 'u2', name: 'Bob', description: 'designer' },
|
||||
],
|
||||
upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[0],
|
||||
})
|
||||
|
||||
expect(result.instructions).toContain('"Claude"')
|
||||
expect(result.instructions).toContain('Code helper')
|
||||
expect(result.instructions).toContain('dev')
|
||||
expect(result.instructions).toContain('Alice')
|
||||
})
|
||||
|
||||
it('invalidates room cache', async () => {
|
||||
// Create a snapshot via the fetcher mock
|
||||
mockFetcher.getContextSnapshot = vi.fn().mockReturnValue({
|
||||
roomId: 'room-1',
|
||||
summary: 'Test',
|
||||
lastMessageId: 'msg-10',
|
||||
lastMessageTimestamp: 1000,
|
||||
updatedAt: Date.now(),
|
||||
})
|
||||
|
||||
const messages = makeMessages(5)
|
||||
mockFetcher.getMessages = vi.fn().mockReturnValue(messages)
|
||||
|
||||
// Build context to create snapshot
|
||||
await engine.buildContext({
|
||||
roomId: 'room-1', agentId: 'agent-1', agentName: 'Claude',
|
||||
agentDescription: '', agentSocketId: 'agent-socket', roomName: 'general',
|
||||
memberNames: [], members: [], upstream: 'http://localhost:8642', apiKey: null,
|
||||
currentMessage: messages[messages.length - 1],
|
||||
})
|
||||
|
||||
// Invalidate
|
||||
engine.invalidateRoom('room-1')
|
||||
expect(mockFetcher.deleteContextSnapshot).toHaveBeenCalledWith('room-1')
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,8 +6,8 @@ const contentAllMock = vi.fn()
|
||||
const likeAllMock = vi.fn()
|
||||
const prepareMock = vi.fn((sql: string) => {
|
||||
if (sql.includes('messages_fts MATCH')) return ({ all: contentAllMock })
|
||||
if (sql.includes('m.content LIKE ?')) return ({ all: likeAllMock })
|
||||
if (sql.includes("LOWER(COALESCE(base.title, '')) LIKE ?")) return ({ all: titleAllMock })
|
||||
if (sql.includes('JOIN messages m') && sql.includes('LIKE')) return ({ all: likeAllMock })
|
||||
if (sql.includes('base.title') && sql.includes('LIKE')) return ({ all: titleAllMock })
|
||||
return ({ all: allMock })
|
||||
})
|
||||
const closeMock = vi.fn()
|
||||
@@ -231,25 +231,25 @@ describe('session DB summaries', () => {
|
||||
expect(rows[1].snippet).toContain('docker')
|
||||
})
|
||||
|
||||
it('falls back to LIKE search when messages_fts is missing for numeric queries', async () => {
|
||||
it('falls back to literal content search for punctuation-only queries instead of unsafe FTS', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('no such table: messages_fts')
|
||||
throw new Error('fts5: syntax error near "."')
|
||||
})
|
||||
likeAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'numeric-1',
|
||||
id: 'dot-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: '',
|
||||
started_at: 1710002800,
|
||||
started_at: 1710004000,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 2,
|
||||
output_tokens: 3,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
@@ -257,42 +257,39 @@ describe('session DB summaries', () => {
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'numeric preview',
|
||||
last_active: 1710002805,
|
||||
matched_message_id: 9,
|
||||
snippet: 'ticket 12345',
|
||||
preview: 'punctuation preview',
|
||||
last_active: 1710004001,
|
||||
matched_message_id: 21,
|
||||
snippet: 'value.with.dot',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('123', undefined, 10)
|
||||
const rows = await mod.searchSessionSummaries('.', undefined, 10)
|
||||
|
||||
expect(likeAllMock).toHaveBeenCalledWith('123', '%123%')
|
||||
expect(contentAllMock).not.toHaveBeenCalled()
|
||||
expect(likeAllMock).toHaveBeenCalled()
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].id).toBe('numeric-1')
|
||||
expect(rows[0].snippet).toContain('123')
|
||||
expect(rows[0].id).toBe('dot-1')
|
||||
})
|
||||
|
||||
it('keeps the source filter when messages_fts is missing for numeric queries', async () => {
|
||||
it('keeps safe dotted queries on the FTS path', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('no such table: messages_fts')
|
||||
})
|
||||
likeAllMock.mockReturnValue([
|
||||
contentAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'numeric-telegram-1',
|
||||
source: 'telegram',
|
||||
id: 'node-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: '',
|
||||
started_at: 1710002850,
|
||||
title: 'Node.js notes',
|
||||
started_at: 1710004500,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 2,
|
||||
output_tokens: 3,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
@@ -300,38 +297,38 @@ describe('session DB summaries', () => {
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'telegram numeric preview',
|
||||
last_active: 1710002855,
|
||||
matched_message_id: 12,
|
||||
snippet: 'telegram 123 body',
|
||||
rank: 0,
|
||||
preview: 'dotted preview',
|
||||
last_active: 1710004501,
|
||||
matched_message_id: 22,
|
||||
snippet: '>>>node.js<<< runtime',
|
||||
rank: 0.2,
|
||||
},
|
||||
])
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('123', 'telegram', 10)
|
||||
const rows = await mod.searchSessionSummaries('node.js', undefined, 10)
|
||||
|
||||
expect(likeAllMock).toHaveBeenCalledWith('telegram', '123', '%123%')
|
||||
expect(contentAllMock).toHaveBeenCalled()
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].source).toBe('telegram')
|
||||
expect(rows[0].id).toBe('numeric-telegram-1')
|
||||
expect(rows[0].id).toBe('node-1')
|
||||
})
|
||||
|
||||
it('preserves title matches when messages_fts is missing for numeric queries', async () => {
|
||||
it('keeps explicit wildcard dotted queries on the FTS path with valid syntax', async () => {
|
||||
titleAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'title-123',
|
||||
id: 'node-wildcard-title-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: 'Issue 123',
|
||||
started_at: 1710002900,
|
||||
title: 'Node.js wildcard notes',
|
||||
started_at: 1710004590,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 2,
|
||||
output_tokens: 3,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
@@ -339,30 +336,27 @@ describe('session DB summaries', () => {
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'title numeric preview',
|
||||
last_active: 1710002910,
|
||||
preview: 'wildcard title preview',
|
||||
last_active: 1710004595,
|
||||
matched_message_id: null,
|
||||
snippet: 'Issue 123',
|
||||
snippet: 'Node.js wildcard notes',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('no such table: messages_fts')
|
||||
})
|
||||
likeAllMock.mockReturnValue([
|
||||
contentAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'content-123',
|
||||
id: 'node-wildcard-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: '',
|
||||
started_at: 1710002890,
|
||||
title: 'Node.js wildcard notes',
|
||||
started_at: 1710004600,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 2,
|
||||
output_tokens: 3,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
@@ -370,26 +364,243 @@ describe('session DB summaries', () => {
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'content numeric preview',
|
||||
last_active: 1710002895,
|
||||
matched_message_id: 10,
|
||||
snippet: 'content 123 body',
|
||||
preview: 'wildcard dotted preview',
|
||||
last_active: 1710004601,
|
||||
matched_message_id: 24,
|
||||
snippet: '>>>node.js<<< runtime',
|
||||
rank: 0.15,
|
||||
},
|
||||
])
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('node.js*', undefined, 10)
|
||||
|
||||
expect(titleAllMock).toHaveBeenCalledWith('%node.js%', 10)
|
||||
expect(contentAllMock).toHaveBeenCalledWith('"node.js"*', 40)
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows[0].id).toBe('node-wildcard-title-1')
|
||||
expect(rows[1].id).toBe('node-wildcard-1')
|
||||
})
|
||||
|
||||
it('keeps quoted wildcard dotted queries on the FTS path with valid syntax', async () => {
|
||||
titleAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'node-quoted-title-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: 'Quoted Node.js wildcard notes',
|
||||
started_at: 1710004640,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: '',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'quoted title preview',
|
||||
last_active: 1710004645,
|
||||
matched_message_id: null,
|
||||
snippet: 'Quoted Node.js wildcard notes',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
contentAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'node-quoted-wildcard-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: 'Quoted Node.js wildcard notes',
|
||||
started_at: 1710004650,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: '',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'quoted wildcard dotted preview',
|
||||
last_active: 1710004651,
|
||||
matched_message_id: 25,
|
||||
snippet: '>>>node.js<<< runtime',
|
||||
rank: 0.12,
|
||||
},
|
||||
])
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('"node.js"*', undefined, 10)
|
||||
|
||||
expect(titleAllMock).toHaveBeenCalledWith('%node.js%', 10)
|
||||
expect(contentAllMock).toHaveBeenCalledWith('"node.js"*', 40)
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows[0].id).toBe('node-quoted-title-1')
|
||||
expect(rows[1].id).toBe('node-quoted-wildcard-1')
|
||||
})
|
||||
|
||||
it('keeps non-ASCII dotted queries on the safe quoted FTS path', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'unicode-dot-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: 'naïve.js note',
|
||||
started_at: 1710004700,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: '',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'unicode dotted preview',
|
||||
last_active: 1710004701,
|
||||
matched_message_id: 23,
|
||||
snippet: 'naïve.js runtime',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('123', undefined, 10)
|
||||
const rows = await mod.searchSessionSummaries('naïve.js', undefined, 10)
|
||||
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows[0].id).toBe('title-123')
|
||||
expect(rows[0].matched_message_id).toBeNull()
|
||||
expect(rows[1].id).toBe('content-123')
|
||||
expect(rows[1].matched_message_id).toBe(10)
|
||||
expect(contentAllMock).toHaveBeenCalledWith('"naïve.js"', 40)
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].id).toBe('unicode-dot-1')
|
||||
})
|
||||
|
||||
it('falls back to LIKE search for CJK queries', async () => {
|
||||
it('escapes LIKE wildcards for literal special-character searches', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
likeAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'percent-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: '100% reproducible',
|
||||
started_at: 1710005000,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: '',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'literal percent preview',
|
||||
last_active: 1710005001,
|
||||
matched_message_id: 31,
|
||||
snippet: '100% reproducible',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('100%', undefined, 10)
|
||||
|
||||
expect(titleAllMock).toHaveBeenCalledWith('%100\\%%', 10)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].id).toBe('percent-1')
|
||||
})
|
||||
|
||||
it('uses literal search for CJK queries even when FTS returns no rows', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockReturnValue([])
|
||||
likeAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'cjk-literal-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: '',
|
||||
started_at: 1710002980,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 2,
|
||||
output_tokens: 3,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: '',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: '中文内容预览',
|
||||
last_active: 1710002985,
|
||||
matched_message_id: 10,
|
||||
snippet: '这里也有记忆断裂',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('记忆断裂', undefined, 10)
|
||||
|
||||
expect(contentAllMock).not.toHaveBeenCalled()
|
||||
expect(likeAllMock).toHaveBeenCalledWith('记忆断裂', '%记忆断裂%', 40)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].id).toBe('cjk-literal-1')
|
||||
})
|
||||
|
||||
it('falls back to LIKE search for CJK queries while preserving title matches', async () => {
|
||||
titleAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'cjk-title-1',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: '记忆断裂标题',
|
||||
started_at: 1710002990,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 2,
|
||||
output_tokens: 2,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: '',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'title preview',
|
||||
last_active: 1710002995,
|
||||
matched_message_id: null,
|
||||
snippet: '记忆断裂标题',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('fts5 tokenizer miss')
|
||||
})
|
||||
@@ -425,12 +636,96 @@ describe('session DB summaries', () => {
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
const rows = await mod.searchSessionSummaries('记忆断裂', undefined, 10)
|
||||
|
||||
expect(likeAllMock).toHaveBeenCalledWith('记忆断裂', '%记忆断裂%')
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(likeAllMock).toHaveBeenCalledWith('记忆断裂', '%记忆断裂%', 40)
|
||||
expect(rows).toHaveLength(2)
|
||||
expect(rows[0].id).toBe('cjk-1')
|
||||
expect(rows[1].id).toBe('cjk-title-1')
|
||||
expect(rows[0].snippet).toContain('记忆断裂')
|
||||
})
|
||||
|
||||
it('does not hide real database failures for safe FTS queries', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('database malformed')
|
||||
})
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
|
||||
await expect(mod.searchSessionSummaries('docker', undefined, 10)).rejects.toThrow(
|
||||
'Failed to search sessions: database malformed',
|
||||
)
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('throws when messages_fts is missing for numeric queries', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('no such table: messages_fts')
|
||||
})
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
|
||||
await expect(mod.searchSessionSummaries('123', undefined, 10)).rejects.toThrow(
|
||||
'Failed to search sessions: no such table: messages_fts',
|
||||
)
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('throws when messages_fts is missing for numeric queries with source filter', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('no such table: messages_fts')
|
||||
})
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
|
||||
await expect(mod.searchSessionSummaries('123', 'telegram', 10)).rejects.toThrow(
|
||||
'Failed to search sessions: no such table: messages_fts',
|
||||
)
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('throws when messages_fts is missing for numeric queries even with title matches', async () => {
|
||||
titleAllMock.mockReturnValue([
|
||||
{
|
||||
id: 'title-123',
|
||||
source: 'cli',
|
||||
user_id: '',
|
||||
model: 'openai/gpt-5.4',
|
||||
title: 'Issue 123',
|
||||
started_at: 1710002900,
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
message_count: 1,
|
||||
tool_call_count: 0,
|
||||
input_tokens: 2,
|
||||
output_tokens: 3,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
reasoning_tokens: 0,
|
||||
billing_provider: '',
|
||||
estimated_cost_usd: 0,
|
||||
actual_cost_usd: null,
|
||||
cost_status: '',
|
||||
preview: 'title numeric preview',
|
||||
last_active: 1710002910,
|
||||
matched_message_id: null,
|
||||
snippet: 'Issue 123',
|
||||
rank: 0,
|
||||
},
|
||||
])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
throw new Error('no such table: messages_fts')
|
||||
})
|
||||
|
||||
const mod = await import('../../packages/server/src/db/hermes/sessions-db')
|
||||
|
||||
await expect(mod.searchSessionSummaries('123', undefined, 10)).rejects.toThrow(
|
||||
'Failed to search sessions: no such table: messages_fts',
|
||||
)
|
||||
expect(likeAllMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not fall back to LIKE when messages_fts is missing for non-numeric queries', async () => {
|
||||
titleAllMock.mockReturnValue([])
|
||||
contentAllMock.mockImplementation(() => {
|
||||
|
||||
@@ -48,6 +48,10 @@ export default defineConfig({
|
||||
'/health': createProxyConfig(),
|
||||
'/upload': createProxyConfig(),
|
||||
'/webhook': createProxyConfig(),
|
||||
'/socket.io': {
|
||||
target: BACKEND,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user