Jelajahi Sumber

fix(webui): Chat run-status control — surface cancel errors + show stop earlier

之前 working tree 里积累的 Chat.tsx WIP, 与 deployment_mode 无关, 是对
运行中 run 的取消 + 历史恢复体验的实打实改进。单独成 commit 保持历史
清晰。

## RunStatusControl 改进

- 取消失败不再静默吞掉: 加 cancelling / lastError 两个 state, 非 2xx
  响应或网络异常都在按钮下方红字显示 (HTTP code + body 前 200 字),
  并 console.error。之前 `catch { /* swallow */ }` 让用户点了没反应也
  不知道为什么。
- 即时 UI 反馈: 取消成功后立刻 qc.setQueryData(status='cancelled'),
  不等 5s 轮询; 再用 0.8s / 2.5s / 6s 三次 refetch 验证后端跟上
  (worker 在 claude call 中途时 cancel flag 可能要几秒才被检查)。
- 取消中按钮变 amber + "取消中…" + disabled, 防重复点击。

## Stop 按钮出现时机

- 之前: 只在 message.status==='done' 后才挂 RunStatusControl, 一个跑
  30+ 步还没 emit final 'done' 的 run 在气泡里看不到停止按钮。
- 现在: run_id 一知道 (SSE 'started') 就挂 stop 控件, 与气泡的本地
  done 状态解耦; 组件自己轮询 DB status, 到终态自动隐藏。

## 历史恢复

- 之前: `if (!run.input || !run.output) continue` — running/cancelled/
  failed 这些常常 output 为空的 run 被整条跳过, 硬刷新后正在跑的
  iterate run 直接从 UI 消失。
- 现在: 只要有 input 就渲染, output 为空时按 run.status 合成占位文案
  (⏳ 仍在运行 / 🛑 已取消 / ❌ 失败+error), 让 RunStatusControl 有
  气泡可挂。

## 验证

  $ cd webui && npm run build
  ✓ tsc 0 errors, built in 4.35s

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
kenny67nju 5 bulan lalu
induk
melakukan
376e37499f
1 mengubah file dengan 117 tambahan dan 33 penghapusan
  1. 117 33
      webui/src/pages/Chat.tsx

+ 117 - 33
webui/src/pages/Chat.tsx

@@ -151,6 +151,8 @@ function RunStatusControl({
   agentId: string; runId: string; apiKey: string
 }) {
   const qc = useQueryClient()
+  const [cancelling, setCancelling] = useState(false)
+  const [lastError, setLastError] = useState<string | null>(null)
   const { data, refetch } = useQuery({
     queryKey: ['run-status', agentId, runId],
     queryFn: async () => {
@@ -170,34 +172,76 @@ function RunStatusControl({
     staleTime: 4000,
   })
 
-  if (data !== 'running') return null
+  if (data !== 'running' && !cancelling && !lastError) return null
 
   return (
-    <button
-      onClick={async () => {
-        try {
-          const r = await fetch(
-            `/api/v1/agents/${agentId}/runs/${runId}/cancel`,
-            {
-              method: 'POST',
-              headers: { Authorization: `Bearer ${apiKey}` },
-            },
-          )
-          if (r.ok) {
-            // Quick UI feedback — also re-fetch to flip the badge.
-            await refetch()
-            qc.invalidateQueries({ queryKey: ['runs', agentId] })
+    <div className="flex flex-col gap-1 items-start">
+      <button
+        disabled={cancelling}
+        onClick={async () => {
+          setLastError(null)
+          setCancelling(true)
+          try {
+            const r = await fetch(
+              `/api/v1/agents/${agentId}/runs/${runId}/cancel`,
+              {
+                method: 'POST',
+                headers: { Authorization: `Bearer ${apiKey}` },
+              },
+            )
+            if (!r.ok) {
+              // Surface backend errors (401/404/500) instead of silently
+              // pretending the click did something.
+              let body = ''
+              try { body = await r.text() } catch { /* */ }
+              setLastError(`HTTP ${r.status} ${r.statusText}${body ? ` — ${body.slice(0, 200)}` : ''}`)
+              // eslint-disable-next-line no-console
+              console.error('[cancel] failed', r.status, body)
+            } else {
+              // Immediately force the UI to act as if status==='cancelled' —
+              // don't wait for the 5s poll. We also nuke the cached run-status
+              // and the runs list so other panels re-fetch.
+              qc.setQueryData(['run-status', agentId, runId], 'cancelled')
+              qc.invalidateQueries({ queryKey: ['runs', agentId] })
+              // Then verify backend agrees within a few seconds (the run
+              // sometimes lingers as 'running' if the worker mid-claude-call
+              // hasn't checked the cancel flag yet).
+              setTimeout(() => { refetch() }, 800)
+              setTimeout(() => { refetch() }, 2500)
+              setTimeout(() => { refetch() }, 6000)
+            }
+          } catch (e) {
+            const msg = (e as Error)?.message || String(e)
+            setLastError(`network: ${msg}`)
+            // eslint-disable-next-line no-console
+            console.error('[cancel] threw', e)
+          } finally {
+            setCancelling(false)
           }
-        } catch { /* swallow — keep button clickable */ }
-      }}
-      className="flex items-center gap-1.5 text-xs text-red-700 hover:text-red-900 bg-red-50 hover:bg-red-100 border border-red-200 rounded-lg px-3 py-1.5 transition-colors"
-      title={`此 run 后端仍在运行 — 点击立即终止 (${runId})`}
-    >
-      <Square size={11} />
-      停止此 run
-      <span className="text-red-400 font-mono">{runId.slice(-8)}</span>
-      <span className="ml-1 inline-block w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
-    </button>
+        }}
+        className={clsx(
+          'flex items-center gap-1.5 text-xs border rounded-lg px-3 py-1.5 transition-colors',
+          cancelling
+            ? 'bg-amber-50 border-amber-200 text-amber-700 cursor-wait'
+            : 'bg-red-50 hover:bg-red-100 border-red-200 text-red-700 hover:text-red-900',
+        )}
+        title={`此 run 后端仍在运行 — 点击立即终止 (${runId})`}
+      >
+        <Square size={11} />
+        {cancelling ? '取消中…' : '停止此 run'}
+        <span className={cancelling ? 'text-amber-400 font-mono' : 'text-red-400 font-mono'}>
+          {runId.slice(-8)}
+        </span>
+        {!cancelling && (
+          <span className="ml-1 inline-block w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
+        )}
+      </button>
+      {lastError && (
+        <div className="text-[10px] text-red-600 bg-red-50 border border-red-200 rounded px-2 py-0.5 max-w-md">
+          取消失败:{lastError}
+        </div>
+      )}
+    </div>
   )
 }
 
@@ -243,12 +287,21 @@ function MessageBubble({
           </div>
         )}
 
-        {/* Workspace file panel + Continue button + Stop-if-running */}
+        {/* Stop button — appears as SOON as the run_id is known (SSE
+            'started' event), independent of the message's local 'done'
+            state. Without this, a run that's chugging through 30+ steps
+            without ever emitting a final 'done' shows no in-bubble stop
+            control. The component polls DB status itself and auto-hides
+            when the run reaches a terminal state. */}
+        {!isUser && msg.runId && (
+          <div className="w-full">
+            <RunStatusControl agentId={agentId} runId={msg.runId} apiKey={apiKey} />
+          </div>
+        )}
+
+        {/* Workspace file panel + Continue button — only after run completes */}
         {!isUser && msg.status === 'done' && msg.runId && (
           <div className="space-y-1 w-full">
-            {/* Renders only when run.status==='running' in DB; auto-hides
-                when the run reaches a terminal state. Polls every 5s. */}
-            <RunStatusControl agentId={agentId} runId={msg.runId} apiKey={apiKey} />
             <WorkspacePanel agentId={agentId} runId={msg.runId} apiKey={apiKey} />
             {onContinue && (
               <button
@@ -601,7 +654,8 @@ export default function Chat() {
     const historical: Message[] = []
     const sorted = [...runsData.runs].reverse()
     for (const run of sorted) {
-      if (!run.input || !run.output) continue
+      // Need at least an input to show anything meaningful.
+      if (!run.input) continue
       historical.push({
         id: `hist-user-${run.id}`,
         role: 'user',
@@ -609,11 +663,32 @@ export default function Chat() {
         status: 'done',
         steps: [],
       })
+      // Pick text + UI status from the run's terminal state. In-flight
+      // (`running`) and `cancelled` / `failed` rows often have empty
+      // `output`; we used to skip those entirely, which is why the
+      // current iterate run vanished from the UI after a hard refresh.
+      // Now we synthesize a placeholder so the RunStatusControl button
+      // still has a bubble to attach to.
+      let bubbleText: string
+      let bubbleStatus: MsgStatus = 'done'
+      const out = (run.output || '').slice(0, 4000)
+      if (out) {
+        bubbleText = out
+      } else if (run.status === 'running') {
+        bubbleText = '⏳ 这条 run 仍在后端运行(刷新前没产出最终结果)'
+      } else if (run.status === 'cancelled') {
+        bubbleText = '🛑 这条 run 已被取消,没有最终输出'
+      } else if (run.status === 'failed') {
+        bubbleText = `❌ 这条 run 失败${run.error ? `:${String(run.error).slice(0, 200)}` : ''}`
+        bubbleStatus = 'error'
+      } else {
+        bubbleText = '(无输出)'
+      }
       historical.push({
         id: `hist-asst-${run.id}`,
         role: 'assistant',
-        text: run.output.slice(0, 4000),
-        status: 'done',
+        text: bubbleText,
+        status: bubbleStatus,
         steps: [],
         runId: run.id,
         workspacePath: run.workspace_path ?? undefined,
@@ -791,7 +866,16 @@ export default function Chat() {
             // button can call /cancel even if the user clicks before any
             // other event arrives.
             const rid = payload.run_id as string | undefined
-            if (rid) currentRunId = rid
+            if (rid) {
+              currentRunId = rid
+              // Also stamp it on the assistant message immediately so the
+              // bubble can render the polling Stop button right away —
+              // without this, the button waits for the SSE 'done' event
+              // and would never appear during long in-flight runs.
+              setMessages(prev => prev.map(m =>
+                m.id === assistantId ? { ...m, runId: rid } : m,
+              ))
+            }
 
           } else if (eventType === 'answer') {
             // answer event: backend sends {content, step, tool, duration_ms}