Files
Hermes-ui/packages/server/src/routes/hermes/terminal.ts
T
ekko ba72264542 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>
2026-04-24 20:41:14 +08:00

328 lines
10 KiB
TypeScript

import { WebSocketServer } from 'ws'
import type { Server as HttpServer } from 'http'
import { accessSync, chmodSync, constants as fsConstants, existsSync } from 'fs'
import { dirname, join } from 'path'
import { getToken } from '../../services/auth'
import { logger } from '../../services/logger'
let pty: any = null
function ensureNodePtySpawnHelperExecutable() {
if (process.platform !== 'darwin') return
try {
const nodePtyRoot = dirname(require.resolve('node-pty/package.json'))
const helperCandidates = [
join(nodePtyRoot, 'build', 'Release', 'spawn-helper'),
join(nodePtyRoot, 'build', 'Debug', 'spawn-helper'),
join(nodePtyRoot, 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper'),
]
for (const helperPath of helperCandidates) {
if (!existsSync(helperPath)) continue
try {
accessSync(helperPath, fsConstants.X_OK)
} catch {
chmodSync(helperPath, 0o755)
logger.debug('Restored execute bit for node-pty helper: %s', helperPath)
}
}
} catch (err: any) {
logger.warn(err, 'Could not normalize node-pty helper permissions')
}
}
try {
ensureNodePtySpawnHelperExecutable()
// eslint-disable-next-line @typescript-eslint/no-require-imports
pty = require('node-pty')
} catch (err: any) {
logger.warn(err, 'node-pty failed to load, terminal feature disabled')
}
// ─── Shell detection ────────────────────────────────────────────
function findShell(): string {
const candidates = [
process.env.SHELL,
'/bin/zsh',
'/bin/bash',
process.platform === 'win32' ? 'powershell.exe' : null,
process.platform === 'win32' ? 'cmd.exe' : null,
].filter(Boolean) as string[]
for (const shell of candidates) {
if (existsSync(shell)) return shell
}
return '/bin/bash'
}
function shellName(shell: string): string {
return shell.split('/').pop() || 'shell'
}
// ─── Session types ──────────────────────────────────────────────
interface PtySession {
id: string
pty: { pid: number; onData: (cb: (data: string) => void) => void; onExit: (cb: (e: { exitCode: number }) => void) => void; write: (data: string) => void; kill: (signal?: string) => void; resize: (cols: number, rows: number) => void }
shell: string
pid: number
createdAt: number
}
interface Connection {
sessions: Map<string, PtySession>
activeSessionId: string | null
outputBuffers: Map<string, string[]>
}
// ─── Helpers ────────────────────────────────────────────────────
function generateId(): string {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
}
function createSession(shell: string): PtySession {
const id = generateId()
let ptyProcess: PtySession['pty']
try {
ptyProcess = pty.spawn(shell, [], {
name: 'xterm-color',
cols: 80,
rows: 24,
cwd: process.env.HOME || undefined,
})
} catch (err: any) {
throw new Error(`Failed to spawn shell "${shell}": ${err.message}`)
}
const session: PtySession = {
id,
pty: ptyProcess,
shell,
pid: ptyProcess.pid,
createdAt: Date.now(),
}
return session
}
// ─── WebSocket server setup ─────────────────────────────────────
export function setupTerminalWebSocket(httpServer: HttpServer) {
if (!pty) {
logger.warn('node-pty not available, skipping terminal WebSocket setup')
return
}
const wss = new WebSocketServer({ noServer: true })
const defaultShell = findShell()
httpServer.on('upgrade', async (req, socket, head) => {
const url = new URL(req.url || '', `http://${req.headers.host}`)
if (url.pathname !== '/api/hermes/terminal') {
return
}
// Auth check
const authToken = await getToken()
if (authToken) {
const token = url.searchParams.get('token') || ''
if (token !== authToken) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
socket.destroy()
return
}
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req)
})
})
wss.on('connection', (ws) => {
const conn: Connection = {
sessions: new Map(),
activeSessionId: null,
outputBuffers: new Map(),
}
// ─── PTY output → WebSocket ──────────────────────────────────
function attachPtyOutput(session: PtySession) {
session.pty.onData((data: string) => {
if (ws.readyState !== ws.OPEN) return
if (conn.activeSessionId === session.id) {
ws.send(data)
} else {
// Buffer output for inactive sessions
let buf = conn.outputBuffers.get(session.id)
if (!buf) {
buf = []
conn.outputBuffers.set(session.id, buf)
}
buf.push(data)
// Cap buffer at 1MB to prevent memory issues
if (buf.length > 5000) {
buf.splice(0, buf.length - 5000)
}
}
})
session.pty.onExit(({ exitCode }: { exitCode: number }) => {
conn.outputBuffers.delete(session.id)
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify({ type: 'exited', id: session.id, exitCode }))
}
conn.sessions.delete(session.id)
logger.info('Session %s exited (pid %d, code %d)', session.id, session.pid, exitCode)
})
}
// ─── Message handler ────────────────────────────────────────
ws.on('message', (raw) => {
const msg = Buffer.isBuffer(raw) ? raw.toString('utf8') : String(raw)
// JSON control message
if (msg.charCodeAt(0) === 0x7B) {
try {
const parsed = JSON.parse(msg)
handleControl(parsed)
} catch {
// Not valid JSON, fall through to raw input
writeRaw(msg)
}
return
}
writeRaw(msg)
})
function writeRaw(data: string) {
const session = conn.activeSessionId ? conn.sessions.get(conn.activeSessionId) : null
if (session) {
session.pty.write(data)
}
}
function handleControl(parsed: any) {
switch (parsed.type) {
case 'create': {
const shell = parsed.shell || defaultShell
let session: PtySession
try {
session = createSession(shell)
} catch (err: any) {
ws.send(JSON.stringify({ type: 'error', message: err.message }))
return
}
conn.sessions.set(session.id, session)
conn.activeSessionId = session.id
attachPtyOutput(session)
ws.send(JSON.stringify({
type: 'created',
id: session.id,
pid: session.pid,
shell: shellName(shell),
}))
logger.info('Session created: %s (%s, pid %d)', session.id, shellName(shell), session.pid)
break
}
case 'switch': {
const { sessionId } = parsed
const session = conn.sessions.get(sessionId)
if (!session) {
ws.send(JSON.stringify({ type: 'error', message: 'Session not found' }))
return
}
conn.activeSessionId = sessionId
// Send switched first so frontend mounts the correct terminal
ws.send(JSON.stringify({ type: 'switched', id: sessionId }))
// Then flush buffered output for this session
const buf = conn.outputBuffers.get(sessionId)
if (buf && buf.length > 0) {
for (const chunk of buf) {
ws.send(chunk)
}
conn.outputBuffers.delete(sessionId)
}
logger.debug('Switched to session %s', sessionId)
break
}
case 'close': {
const { sessionId } = parsed
const session = conn.sessions.get(sessionId)
if (!session) return
session.pty.kill()
conn.sessions.delete(sessionId)
conn.outputBuffers.delete(sessionId)
if (conn.activeSessionId === sessionId) {
// Auto-switch to the first remaining session
const remaining = Array.from(conn.sessions.keys())
conn.activeSessionId = remaining.length > 0 ? remaining[0] : null
}
logger.info('Session closed: %s', sessionId)
break
}
case 'resize': {
const session = conn.activeSessionId ? conn.sessions.get(conn.activeSessionId) : null
if (!session) return
const cols = Math.max(1, parsed.cols || 0)
const rows = Math.max(1, parsed.rows || 0)
try { session.pty.resize(cols, rows) } catch { }
break
}
}
}
// ─── Cleanup ────────────────────────────────────────────────
ws.on('close', () => {
for (const session of Array.from(conn.sessions.values())) {
try { session.pty.kill() } catch { }
}
conn.sessions.clear()
logger.info('Connection closed, all sessions killed')
})
ws.on('error', () => {
for (const session of Array.from(conn.sessions.values())) {
try { session.pty.kill() } catch { }
}
conn.sessions.clear()
})
// ─── Auto-create first session ──────────────────────────────
let firstSession: PtySession
try {
firstSession = createSession(defaultShell)
} catch (err: any) {
ws.send(JSON.stringify({ type: 'error', message: err.message }))
logger.error(err, 'Failed to create session')
ws.close()
return
}
conn.sessions.set(firstSession.id, firstSession)
conn.activeSessionId = firstSession.id
attachPtyOutput(firstSession)
ws.send(JSON.stringify({
type: 'created',
id: firstSession.id,
pid: firstSession.pid,
shell: shellName(defaultShell),
}))
logger.info('First session created: %s (%s, pid %d)', firstSession.id, shellName(defaultShell), firstSession.pid)
})
logger.info('WebSocket ready at /terminal (shell: %s, transport: node-pty)', defaultShell)
}