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:
ekko
2026-04-24 20:41:14 +08:00
committed by GitHub
parent 82965ae6e2
commit ba72264542
47 changed files with 7590 additions and 141 deletions
@@ -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)
if (!ok) {
ctx.status = 500
ctx.body = { error: 'Failed to delete session' }
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(sessionId)
ctx.body = { ok: true }
return
}
deleteUsage(ctx.params.id)
ctx.body = { ok: true }
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) {