Files
hapi/web/src/chat/presentation.ts
T
weishu f7d161e6cf feat: add api-error event support with folding for retry messages
Introduces support for displaying API error system messages in the web UI with
automatic folding of consecutive retry messages to show only the latest state.
2026-01-05 13:00:25 +08:00

59 lines
2.3 KiB
TypeScript

import type { AgentEvent } from '@/chat/types'
export function formatUnixTimestamp(value: number): string {
const ms = value < 1_000_000_000_000 ? value * 1000 : value
const date = new Date(ms)
if (Number.isNaN(date.getTime())) return String(value)
return date.toLocaleString()
}
export type EventPresentation = {
icon: string | null
text: string
}
export function getEventPresentation(event: AgentEvent): EventPresentation {
if (event.type === 'api-error') {
const { retryAttempt, maxRetries } = event as { retryAttempt: number; maxRetries: number }
if (maxRetries > 0 && retryAttempt >= maxRetries) {
return { icon: '⚠️', text: 'API error: Max retries reached' }
}
if (maxRetries > 0) {
return { icon: '⏳', text: `API error: Retrying (${retryAttempt}/${maxRetries})` }
}
if (retryAttempt > 0) {
return { icon: '⏳', text: 'API error: Retrying...' }
}
return { icon: '⚠️', text: 'API error' }
}
if (event.type === 'switch') {
const mode = event.mode === 'local' ? 'local' : 'remote'
return { icon: '🔄', text: `Switched to ${mode}` }
}
if (event.type === 'title-changed') {
const title = typeof event.title === 'string' ? event.title : ''
return { icon: null, text: title ? `Title changed to "${title}"` : 'Title changed' }
}
if (event.type === 'permission-mode-changed') {
const modeValue = (event as Record<string, unknown>).mode
const mode = typeof modeValue === 'string' ? modeValue : 'default'
return { icon: '🔐', text: `Permission mode: ${mode}` }
}
if (event.type === 'limit-reached') {
const endsAt = typeof event.endsAt === 'number' ? event.endsAt : null
return { icon: '⏳', text: endsAt ? `Usage limit reached until ${formatUnixTimestamp(endsAt)}` : 'Usage limit reached' }
}
if (event.type === 'message') {
return { icon: null, text: typeof event.message === 'string' ? event.message : 'Message' }
}
try {
return { icon: null, text: JSON.stringify(event) }
} catch {
return { icon: null, text: String(event.type) }
}
}
export function renderEventLabel(event: AgentEvent): string {
return getEventPresentation(event).text
}