All files / webview/hooks useChatState.ts

74.75% Statements 151/202
61.9% Branches 78/126
58.06% Functions 18/31
76.75% Lines 142/185

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326                  20x 20x 20x 18x 34x   20x       515x 515x 515x 515x   515x 515x       515x                     515x                     515x           515x                 515x                     515x 9x     515x           515x 30x     30x 30x 30x       515x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x           515x 283x 136x 136x 136x 10x 10x 10x 10x     136x 136x 136x 680x 680x         136x           136x   147x 130x 130x 130x 130x 130x 130x 130x     130x 130x 130x 130x 130x 130x 130x 130x   130x 22x 108x 8x 100x 9x 91x 26x 65x                       23x 42x 13x 13x 13x 29x 14x 14x 14x 14x 14x   15x                   15x   103x 103x                   17x 17x           515x 128x   128x 101x                     128x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x     23x 23x 23x       128x 57x 57x 57x 19x 19x                     19x 19x   38x 20x 20x 20x 20x     18x 18x 18x 18x         128x 48x 21x 21x 21x 21x   27x 22x 22x                           515x                  
import { useRef, useState } from 'react'
import { stripAnsi } from '../components/BashResult'
import { isTooManyRequestsError, parseQuotaError } from '../lib/quotaErrors'
import { createToolMessage } from '../lib/toolMessageFormatter'
import type { MessageEntry } from '../lib/types'
import { isHiddenResultTool } from '../lib/utils'
import type { MessageRouter } from './useMessageRouter'
 
export function parseQaItems(content: string): { question: string; answer: string }[] {
  const items: { question: string; answer: string }[] = []
  const answerSection = content.match(/^User answered:(.*)/s)
  if (answerSection) {
    const pairs = answerSection[1].matchAll(/"([^"]+)"\s*=\s*"([^"]+)"/g)
    for (const [, q, a] of pairs) items.push({ question: q, answer: a })
  }
  return items
}
 
export function useChatState(router: MessageRouter) {
  const [messages, setMessages] = useState<MessageEntry[]>([])
  const [streamingText, setStreamingText] = useState('')
  const [streamingThinking, setStreamingThinking] = useState('')
  const [isRunning, setIsRunning] = useState(false)
 
  const streamingTextRef = useRef('')
  const streamingThinkingRef = useRef('')
 
  // ── Session lifecycle ─────────────────────────────────────────────
 
  router.register('session', (_msg) => {
    setMessages((prev) => {
      const lastSkillIdx = [...prev]
        .reverse()
        .findIndex((m) => m.role === 'skill-imported' && (m as { restartState?: string }).restartState === 'restarting')
      if (lastSkillIdx === -1) return prev
      const idx = prev.length - 1 - lastSkillIdx
      return prev.map((m, i) => (i === idx ? { ...m, restartState: 'active' } : m))
    })
  })
 
  router.register('agentRestarting', () => {
    setMessages((prev) => {
      const lastSkillIdx = [...prev]
        .reverse()
        .findIndex((m) => m.role === 'skill-imported' && !(m as { restartState?: string }).restartState)
      if (lastSkillIdx === -1) return prev
      const idx = prev.length - 1 - lastSkillIdx
      return prev.map((m, i) => (i === idx ? { ...m, restartState: 'restarting' } : m))
    })
  })
 
  router.register('skillUploaded', (msg) => {
    setMessages((prev) => [...prev, { role: 'skill-imported', skillName: msg.skillName as string }])
  })
 
  // ── Conversation load/switch ──────────────────────────────────────
 
  router.register('conversationLoaded', (msg) => {
    setMessages(msg.messages as MessageEntry[])
    setStreamingText('')
    setStreamingThinking('')
    streamingTextRef.current = ''
    streamingThinkingRef.current = ''
    setIsRunning(false)
  })
 
  router.register('conversationSwitched', () => {
    setMessages([])
    setStreamingText('')
    setStreamingThinking('')
    streamingTextRef.current = ''
    streamingThinkingRef.current = ''
    setIsRunning(false)
  })
 
  // ── Status ────────────────────────────────────────────────────────
 
  router.register('status', (msg) => {
    Eif (msg.status === 'running') setIsRunning(true)
  })
 
  router.register('userMessage', () => {
    setIsRunning(true)
  })
 
  // ── Streaming ─────────────────────────────────────────────────────
 
  router.register('delta', (msg) => {
    Iif (msg.blockType === 'thinking' && msg.field === 'thinking') {
      streamingThinkingRef.current += msg.content as string
      setStreamingThinking(streamingThinkingRef.current)
    E} else if (msg.blockType === 'text' && msg.field === 'text') {
      streamingTextRef.current += msg.content as string
      setStreamingText(streamingTextRef.current)
    }
  })
 
  router.register('assistant', () => {
    const thinking = streamingThinkingRef.current
    const text = streamingTextRef.current
    streamingThinkingRef.current = ''
    streamingTextRef.current = ''
    setStreamingText('')
    setStreamingThinking('')
    setMessages((prev) => {
      const next = [...prev]
      Iif (thinking) next.push({ role: 'thinking', content: thinking })
      Eif (text) next.push({ role: 'assistant', content: text })
      return next
    })
  })
 
  // ── Tool ──────────────────────────────────────────────────────────
 
  router.register('tool', (msg) => {
    if (msg.status === 'running') {
      const input = msg.input as Record<string, unknown>
      const toolMessage = createToolMessage(msg.name as string, msg.toolUseId as string, input)
      if (msg.name === 'FileEdit' || msg.name === 'Edit') {
        const oldString = String(input.old_string ?? '')
        const newString = String(input.new_string ?? '')
        const totalLines = oldString.split('\n').length + newString.split('\n').length
        if (totalLines > 6) toolMessage.diffAutoOpened = true
      }
 
      setMessages((prev) => {
        let promptIdx = -1
        for (let i = prev.length - 1; i >= 0; i--) {
          const m = prev[i]
          Iif (m.role === 'tool' && !m.toolUseId && m.summary === toolMessage.summary) {
            promptIdx = i
            break
          }
        }
        Iif (promptIdx !== -1) {
          const updated = [...prev]
          const entry = updated[promptIdx]
          if (entry.role === 'tool') updated[promptIdx] = { ...entry, toolUseId: msg.toolUseId as string }
          return updated
        }
        return [...prev, toolMessage]
      })
    } else if (msg.status === 'done') {
      setMessages((prev) => {
        let idx = -1
        for (let i = prev.length - 1; i >= 0; i--) {
          const m = prev[i]
          Eif (m.role === 'tool' && m.toolUseId === msg.toolUseId) {
            idx = i
            break
          }
        }
        const lastMsg = prev[prev.length - 1]
        const lastTool = lastMsg?.role === 'tool' ? lastMsg : null
        const entry = idx !== -1 ? prev[idx] : lastTool && !lastTool.result ? lastTool : null
        const entryIdx = idx !== -1 ? idx : prev.length - 1
        Eif (entry?.role === 'tool') {
          const updated = [...prev]
          const content = msg.content as string
          const isError = msg.isError as boolean
          let result: string | null
          if (['FileRead', 'Edit', 'FileEdit', 'Write', 'FileWrite', 'WebFetch'].includes(entry.name)) {
            result = null
          } else if (entry.name === 'Glob' && !isError) {
            result = content
          } else if (entry.name === 'Grep' && !isError) {
            result = content
          } else if (entry.name === 'Bash') {
            result = stripAnsi(content).slice(0, 5000)
          } else if (
            [
              'TodoWrite',
              'Skill',
              'EnterPlanMode',
              'ExitPlanMode',
              'mcp__ide-vs-code__build_app',
              'build_app',
              'mcp__ide-vs-code__get_problems',
              'get_problems',
            ].includes(entry.name)
          ) {
            result = null
          } else if (isHiddenResultTool(entry.name)) {
            result = null
            updated[entryIdx] = { ...entry, result, isError, apiResult: content.slice(0, 300) }
            return updated
          } else if (entry.name === 'AskUserQuestion' && !isError) {
            result = null
            const qaItems = parseQaItems(content)
            Eif (qaItems.length > 0) {
              updated[entryIdx] = { ...entry, result, isError, qaItems }
              return updated
            }
          I} else if ((entry.name === 'mcp__ide-vs-code__get_problems' || entry.name === 'get_problems') && !isError) {
            result = null
            try {
              const parsed = JSON.parse(content)
              if (Array.isArray(parsed)) {
                updated[entryIdx] = { ...entry, result, isError, problems: parsed }
                return updated
              }
            } catch {}
          } else {
            result = content.slice(0, 500)
          }
          updated[entryIdx] = { ...entry, result, isError }
          return updated
        }
        return [
          ...prev,
          {
            role: (msg.isError ? 'error' : 'info') as 'error' | 'info',
            content: (msg.content as string).slice(0, 500),
          },
        ]
      })
    E} else if (msg.status === 'error') {
      setMessages((prev) => [...prev, { role: 'error', content: `${msg.name}: ${msg.message}` }])
    }
  })
 
  // ── Result ────────────────────────────────────────────────────────
 
  router.register('result', (msg) => {
    setIsRunning(false)
 
    const appendUsage = (next: MessageEntry[], usage?: Record<string, unknown>) => {
      Iif (usage) {
        next.push({
          role: 'token-stats',
          inputTokens: usage.inputTokens as number,
          outputTokens: usage.outputTokens as number,
          bzTokens: usage.bzTokens as number,
          interactionCount: usage.interactionCount as number,
        })
      }
    }
 
    if (msg.status === 'aborted') {
      const thinking = streamingThinkingRef.current
      const text = streamingTextRef.current
      streamingThinkingRef.current = ''
      streamingTextRef.current = ''
      setStreamingThinking('')
      setStreamingText('')
      setMessages((prev) => {
        const next = [...prev]
        Iif (thinking) next.push({ role: 'thinking', content: thinking })
        Eif (text) next.push({ role: 'assistant', content: text })
        const last = next[next.length - 1]
        Iif (last?.role === 'tool' && !last.result) {
          next[next.length - 1] = { ...last, result: 'Tool interrupted', isError: true }
        }
        next.push({ role: 'info', content: 'Interrupted' })
        appendUsage(next, msg.usage as Record<string, unknown> | undefined)
        return next
      })
    }
 
    if (msg.status === 'error') {
      const error = msg.error as string
      const quota = parseQuotaError(error)
      if (quota) {
        setMessages((prev) => {
          const next: MessageEntry[] = [
            ...prev,
            {
              role: 'quota-error',
              kind: quota.kind,
              used: quota.used,
              limit: quota.limit,
              window: quota.window,
              resetAt: quota.resetAt?.toISOString() ?? null,
            },
          ]
          appendUsage(next, msg.usage as Record<string, unknown> | undefined)
          return next
        })
      } else if (isTooManyRequestsError(error)) {
        setMessages((prev) => {
          const next: MessageEntry[] = [...prev, { role: 'unavailable-error' }]
          appendUsage(next, msg.usage as Record<string, unknown> | undefined)
          return next
        })
      } else {
        setMessages((prev) => {
          const next: MessageEntry[] = [...prev, { role: 'error', content: error }]
          appendUsage(next, msg.usage as Record<string, unknown> | undefined)
          return next
        })
      }
    }
 
    if (msg.status === 'success') {
      if (msg.output) {
        setMessages((prev) => {
          const next: MessageEntry[] = [...prev, { role: 'info', content: msg.output as string }]
          appendUsage(next, msg.usage as Record<string, unknown> | undefined)
          return next
        })
      } else if (msg.usage) {
        const usage = msg.usage as Record<string, unknown>
        setMessages((prev) => [
          ...prev,
          {
            role: 'token-stats',
            inputTokens: usage.inputTokens as number,
            outputTokens: usage.outputTokens as number,
            bzTokens: usage.bzTokens as number,
            interactionCount: usage.interactionCount as number,
          },
        ])
      }
    }
  })
 
  return {
    messages,
    setMessages,
    streamingText,
    streamingThinking,
    isRunning,
    setIsRunning,
  }
}