diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 8838d13..de296d9 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -3299,7 +3299,7 @@ fieldset:disabled label { .copilot-sidebar { position: fixed; inset: 0 0 0 auto; - width: 400px; + width: 520px; max-width: 100vw; z-index: 45; display: flex; @@ -3498,8 +3498,10 @@ fieldset:disabled label { } .copilot-composer textarea { width: 100%; - min-height: 72px; - max-height: 180px; + min-height: 40px; + max-height: 160px; + overflow-y: auto; + resize: none; } .copilot-composer > div { display: flex; @@ -3515,6 +3517,101 @@ fieldset:disabled label { color: var(--red); margin-top: 8px; } +.copilot-progress { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--muted); + font-size: 12px; + margin-bottom: 8px; +} +.copilot-progress::before { + content: ''; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--teal); + animation: copilot-pulse 1.2s ease-in-out infinite; +} +@keyframes copilot-pulse { + 0%, + 100% { + opacity: 0.35; + } + 50% { + opacity: 1; + } +} +.copilot-cursor { + display: inline-block; + width: 2px; + height: 1em; + margin-left: 2px; + vertical-align: -2px; + background: var(--teal-dark); + animation: copilot-blink 1s step-end infinite; +} +@keyframes copilot-blink { + 50% { + opacity: 0; + } +} +.copilot-thinking { + margin-bottom: 10px; + padding: 8px 10px; + background: #f6f8fb; + border-radius: 6px; + font-size: 12px; + color: var(--muted); +} +.copilot-thinking summary { + cursor: pointer; + color: var(--ink); + font-weight: 600; +} +.copilot-thinking p { + margin-top: 6px; + white-space: pre-wrap; +} +.copilot-quick-replies { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 10px; +} +.copilot-quick-replies button { + border: 1px solid var(--border); + background: white; + border-radius: 14px; + padding: 5px 11px; + font-size: 12px; + color: var(--teal-dark); +} +.copilot-quick-replies button:hover { + border-color: #b8dcd3; + background: var(--teal-pale); +} +.copilot-welcome .copilot-quick-replies { + justify-content: center; +} +.copilot-card-goal { + padding: 10px; + background: #f6f8fb; + border-radius: 6px; +} +.copilot-card-goal strong { + display: block; + margin-bottom: 4px; + font-size: 12px; +} +.copilot-card-goal p, +.copilot-card-goal ul { + margin: 0; + white-space: pre-wrap; +} +.copilot-card-goal ul { + padding-left: 18px; +} .wiki-source { background: white; border: 1px solid var(--border); diff --git a/apps/web/src/features/copilot-stream.ts b/apps/web/src/features/copilot-stream.ts new file mode 100644 index 0000000..7ea0680 --- /dev/null +++ b/apps/web/src/features/copilot-stream.ts @@ -0,0 +1,147 @@ +'use client'; +import { useCallback, useRef, useState } from 'react'; + +/** + * The Copilot's answer, as it arrives. The console keeps one streaming answer in local state and + * swaps it for the stored message when `done` arrives, so the transcript is never written twice. + * + * 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 CopilotStreamEvent = + | { type: 'delta'; content: string } + | { type: 'thinking'; content: string } + | { type: 'tool_use'; name: string; progress: 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; + /** Accumulated reasoning, shown collapsed. */ + thinking: string; + /** What the Copilot is doing right now, in the customer's words. */ + progress: string; + streaming: boolean; + error: string; + summary?: Record; +}; +const EMPTY: CopilotStreamState = { content: '', thinking: '', progress: '', streaming: false, error: '' }; + +export function useCopilotStream() { + const [state, setState] = useState(EMPTY); + const active = useRef(null); + const stop = useCallback(() => { + active.current?.abort(); + active.current = null; + setState(current => ({ ...current, streaming: false, progress: '' })); + }, []); + const reset = useCallback(() => { + active.current?.abort(); + active.current = null; + setState(EMPTY); + }, []); + const start = useCallback( + async (input: { + projectId: string; + sessionId: string; + content: string; + clientId: string; + context?: { pathname?: string; runId?: string }; + onDone?: () => void; + }) => { + active.current?.abort(); + const controller = new AbortController(); + active.current = controller; + setState({ ...EMPTY, streaming: true }); + try { + const response = await fetch(`/api/projects/${input.projectId}/copilot/sessions/${input.sessionId}/stream`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'Idempotency-Key': input.clientId }, + body: JSON.stringify({ + content: input.content, + clientId: input.clientId, + ...(input.context ? { context: input.context } : {}), + }), + cache: 'no-store', + credentials: 'same-origin', + signal: controller.signal, + }); + if (!response.ok) { + const payload = await response.json().catch(() => null); + throw new Error(payload?.error?.message ?? `请求失败 (${response.status})`); + } + if (!response.body) throw new Error('回答没有返回内容,请重试。'); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + let finished = false; + for (;;) { + const part = await reader.read(); + if (part.done) break; + buffer += decoder.decode(part.value, { stream: true }).replace(/\r\n/g, '\n'); + for (;;) { + const end = buffer.indexOf('\n\n'); + if (end < 0) break; + const chunk = buffer.slice(0, end); + buffer = buffer.slice(end + 2); + const data = chunk + .split('\n') + .filter(line => line.startsWith('data:')) + .map(line => line.slice(5).trim()) + .join('\n'); + if (!data) continue; + let event: CopilotStreamEvent; + try { + event = JSON.parse(data) as CopilotStreamEvent; + } catch { + continue; + } + if (event.type === 'delta') + setState(current => ({ ...current, content: `${current.content}${event.content}` })); + 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') { + finished = true; + setState(current => ({ + ...current, + streaming: false, + progress: '', + summary: event.summary, + content: + typeof event.summary.content === 'string' && event.summary.content + ? event.summary.content + : current.content, + })); + } + } + } + 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 + setState(current => ({ + ...current, + streaming: false, + progress: '', + 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 71e05c3..96d9e8e 100644 --- a/apps/web/src/features/copilot.tsx +++ b/apps/web/src/features/copilot.tsx @@ -1,24 +1,24 @@ 'use client'; -import { BookOpen, Bot, Bug, ExternalLink, Lightbulb, Plus, Send, X } from 'lucide-react'; +import { BookOpen, Bot, Bug, ExternalLink, Lightbulb, Plus, RefreshCw, Send, Square, X } from 'lucide-react'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; -import { useEffect, useState } from 'react'; -import { useSWRConfig } from 'swr'; +import { useEffect, useRef, useState } from 'react'; import { withAnswers } from '@wishforge/contracts/wish'; import type { 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 { Button, ErrorNotice, Notice } from '@/components/ui'; +import { useCopilotStream } from './copilot-stream'; -const kindLabels = { faq: 'FAQ / 配置', bug: '疑似 Bug', feature: '需求', unknown: '依据不足' } as const; +const kindLabels = { faq: '使用说明', bug: '疑似 Bug', feature: '需求', unknown: '待补充' } as const; const sessionKey = (projectId: string) => `wishforge.copilot.session.${projectId}`; -function Sources({ message }: { message: CopilotMessage }) { +function Sources({ message }: { message: { sources?: CopilotMessage['sources']; knowledgeVersion?: string } }) { if (!message.sources?.length) return null; return (
- 依据 · Wiki {message.knowledgeVersion?.slice(0, 8)} + 参考资料 {message.sources.map(source => (
@@ -31,6 +31,11 @@ function Sources({ message }: { message: CopilotMessage }) { ); } +/** + * The Wish the Copilot drafted, shown as one card to confirm. The customer picks between the + * options the Copilot offered, or types nothing at all: the card already says what will change and + * how it will be checked. Only the confirm button creates the Wish. + */ function WishDraft({ message, projectId, @@ -42,26 +47,26 @@ function WishDraft({ sessionId: string; onCreated: () => void; }) { - const baseGoal = message.goal ?? ''; + const baseGoal = message.goal ?? message.content; const baseCriteria = message.acceptanceCriteria ?? []; - const [goal, setGoal] = useState(baseGoal); - const [criteria, setCriteria] = useState(baseCriteria.join('\n')); const [selected, setSelected] = useState>({}); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [created, setCreated] = useState(message.wish); - const choose = (questionIndex: number, optionIndex: number) => { - const next = { ...selected, [questionIndex]: optionIndex }; - setSelected(next); - const answers = (message.questions ?? []) - .map((question, index) => question.options[next[index] ?? -1]?.wish ?? '') - .filter(Boolean); - setGoal(withAnswers(baseGoal, answers)); - const additions = (message.questions ?? []) - .map((question, index) => question.options[next[index] ?? -1]?.acceptanceCriterion) - .filter((value): value is string => Boolean(value)); - setCriteria([...baseCriteria, ...additions].join('\n')); - }; + 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) => question.options[selected[index] ?? -1]?.wish ?? '') + .filter(Boolean); + const additions = (message.questions ?? []) + .map((question, index) => question.options[selected[index] ?? -1]?.acceptanceCriterion) + .filter((value): value is string => Boolean(value)); + const goal = withAnswers(baseGoal, answers).trim(); + const criteria = [...baseCriteria, ...additions].map(line => line.trim()).filter(Boolean); const submit = async () => { if (busy || created) return; setBusy(true); @@ -71,11 +76,8 @@ function WishDraft({ `/projects/${projectId}/copilot/sessions/${sessionId}/wish`, { messageId: message.id, - goal: goal.trim(), - acceptanceCriteria: criteria - .split('\n') - .map(line => line.trim()) - .filter(Boolean), + goal: goal.length >= 8 ? goal : `请按对话中的描述完成这次改动:${goal}`, + acceptanceCriteria: criteria.length ? criteria : ['改动完成,且对话中描述的现象不再出现'], answers: [], }, 'POST', @@ -101,16 +103,23 @@ function WishDraft({ ))} ) : ( -

尚未提供复现步骤,请在 Wish 中补充。

+

还没提供复现步骤,工程师会再确认。

)} - 当前上下文 -

{message.contextSummary || '未提供额外上下文。'}

+ 当时的情况 +

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

) : null} +
+ 要做的改动 +

{goal}

+
+
+ 做完怎么确认 +
    {criteria.length ? criteria.map(item =>
  • {item}
  • ) :
  • 改动完成即可。
  • }
+
{message.questions?.map((question, questionIndex) => (
- Grill me · {question.question} - 依据 {question.sourcePath} + {question.question}
{question.options.map((option, optionIndex) => (
))} -