diff --git a/apps/web/package.json b/apps/web/package.json index 1c843a8..a352b0a 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -10,13 +10,15 @@ }, "dependencies": { "@wishforge/contracts": "*", + "jose": "^6.1.3", + "lucide-react": "^0.577.0", "next": "^16.1.6", "react": "^19.2.4", "react-dom": "^19.2.4", - "lucide-react": "^0.577.0", - "swr": "^2.4.1", - "jose": "^6.1.3", - "server-only": "^0.0.1" + "react-markdown": "^10.1.0", + "remark-gfm": "^4.0.1", + "server-only": "^0.0.1", + "swr": "^2.4.1" }, "devDependencies": { "@types/node": "^24.0.0", diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 6f8d409..1fd6e76 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -3408,7 +3408,7 @@ fieldset:disabled label { .copilot-welcome { text-align: center; color: var(--muted); - padding: 30px 16px 12px; + padding: 24px 16px 40px; } .copilot-welcome-icon { display: inline-flex; @@ -3667,6 +3667,7 @@ fieldset:disabled label { .copilot-welcome .copilot-quick-replies { justify-content: center; margin-top: 14px; + margin-bottom: 24px; } .copilot-thinking { margin-bottom: 8px; @@ -3910,6 +3911,404 @@ fieldset:disabled label { .copilot-input-notice { color: #9d343c; } + +/* Copilot Markdown Styling */ +.copilot-md { + font-size: 13px; + line-height: 1.6; + color: var(--wf-text-body, #334155); +} +.copilot-md p { + margin: 0 0 8px; +} +.copilot-md p:last-child { + margin-bottom: 0; +} +.copilot-md ul, +.copilot-md ol { + margin: 4px 0 8px 18px; + padding: 0; +} +.copilot-md li { + margin-bottom: 3px; +} +.copilot-md code { + font-family: var(--font-mono, 'JetBrains Mono', monospace); + font-size: 11.5px; + background: var(--wf-bg-subtle, #f1f5f9); + padding: 2px 5px; + border-radius: 4px; + color: #0f766e; +} +.copilot-md pre { + background: #0f172a; + color: #f8fafc; + padding: 10px 12px; + border-radius: 6px; + overflow-x: auto; + margin: 8px 0; +} +.copilot-md pre code { + background: transparent; + color: inherit; + padding: 0; +} +.copilot-md table { + width: 100%; + border-collapse: collapse; + margin: 8px 0; + font-size: 12px; +} +.copilot-md th, +.copilot-md td { + border: 1px solid var(--wf-border-subtle, #e2e8f0); + padding: 4px 8px; + text-align: left; +} +.copilot-md th { + background: var(--wf-bg-subtle, #f1f5f9); + font-weight: 600; +} + +/* Sources Meta */ +.copilot-sources-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 6px; +} +.copilot-sources-meta { + font-size: 11px; + color: var(--wf-text-muted, #64748b); + font-weight: normal; +} +.copilot-source-num { + font-weight: 600; + color: #0f766e; + margin-right: 2px; +} + +/* DiagnosisCard */ +.copilot-diagnosis-card { + margin-top: 10px; + border-radius: 8px; + border: 1px solid var(--wf-border-subtle, #e2e8f0); + background: #fff; + padding: 12px 14px; + font-size: 12px; +} +.copilot-diagnosis-card.is-problem { + border-color: #fecaca; + background: #fffafa; +} +.copilot-diagnosis-card.is-expected { + border-color: #bbf7d0; + background: #fbfdfb; +} +.copilot-diagnosis-card.is-insufficient { + border-color: #fde68a; + background: #fffdf7; +} +.copilot-diagnosis-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 10px; + padding-bottom: 6px; + border-bottom: 1px solid #f1f5f9; +} +.copilot-diagnosis-title { + display: flex; + align-items: center; + gap: 6px; + color: #0f172a; +} +.copilot-verdict-badge { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 11px; + font-weight: 600; + padding: 2px 7px; + border-radius: 999px; +} +.copilot-verdict-badge.problem { + background: #fee2e2; + color: #b91c1c; +} +.copilot-verdict-badge.expected { + background: #dcfce7; + color: #15803d; +} +.copilot-verdict-badge.insufficient { + background: #fef3c7; + color: #b45309; +} +.copilot-diagnosis-section { + margin-bottom: 8px; +} +.copilot-diagnosis-section h4 { + margin: 0 0 4px; + font-size: 11px; + font-weight: 600; + color: #64748b; + text-transform: uppercase; + letter-spacing: 0.5px; +} +.copilot-facts-list, +.copilot-hypotheses-list, +.copilot-missing-list { + margin: 0; + padding: 0; + list-style: none; +} +.copilot-facts-list li { + display: flex; + align-items: baseline; + gap: 6px; + margin-bottom: 5px; + line-height: 1.5; +} +.copilot-fact-bullet { + color: #0f766e; + font-weight: bold; +} +.copilot-fact-text { + flex: 1; +} +.copilot-evidence-chip { + display: inline-block; + font-size: 10.5px; + padding: 1px 6px; + border-radius: 4px; + white-space: nowrap; +} +.copilot-evidence-chip.is-available { + background: #f0fdfa; + color: #0f766e; + border: 1px solid #ccfbf1; +} +.copilot-evidence-chip.is-unavailable { + background: #f1f5f9; + color: #94a3b8; + border: 1px solid #e2e8f0; +} +.copilot-hypotheses-list li { + display: flex; + align-items: baseline; + justify-content: space-between; + margin-bottom: 4px; + color: #475569; +} +.copilot-confidence-tag { + font-size: 10px; + padding: 1px 5px; + border-radius: 3px; + background: #f1f5f9; + color: #64748b; +} +.copilot-confidence-tag.high { + background: #e0f2fe; + color: #0369a1; +} +.copilot-missing-list li { + color: #b45309; + font-size: 11.5px; + margin-bottom: 3px; +} +.copilot-diagnosis-empty { + color: #94a3b8; + font-size: 11px; + margin: 4px 0 8px; +} +.copilot-diagnosis-actions { + display: flex; + gap: 8px; + margin-top: 10px; + padding-top: 8px; + border-top: 1px dashed #e2e8f0; +} + +/* Tool Steps Progression */ +.copilot-steps-container { + margin-bottom: 8px; + background: #f8fafc; + border: 1px solid #e2e8f0; + border-radius: 6px; + overflow: hidden; + font-size: 11.5px; +} +.copilot-steps-bar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 6px 10px; + cursor: pointer; + user-select: none; +} +.copilot-steps-summary { + display: flex; + align-items: center; + gap: 6px; + color: #334155; +} +.copilot-steps-count { + color: #94a3b8; +} +.copilot-spin { + animation: copilot-spin 1s linear infinite; + color: #0f766e; +} +@keyframes copilot-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} +.copilot-success-icon { + color: #15803d; +} +.copilot-steps-toggle { + background: transparent; + border: none; + color: #64748b; + cursor: pointer; + padding: 0; + display: flex; + align-items: center; +} +.copilot-steps-list { + margin: 0; + padding: 6px 10px; + border-top: 1px solid #e2e8f0; + background: #fff; + list-style: none; +} +.copilot-step-item { + display: flex; + align-items: center; + gap: 6px; + padding: 3px 0; + color: #475569; +} +.copilot-step-ok { + color: #15803d; +} +.copilot-step-missing { + color: #b45309; +} +.copilot-step-failed { + color: #b91c1c; +} +.copilot-step-missing-tag { + font-size: 9.5px; + padding: 0 4px; + background: #fef3c7; + color: #b45309; + border-radius: 3px; +} + +/* Action Bar */ +.copilot-action-bar { + display: flex; + justify-content: flex-end; + margin-top: 4px; +} +.copilot-action-btn { + background: transparent; + border: none; + color: #94a3b8; + font-size: 11px; + display: inline-flex; + align-items: center; + gap: 4px; + cursor: pointer; + padding: 2px 6px; + border-radius: 4px; + transition: all 0.15s ease; +} +.copilot-action-btn:hover { + background: #f1f5f9; + color: #334155; +} + +/* Choice Preview */ +.copilot-choice-preview { + margin-top: 6px; + padding: 6px 10px; + background: #f0fdfa; + border-left: 2px solid #0f766e; + border-radius: 0 4px 4px 0; + font-size: 11px; + color: #334155; +} +.copilot-choice-preview strong { + color: #0f766e; +} + +/* Editable Wish Draft */ +.copilot-edit-toggle { + margin-left: auto; + background: transparent; + border: none; + color: #0f766e; + font-size: 11px; + cursor: pointer; + display: flex; + align-items: center; + gap: 4px; +} +.copilot-edit-textarea { + width: 100%; + border: 1px solid #cbd5e1; + border-radius: 4px; + padding: 6px 8px; + font-size: 12px; + font-family: inherit; + margin-top: 4px; + resize: vertical; +} + +/* Scroll Bottom Capsule */ +.copilot-scroll-bottom { + position: absolute; + bottom: 80px; + left: 50%; + transform: translateX(-50%); + background: #0f172a; + color: #fff; + border: none; + border-radius: 999px; + padding: 6px 14px; + font-size: 11px; + display: flex; + align-items: center; + gap: 6px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); + cursor: pointer; + z-index: 10; + animation: copilot-fade-in 0.2s ease; +} +@keyframes copilot-fade-in { + from { + opacity: 0; + transform: translate(-50%, 6px); + } + to { + opacity: 1; + transform: translate(-50%, 0); + } +} + +.copilot-error-title { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 4px; + color: #b91c1c; +} @media (min-width: 1101px) { .console.copilot-open .main-shell { margin-right: 520px; diff --git a/apps/web/src/features/copilot-stream.ts b/apps/web/src/features/copilot-stream.ts index d148dc8..7f39f7f 100644 --- a/apps/web/src/features/copilot-stream.ts +++ b/apps/web/src/features/copilot-stream.ts @@ -8,13 +8,33 @@ import { useCallback, useRef, useState } from 'react'; * Frames are Server-Sent Events from the control plane. A frame is either text, a thought, a short * progress sentence or the final summary; nothing here understands the model or its tools. */ +export type CopilotStreamStep = { + stepId: string; + name: string; + label: string; + status: 'running' | 'ok' | 'missing' | 'failed'; + evidenceId?: string; + observedAt?: string; + startedAt: number; +}; + export type CopilotStreamEvent = | { type: 'delta'; content: string } | { type: 'thinking'; content: string } - | { type: 'tool_use'; name: string; progress: string } + | { + type: 'tool_use'; + stepId?: string; + phase?: 'start' | 'end'; + name: string; + progress: string; + outcome?: 'ok' | 'missing' | 'failed'; + evidenceId?: string; + observedAt?: string; + } | { type: 'card'; cardType: 'diagnosis' | 'wish' | 'error'; object: unknown } | { type: 'done'; summary: Record } | { type: 'error'; code?: string; message: string }; + export type CopilotStreamState = { /** Accumulated answer text. */ content: string; @@ -22,25 +42,65 @@ export type CopilotStreamState = { thinking: string; /** What the Copilot is doing right now, in the customer's words. */ progress: string; + /** Investigation steps progression. */ + steps: CopilotStreamStep[]; streaming: boolean; error: string; + errorCode?: string; + diagnosis?: unknown; summary?: Record; }; -const EMPTY: CopilotStreamState = { content: '', thinking: '', progress: '', streaming: false, error: '' }; + +export const EMPTY_COPILOT_STREAM: CopilotStreamState = { + content: '', + thinking: '', + progress: '', + steps: [], + streaming: false, + error: '', +}; + +export function friendlyErrorMessage(code?: string, rawMessage?: string): string { + if (code === 'upstream_unavailable') { + return '诊断服务暂不可用(模型通道或上游服务不通),这不是正常结果,请稍后重试。'; + } + if (code === 'rate_limited') { + return '查询请求过于频繁(已达每分钟限额),请约 15 秒后再试。'; + } + if (code === 'timeout') { + return '诊断分析超时,请稍后重试。'; + } + if (code === 'not_configured') { + return '项目未配置诊断通道或模型凭据,请联系管理员。'; + } + if (code === 'upstream_refused') { + return '上游诊断服务拒绝了请求,请核对权限或稍后重试。'; + } + if (code === 'invalid_input') { + return '输入的任务编号或请求标识格式有误。'; + } + return rawMessage || '回答未完成,请重试。'; +} + +const failRunningSteps = (steps: CopilotStreamStep[]): CopilotStreamStep[] => + steps.map(s => (s.status === 'running' ? { ...s, status: 'failed' as const } : s)); export function useCopilotStream() { - const [state, setState] = useState(EMPTY); + const [state, setState] = useState(EMPTY_COPILOT_STREAM); const active = useRef(null); + const stop = useCallback(() => { active.current?.abort(); active.current = null; - setState(current => ({ ...current, streaming: false, progress: '' })); + setState(current => ({ ...current, streaming: false, progress: '', steps: failRunningSteps(current.steps) })); }, []); + const reset = useCallback(() => { active.current?.abort(); active.current = null; - setState(EMPTY); + setState(EMPTY_COPILOT_STREAM); }, []); + const start = useCallback( async (input: { projectId: string; @@ -49,13 +109,13 @@ export function useCopilotStream() { clientId: string; /** Ids of the pictures uploaded for this question, in the order they were shown. */ attachments?: string[]; - context?: { pathname?: string; runId?: string }; + context?: { pathname?: string; runId?: string; taskId?: string; requestId?: string }; onDone?: () => void; }) => { active.current?.abort(); const controller = new AbortController(); active.current = controller; - setState({ ...EMPTY, streaming: true }); + setState({ ...EMPTY_COPILOT_STREAM, streaming: true }); try { const response = await fetch(`/api/projects/${input.projectId}/copilot/sessions/${input.sessionId}/stream`, { method: 'POST', @@ -72,7 +132,9 @@ export function useCopilotStream() { }); if (!response.ok) { const payload = await response.json().catch(() => null); - throw new Error(payload?.error?.message ?? `请求失败 (${response.status})`); + const code = payload?.error?.code; + const msg = payload?.error?.message ?? `请求失败 (${response.status})`; + throw new Error(friendlyErrorMessage(code, msg)); } if (!response.body) throw new Error('回答没有返回内容,请重试。'); const reader = response.body.getReader(); @@ -100,22 +162,63 @@ export function useCopilotStream() { } catch { continue; } - if (event.type === 'delta') + if (event.type === 'delta') { setState(current => ({ ...current, content: `${current.content}${event.content}` })); - else if (event.type === 'thinking') + } else if (event.type === 'thinking') { setState(current => ({ ...current, thinking: `${current.thinking}${event.content}` })); - else if (event.type === 'tool_use') setState(current => ({ ...current, progress: event.progress })); - else if (event.type === 'error') - setState(current => ({ ...current, streaming: false, progress: '', error: event.message })); - else if (event.type === 'done') { + } else if (event.type === 'tool_use') { + setState(current => { + const stepId = event.stepId || `step-${current.steps.length + 1}`; + const existingIndex = current.steps.findIndex(s => s.stepId === stepId); + const status = event.phase === 'end' ? (event.outcome ?? 'ok') : 'running'; + let nextSteps = [...current.steps]; + if (existingIndex >= 0) { + nextSteps[existingIndex] = { + ...nextSteps[existingIndex]!, + label: event.progress || nextSteps[existingIndex]!.label, + status, + evidenceId: event.evidenceId ?? nextSteps[existingIndex]!.evidenceId, + observedAt: event.observedAt ?? nextSteps[existingIndex]!.observedAt, + }; + } else { + nextSteps.push({ + stepId, + name: event.name, + label: event.progress, + status, + evidenceId: event.evidenceId, + observedAt: event.observedAt, + startedAt: Date.now(), + }); + } + return { + ...current, + progress: event.progress, + steps: nextSteps, + }; + }); + } else if (event.type === 'card' && event.cardType === 'diagnosis') { + setState(current => ({ ...current, diagnosis: event.object })); + } else if (event.type === 'error') { + setState(current => ({ + ...current, + streaming: false, + progress: '', + steps: failRunningSteps(current.steps), + error: friendlyErrorMessage(event.code, event.message), + errorCode: event.code, + })); + } else if (event.type === 'done') { finished = true; setState(current => ({ ...current, streaming: false, progress: '', + steps: current.steps.map(s => (s.status === 'running' ? { ...s, status: 'ok' as const } : s)), summary: event.summary, + diagnosis: event.summary?.diagnosis ?? current.diagnosis, content: - typeof event.summary.content === 'string' && event.summary.content + typeof event.summary?.content === 'string' && event.summary.content ? event.summary.content : current.content, })); @@ -123,28 +226,40 @@ export function useCopilotStream() { } } await reader.cancel().catch(() => undefined); - if (!finished) - setState(current => - current.error - ? { ...current, streaming: false, progress: '' } - : { ...current, streaming: false, progress: '', error: '回答中断了,请重试。' }, - ); - input.onDone?.(); - } catch (error) { - if (controller.signal.aborted) - setState(current => ({ ...current, streaming: false, progress: '', error: '已停止生成。' })); - else + if (!finished) { setState(current => ({ ...current, streaming: false, progress: '', + steps: failRunningSteps(current.steps), + error: current.error || '回答中断了,请重试。', + })); + } + input.onDone?.(); + } catch (error) { + if (controller.signal.aborted) { + setState(current => ({ + ...current, + streaming: false, + progress: '', + steps: failRunningSteps(current.steps), + error: '已停止生成。', + })); + } else { + setState(current => ({ + ...current, + streaming: false, + progress: '', + steps: failRunningSteps(current.steps), error: error instanceof Error ? error.message : '回答未完成,请重试。', })); + } } finally { if (active.current === controller) active.current = null; } }, [], ); + return { state, start, stop, reset }; } diff --git a/apps/web/src/features/copilot.tsx b/apps/web/src/features/copilot.tsx index 4b4d1eb..4820260 100644 --- a/apps/web/src/features/copilot.tsx +++ b/apps/web/src/features/copilot.tsx @@ -1,32 +1,95 @@ 'use client'; -import { BookOpen, Bot, Bug, ExternalLink, Lightbulb, Maximize2, Plus, RefreshCw, Sparkles, X } from 'lucide-react'; +import { + AlertTriangle, + ArrowDown, + BookOpen, + Bot, + Bug, + Check, + CheckCircle2, + ChevronDown, + ChevronRight, + Copy, + Edit3, + ExternalLink, + Lightbulb, + LoaderCircle, + Maximize2, + Plus, + RefreshCw, + ShieldAlert, + Sparkles, + X, + XCircle, +} from 'lucide-react'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; import { useEffect, useRef, useState } from 'react'; +import ReactMarkdown from 'react-markdown'; +import remarkGfm from 'remark-gfm'; import { withAnswers } from '@wishforge/contracts/wish'; import { plainText } from '@wishforge/contracts/text'; -import type { CopilotAttachment, CopilotMessage, CopilotSession } from '@wishforge/contracts'; +import type { CopilotAttachment, CopilotDiagnosis, CopilotMessage, CopilotSession } from '@wishforge/contracts'; import { api, messageOf, mutateApi, useResource } from '@/lib/api'; import { browserId } from '@/lib/browser-id'; import type { Project } from '@/lib/types'; import { ErrorNotice, Notice } from '@/components/ui'; -import { useCopilotStream } from './copilot-stream'; +import { useCopilotStream, type CopilotStreamStep } from './copilot-stream'; import { CopilotComposer, MAX_PICTURES, PICTURE_TYPES, pictureProblem, type PendingPicture } from './copilot-composer'; const kindLabels = { faq: '使用说明', bug: '疑似 Bug', feature: '需求', unknown: '待补充' } as const; const sessionKey = (projectId: string) => `wishforge.copilot.session.${projectId}`; -/** What a customer is most likely to want to say first, one click each. */ -const scenes = ['你能帮我做什么?', '某个按钮点了没反应', '想把首页那句介绍改个说法']; -function Sources({ message }: { message: { sources?: CopilotMessage['sources']; knowledgeVersion?: string } }) { +/** What a customer is most likely to want to say first, one click each. */ +const scenes = [ + '你能帮我做什么?', + '平台任务报错了(填入编号排查)', + '调整切片时提示系统响应超时,请帮我排查', + '如何提交 Wish?请根据当前项目 Wiki 回答。', +]; + +/** Safe Markdown renderer that sanitizes through plainText first to protect internal paths */ +function SafeMarkdown({ content }: { content: string }) { + let safe = plainText(content); + // Auto-close unclosed code block if odd number of triple backticks + const codeBlockCount = (safe.match(/```/g) || []).length; + if (codeBlockCount % 2 === 1) { + safe += '\n```'; + } + return ( +
+ {safe} +
+ ); +} + +function Sources({ + message, +}: { + message: { sources?: CopilotMessage['sources']; knowledgeVersion?: string; createdAt?: string }; +}) { if (!message.sources?.length) return null; + const timeStr = message.createdAt + ? new Date(message.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + : ''; + const versionHash = message.knowledgeVersion ? message.knowledgeVersion.slice(0, 8) : ''; return (
- 参考资料 - {message.sources.map(source => ( +
+ 参考资料 + {versionHash || timeStr ? ( + + {versionHash ? `快照版本 ${versionHash}` : ''} + {versionHash && timeStr ? ' · ' : ''} + {timeStr ? `回答于 ${timeStr}` : ''} + + ) : null} +
+ {message.sources.map((source, index) => (
- {source.title} + [{index + 1}] {source.title}{' '} + {plainText(source.excerpt)}
@@ -35,6 +98,185 @@ function Sources({ message }: { message: { sources?: CopilotMessage['sources']; ); } +function DiagnosisCard({ + diagnosis, + onProvideInfo, + onShowWish, +}: { + diagnosis?: CopilotDiagnosis; + onProvideInfo?: () => void; + onShowWish?: () => void; +}) { + if (!diagnosis) return null; + const verdictMap = { + problem: { label: '发现问题', className: 'is-problem', icon: }, + expected: { label: '符合规则', className: 'is-expected', icon: }, + insufficient: { label: '证据不足', className: 'is-insufficient', icon: }, + } as const; + const currentVerdict = verdictMap[diagnosis.verdict] ?? verdictMap.insufficient; + const evidenceMap = new Map((diagnosis.evidence ?? []).map(e => [e.id, e])); + + return ( +
+
+
+ + 线上排障与诊断 +
+ + {currentVerdict.icon} {currentVerdict.label} + +
+ + {diagnosis.facts?.length ? ( +
+

已确认的事实

+
    + {diagnosis.facts.map((fact, idx) => { + const ev = evidenceMap.get(fact.evidenceId); + const timeStr = ev?.observedAt + ? new Date(ev.observedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + : ''; + const available = ev?.available ?? true; + return ( +
  • + • + {plainText(fact.text)} + {ev ? ( + + {ev.label || '线上证据'} + {timeStr ? ` · ${timeStr}` : ''} + {!available ? ' (未采集)' : ''} + + ) : null} +
  • + ); + })} +
+
+ ) : ( +

本次没有取到线上证据

+ )} + + {diagnosis.hypotheses?.length ? ( +
+

可能的原因(推测)

+
    + {diagnosis.hypotheses.map((h, idx) => ( +
  • + {plainText(h.text)} + + 置信度: {h.confidence === 'high' ? '高' : h.confidence === 'medium' ? '中' : '低'} + +
  • + ))} +
+
+ ) : null} + + {diagnosis.missing?.length ? ( +
+

还缺的证据

+
    + {diagnosis.missing.map((m, idx) => ( +
  • {plainText(m)}
  • + ))} +
+
+ ) : null} + + {diagnosis.verdict === 'insufficient' ? ( +
+ {onProvideInfo ? ( + + ) : null} + {onShowWish ? ( + + ) : null} +
+ ) : null} +
+ ); +} + +function ToolSteps({ steps }: { steps: CopilotStreamStep[] }) { + const [expanded, setExpanded] = useState(false); + if (!steps.length) return null; + const running = steps.filter(s => s.status === 'running'); + const activeStep = running.at(-1) ?? steps.at(-1); + + return ( +
+
setExpanded(!expanded)}> + + {activeStep?.status === 'running' ? ( + + ) : activeStep?.status === 'missing' ? ( + + ) : activeStep?.status === 'failed' ? ( + + ) : ( + + )} + {activeStep?.label || '处理中…'} + ({steps.length} 步) + + +
+ + {expanded ? ( +
    + {steps.map(step => ( +
  • + {step.status === 'running' ? ( + + ) : step.status === 'ok' ? ( + + ) : step.status === 'missing' ? ( + + ) : ( + + )} + {step.label} + {step.status === 'missing' ? 缺失 : null} +
  • + ))} +
+ ) : null} +
+ ); +} + +function MessageActionBar({ content }: { content: string }) { + const [copied, setCopied] = useState(false); + const copy = async () => { + try { + await navigator.clipboard.writeText(plainText(content)); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } catch { + // ignore + } + }; + return ( +
+ +
+ ); +} + /** The pictures a question was sent with, still visible after a reload. */ function PictureStrip({ pictures, @@ -61,9 +303,8 @@ function PictureStrip({ } /** - * The Wish the Copilot drafted, shown as one card to confirm. The card never repeats the answer - * above it: it says what will change (only when that is a different sentence), how it will be - * checked, and what the customer may want to pick before confirming. + * The Wish the Copilot drafted, shown as one card to confirm. The card allows editing + * goal and criteria before submission. */ function WishDraft({ message, @@ -80,16 +321,24 @@ function WishDraft({ const baseGoal = statedGoal || plainText(message.content); const repeatsAnswer = statedGoal === plainText(message.content).trim(); const baseCriteria = (message.acceptanceCriteria ?? []).map(plainText); + const [selected, setSelected] = useState>({}); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [created, setCreated] = useState(message.wish); + + // Editable fields + const [isEditing, setIsEditing] = useState(false); + const [customGoal, setCustomGoal] = useState(null); + const [customCriteria, setCustomCriteria] = useState(null); + const choose = (questionIndex: number, optionIndex: number) => setSelected(current => current[questionIndex] === optionIndex ? Object.fromEntries(Object.entries(current).filter(([key]) => Number(key) !== questionIndex)) : { ...current, [questionIndex]: optionIndex }, ); + const answers = (message.questions ?? []) .map((question, index) => plainText(question.options[selected[index] ?? -1]?.wish ?? '')) .filter(Boolean); @@ -97,8 +346,19 @@ function WishDraft({ .map((question, index) => question.options[selected[index] ?? -1]?.acceptanceCriterion) .filter((value): value is string => Boolean(value)) .map(plainText); - const goal = withAnswers(baseGoal, answers).trim(); - const criteria = [...baseCriteria, ...additions].map(line => line.trim()).filter(Boolean); + + const calculatedGoal = withAnswers(baseGoal, answers).trim(); + const calculatedCriteria = [...baseCriteria, ...additions].map(line => line.trim()).filter(Boolean); + + const activeGoal = customGoal !== null ? customGoal : calculatedGoal; + const activeCriteria = + customCriteria !== null + ? customCriteria + .split('\n') + .map(s => s.trim()) + .filter(Boolean) + : calculatedCriteria; + const submit = async () => { if (busy || created) return; setBusy(true); @@ -108,8 +368,8 @@ function WishDraft({ `/projects/${projectId}/copilot/sessions/${sessionId}/wish`, { messageId: message.id, - goal: goal.length >= 8 ? goal : `请按对话中的描述完成这次改动:${goal}`, - acceptanceCriteria: criteria.length ? criteria : ['改动完成,且对话中描述的现象不再出现'], + goal: activeGoal.length >= 8 ? activeGoal : `请按对话中的描述完成这次改动:${activeGoal}`, + acceptanceCriteria: activeCriteria.length ? activeCriteria : ['改动完成,且对话中描述的现象不再出现'], answers: [], }, 'POST', @@ -123,11 +383,23 @@ function WishDraft({ setBusy(false); } }; + return (
{message.kind === 'bug' ? '确认这次修复' : '确认这个需求'} +
{message.kind === 'bug' ? (
@@ -145,18 +417,45 @@ function WishDraft({

{plainText(message.contextSummary || '没有额外说明。')}

) : null} - {statedGoal && !repeatsAnswer ? ( -
-

要做的改动

-

{plainText(goal)}

+ + {isEditing ? ( +
+

要做的改动(可修改)

+