feat: display rate limit warnings instead of raw JSON (#388)

* refactor(web): extract normalizeTimestamp helper in presentation

Extract the shared seconds-vs-milliseconds normalization logic into
a private `normalizeTimestamp()` helper. No behavior change —
`formatUnixTimestamp()` produces identical output.

* refactor(web): return AgentEvent from parseClaudeUsageLimit

Change return type from `number | null` to `AgentEvent | null` so
the caller doesn't need to construct the event object. No behavior
change — the same `limit-reached` event is produced.

* feat(cli): convert rate_limit_event to standardized text format

Parse undocumented Claude `rate_limit_event` JSON in the CLI adapter
layer (AcpMessageHandler) before it reaches the web.

Converted text format (pipe-delimited):
  - "Claude AI usage limit warning|{ts}|{pct}|{rateLimitType}"
  - "Claude AI usage limit reached|{ts}|{rateLimitType}"

Status handling:
  - `allowed_warning` → warning text with utilization and limit type
  - `rejected` → reached text with limit type
  - `allowed` → silently suppressed (noise)
  - unknown statuses → passed through as-is (forward-compatible)

* feat(web): display rate limit warnings with limit type

Parse standardized pipe-delimited text from the CLI adapter into
`limit-warning` and `limit-reached` events, displaying the rate
limit type (5-hour, 7-day) when available.

- `limit-warning`: "⚠️ Usage limit 90% (5-hour) · resets 2:00 PM"
- `limit-reached`: " Usage limit reached (5-hour) until 4/2/2026"
- Backward compatible: `limit-reached` without limitType still works

The `reached` regex uses `(?:\|([^|]*))?$` to optionally match the
limitType field, maintaining compatibility with the existing format.

* refactor(cli): move rate limit parsing out of flushText

Remove rate limit detection from flushText() back to plain buffer
flush. The next commit will re-add parsing at the chunk level
(handleUpdate) where it can intercept before buffer merging.

Includes failing tests that demonstrate the mixed-chunk bug:
when a rate_limit_event chunk arrives in the same turn as normal
text, the JSON leaks into the merged buffer.

* fix(cli): intercept rate_limit_event at chunk level, not flush

Move rate limit detection from flushText() to the agentMessageChunk
handler so it fires before the chunk enters the shared text buffer.

Previously, a rate_limit_event chunk arriving in the same turn as
normal text would merge into bufferedText and leak as raw JSON.
Now the chunk is intercepted individually, the existing buffer is
flushed first (preserving prior text), and the converted message
is emitted separately.

* fix(cli): skip flush when suppressing allowed rate_limit_event

Only flush the text buffer when the parsed event will actually be
displayed. Suppressed events (e.g. status: 'allowed') now return
immediately without flushing, preventing a text → allowed → text
sequence from splitting one answer into two agent-text blocks.

* fix(web): include limitType in limit-reached reconcile key

Without this, reprocessing a message from the old format (no
limitType) to the new typed format reuses the stale block and
the (5-hour)/(7-day) suffix never appears.
This commit is contained in:
Junmo Kim
2026-04-03 08:25:22 +08:00
committed by GitHub
parent 36022a0a1a
commit 00ba610ab0
10 changed files with 575 additions and 16 deletions
+43 -4
View File
@@ -1,12 +1,40 @@
import type { AgentEvent } from '@/chat/types'
export function formatUnixTimestamp(value: number): string {
function normalizeTimestamp(value: number): Date {
const ms = value < 1_000_000_000_000 ? value * 1000 : value
const date = new Date(ms)
return new Date(ms)
}
export function formatUnixTimestamp(value: number): string {
const date = normalizeTimestamp(value)
if (Number.isNaN(date.getTime())) return String(value)
return date.toLocaleString()
}
export function formatResetTime(value: number): string {
const date = normalizeTimestamp(value)
if (Number.isNaN(date.getTime())) return String(value)
const now = new Date()
const isToday = date.getFullYear() === now.getFullYear()
&& date.getMonth() === now.getMonth()
&& date.getDate() === now.getDate()
if (isToday) {
return date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })
}
return date.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })
}
// Known types: five_hour → "5-hour", seven_day → "7-day".
// Unknown types use underscore-to-space fallback (e.g. thirty_day → "thirty day").
function formatLimitType(limitType: string | undefined): string {
if (!limitType) return ''
if (limitType === 'five_hour') return '5-hour'
if (limitType === 'seven_day') return '7-day'
return limitType.replace(/_/g, ' ')
}
function formatDuration(ms: number): string {
const seconds = ms / 1000
if (seconds < 60) return `${seconds.toFixed(1)}s`
@@ -47,9 +75,20 @@ export function getEventPresentation(event: AgentEvent): EventPresentation {
const mode = typeof modeValue === 'string' ? modeValue : 'default'
return { icon: '🔐', text: `Permission mode: ${mode}` }
}
if (event.type === 'limit-warning') {
const ev = event as { utilization?: number; endsAt?: number; limitType?: string }
const pct = Math.round((ev.utilization ?? 0) * 100)
const endsAt = typeof ev.endsAt === 'number' ? ev.endsAt : null
const typeLabel = formatLimitType(ev.limitType)
const suffix = typeLabel ? ` (${typeLabel})` : ''
return { icon: '⚠️', text: endsAt ? `Usage limit ${pct}%${suffix} · resets ${formatResetTime(endsAt)}` : `Usage limit ${pct}%${suffix}` }
}
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' }
const ev = event as { endsAt?: number; limitType?: string }
const endsAt = typeof ev.endsAt === 'number' ? ev.endsAt : null
const typeLabel = formatLimitType(ev.limitType)
const suffix = typeLabel ? ` (${typeLabel})` : ''
return { icon: '⏳', text: endsAt ? `Usage limit reached${suffix} until ${formatUnixTimestamp(endsAt)}` : `Usage limit reached${suffix}` }
}
if (event.type === 'message') {
return { icon: null, text: typeof event.message === 'string' ? event.message : 'Message' }