✨ Render diagnosis cards, tool steps, safe Markdown, and editable Wish drafts
Some checks failed
CI / Format, types and tests (pull_request) Has been cancelled
CI / PostgreSQL migrations and integration tests (pull_request) Has been cancelled
CI / IDE gateway, collaboration and policy tests (pull_request) Has been cancelled

Display structured Copilot diagnoses with verdict badges, server-stamped evidence chips, confidence-tagged hypotheses, missing-evidence callouts, and an explicit handoff path when evidence is insufficient.

Add progressive start/end tool step rows, path-scrubbed Markdown rendering via react-markdown and remark-gfm, typed stream error banners, sticky-threshold auto-scroll, copy actions, Grill-me choice previews, editable Wish drafts, and the accompanying design and operations docs.
This commit is contained in:
wishforge 2026-11-11 07:59:03 -08:00
parent 9dde59e8c6
commit 5855d5a43c
8 changed files with 2990 additions and 100 deletions

View File

@ -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",

View File

@ -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;

View File

@ -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<string, unknown> }
| { 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<string, unknown>;
};
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<CopilotStreamState>(EMPTY);
const [state, setState] = useState<CopilotStreamState>(EMPTY_COPILOT_STREAM);
const active = useRef<AbortController | null>(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 };
}

View File

@ -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 (
<div className="copilot-md">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{safe}</ReactMarkdown>
</div>
);
}
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 (
<div className="copilot-sources">
<strong>参考资料</strong>
{message.sources.map(source => (
<div className="copilot-sources-header">
<strong>参考资料</strong>
{versionHash || timeStr ? (
<span className="copilot-sources-meta">
{versionHash ? `快照版本 ${versionHash}` : ''}
{versionHash && timeStr ? ' · ' : ''}
{timeStr ? `回答于 ${timeStr}` : ''}
</span>
) : null}
</div>
{message.sources.map((source, index) => (
<div className="copilot-source" key={source.path}>
<Link href={source.url} target="_blank">
<BookOpen size={13} /> {source.title} <ExternalLink size={12} />
<BookOpen size={13} /> <span className="copilot-source-num">[{index + 1}]</span> {source.title}{' '}
<ExternalLink size={12} />
</Link>
<small>{plainText(source.excerpt)}</small>
</div>
@ -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: <Bug size={13} /> },
expected: { label: '符合规则', className: 'is-expected', icon: <CheckCircle2 size={13} /> },
insufficient: { label: '证据不足', className: 'is-insufficient', icon: <AlertTriangle size={13} /> },
} as const;
const currentVerdict = verdictMap[diagnosis.verdict] ?? verdictMap.insufficient;
const evidenceMap = new Map((diagnosis.evidence ?? []).map(e => [e.id, e]));
return (
<div className={`copilot-diagnosis-card ${currentVerdict.className}`}>
<header className="copilot-diagnosis-header">
<div className="copilot-diagnosis-title">
<ShieldAlert size={15} />
<strong>线上排障与诊断</strong>
</div>
<span className={`copilot-verdict-badge ${diagnosis.verdict}`}>
{currentVerdict.icon} {currentVerdict.label}
</span>
</header>
{diagnosis.facts?.length ? (
<section className="copilot-diagnosis-section">
<h4>已确认的事实</h4>
<ul className="copilot-facts-list">
{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 (
<li key={idx}>
<span className="copilot-fact-bullet">•</span>
<span className="copilot-fact-text">{plainText(fact.text)}</span>
{ev ? (
<span
className={`copilot-evidence-chip ${available ? 'is-available' : 'is-unavailable'}`}
title={available ? `采集时间:${ev.observedAt ?? '实时'}` : '暂时拿不到,不代表正常'}
>
{ev.label || '线上证据'}
{timeStr ? ` · ${timeStr}` : ''}
{!available ? ' (未采集)' : ''}
</span>
) : null}
</li>
);
})}
</ul>
</section>
) : (
<p className="copilot-diagnosis-empty">本次没有取到线上证据</p>
)}
{diagnosis.hypotheses?.length ? (
<section className="copilot-diagnosis-section">
<h4>可能的原因(推测)</h4>
<ul className="copilot-hypotheses-list">
{diagnosis.hypotheses.map((h, idx) => (
<li key={idx}>
<span className="copilot-hypothesis-text">{plainText(h.text)}</span>
<span className={`copilot-confidence-tag ${h.confidence}`}>
置信度: {h.confidence === 'high' ? '高' : h.confidence === 'medium' ? '中' : '低'}
</span>
</li>
))}
</ul>
</section>
) : null}
{diagnosis.missing?.length ? (
<section className="copilot-diagnosis-section">
<h4>还缺的证据</h4>
<ul className="copilot-missing-list">
{diagnosis.missing.map((m, idx) => (
<li key={idx}>{plainText(m)}</li>
))}
</ul>
</section>
) : null}
{diagnosis.verdict === 'insufficient' ? (
<footer className="copilot-diagnosis-actions">
{onProvideInfo ? (
<button type="button" className="copilot-secondary" onClick={onProvideInfo}>
我去补充信息
</button>
) : null}
{onShowWish ? (
<button type="button" className="copilot-secondary" onClick={onShowWish}>
仍然交给工程师
</button>
) : null}
</footer>
) : null}
</div>
);
}
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 (
<div className="copilot-steps-container">
<div className="copilot-steps-bar" onClick={() => setExpanded(!expanded)}>
<span className="copilot-steps-summary">
{activeStep?.status === 'running' ? (
<LoaderCircle size={14} className="copilot-spin" />
) : activeStep?.status === 'missing' ? (
<AlertTriangle size={14} className="copilot-step-missing" />
) : activeStep?.status === 'failed' ? (
<XCircle size={14} className="copilot-step-failed" />
) : (
<CheckCircle2 size={14} className="copilot-success-icon" />
)}
<span>{activeStep?.label || '处理中…'}</span>
<span className="copilot-steps-count">({steps.length} 步)</span>
</span>
<button type="button" className="copilot-steps-toggle" aria-label="展开排查步骤">
{expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</button>
</div>
{expanded ? (
<ul className="copilot-steps-list">
{steps.map(step => (
<li key={step.stepId} className={`copilot-step-item ${step.status}`}>
{step.status === 'running' ? (
<LoaderCircle size={13} className="copilot-spin" />
) : step.status === 'ok' ? (
<Check size={13} className="copilot-step-ok" />
) : step.status === 'missing' ? (
<AlertTriangle size={13} className="copilot-step-missing" />
) : (
<XCircle size={13} className="copilot-step-failed" />
)}
<span className="copilot-step-label">{step.label}</span>
{step.status === 'missing' ? <span className="copilot-step-missing-tag">缺失</span> : null}
</li>
))}
</ul>
) : null}
</div>
);
}
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 (
<div className="copilot-action-bar">
<button type="button" className="copilot-action-btn" title="复制结论" onClick={copy}>
{copied ? <Check size={13} /> : <Copy size={13} />}
<span>{copied ? '已复制' : '复制结论'}</span>
</button>
</div>
);
}
/** 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<Record<number, number>>({});
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<string | null>(null);
const [customCriteria, setCustomCriteria] = useState<string | null>(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 (
<div className="copilot-card">
<header>
<Sparkles size={15} />
<strong>{message.kind === 'bug' ? '确认这次修复' : '确认这个需求'}</strong>
<button
type="button"
className="copilot-edit-toggle"
onClick={() => {
if (!isEditing && customGoal === null) setCustomGoal(calculatedGoal);
if (!isEditing && customCriteria === null) setCustomCriteria(calculatedCriteria.join('\n'));
setIsEditing(!isEditing);
}}
>
<Edit3 size={13} /> {isEditing ? '收起编辑' : '编辑草稿'}
</button>
</header>
{message.kind === 'bug' ? (
<section className="copilot-card-row">
@ -145,18 +417,45 @@ function WishDraft({
<p>{plainText(message.contextSummary || '没有额外说明。')}</p>
</section>
) : null}
{statedGoal && !repeatsAnswer ? (
<section className="copilot-card-row">
<h4>要做的改动</h4>
<p>{plainText(goal)}</p>
{isEditing ? (
<section className="copilot-card-row copilot-edit-section">
<h4>要做的改动(可修改)</h4>
<textarea
className="copilot-edit-textarea"
rows={3}
value={activeGoal}
onChange={e => setCustomGoal(e.target.value)}
/>
<h4>做完怎么确认(每行一条)</h4>
<textarea
className="copilot-edit-textarea"
rows={3}
value={customCriteria !== null ? customCriteria : calculatedCriteria.join('\n')}
onChange={e => setCustomCriteria(e.target.value)}
/>
</section>
) : null}
<section className="copilot-card-row">
<h4>做完怎么确认</h4>
<ul>
{criteria.length ? criteria.map(item => <li key={item}>{plainText(item)}</li>) : <li>改动完成即可。</li>}
</ul>
</section>
) : (
<>
{statedGoal && !repeatsAnswer ? (
<section className="copilot-card-row">
<h4>要做的改动</h4>
<p>{plainText(activeGoal)}</p>
</section>
) : null}
<section className="copilot-card-row">
<h4>做完怎么确认</h4>
<ul>
{activeCriteria.length ? (
activeCriteria.map(item => <li key={item}>{plainText(item)}</li>)
) : (
<li>改动完成即可。</li>
)}
</ul>
</section>
</>
)}
{message.questions?.map((question, questionIndex) => (
<fieldset className="copilot-choice" key={question.question}>
<legend>{plainText(question.question)}</legend>
@ -173,8 +472,27 @@ function WishDraft({
</button>
))}
</div>
{selected[questionIndex] !== undefined && (
<div className="copilot-choice-preview">
<span>
选择此项后,需求目标将调整为:
<strong>
{plainText(
withAnswers(baseGoal, [plainText(question.options[selected[questionIndex]!]?.wish ?? '')]),
)}
</strong>
{question.options[selected[questionIndex]!]?.acceptanceCriterion ? (
<span>
(新增验收标准:
{plainText(question.options[selected[questionIndex]!]!.acceptanceCriterion!)})
</span>
) : null}
</span>
</div>
)}
</fieldset>
))}
{error ? (
<p role="alert" className="copilot-error">
{plainText(error)}
@ -186,7 +504,12 @@ function WishDraft({
查看这次改动 <ExternalLink size={14} />
</Link>
) : (
<button type="button" className="copilot-primary" disabled={busy || !goal} onClick={() => void submit()}>
<button
type="button"
className="copilot-primary"
disabled={busy || !activeGoal}
onClick={() => void submit()}
>
{busy ? '正在提交…' : '确认,开始处理'}
</button>
)}
@ -195,19 +518,26 @@ function WishDraft({
);
}
/** The answer as it arrives: reasoning folded away, a short progress line, then the words. */
/** The answer as it arrives: reasoning folded away, step list, diagnosis card, then words. */
function StreamingAnswer({
state,
onRetry,
onProvideInfo,
onShowWish,
}: {
state: {
content: string;
thinking: string;
progress: string;
steps?: CopilotStreamStep[];
streaming: boolean;
error: string;
errorCode?: string;
diagnosis?: unknown;
};
onRetry: () => void;
onProvideInfo?: () => void;
onShowWish?: () => void;
}) {
if (!state.streaming && !state.content && !state.error && !state.thinking) return null;
return (
@ -222,34 +552,54 @@ function StreamingAnswer({
<p>{plainText(state.thinking)}</p>
</details>
) : null}
{state.progress ? (
{state.steps?.length ? (
<ToolSteps steps={state.steps} />
) : state.progress ? (
<p className="copilot-progress" role="status">
{state.progress}
</p>
) : null}
{state.content ? (
<p className="copilot-answer">
{plainText(state.content)}
<div className="copilot-answer">
<SafeMarkdown content={state.content} />
{state.streaming ? (
<span className="copilot-cursor" aria-hidden>
▊
</span>
) : null}
</p>
</div>
) : null}
{state.streaming && !state.content && !state.progress ? (
{state.diagnosis ? (
<DiagnosisCard
diagnosis={state.diagnosis as CopilotDiagnosis}
onProvideInfo={onProvideInfo}
onShowWish={onShowWish}
/>
) : null}
{state.streaming && !state.content && !state.progress && !state.steps?.length ? (
<p className="copilot-progress" role="status">
正在准备回答…
</p>
) : null}
{state.error ? (
<div className="copilot-error-card">
<div className="copilot-error-title">
<AlertTriangle size={15} />
<strong>{state.errorCode === 'upstream_unavailable' ? '上游服务暂时不可用' : '出错了'}</strong>
</div>
<p role="alert">{plainText(state.error)}</p>
<button type="button" className="copilot-secondary" onClick={onRetry}>
<RefreshCw size={14} /> 重试
</button>
</div>
) : null}
{!state.streaming && state.content ? <MessageActionBar content={state.content} /> : null}
</div>
</article>
);
@ -259,17 +609,23 @@ function Message({
message,
projectId,
sessionId,
steps,
onCreated,
onQuickReply,
onRetry,
onProvideInfo,
}: {
message: CopilotMessage;
projectId: string;
sessionId: string;
steps?: CopilotStreamStep[];
onCreated: () => void;
onQuickReply: (reply: string) => void;
onRetry: () => void;
onProvideInfo?: () => void;
}) {
const [forceShowWish, setForceShowWish] = useState(false);
if (message.role === 'user')
return (
<div className="copilot-message user">
@ -281,6 +637,7 @@ function Message({
</div>
</div>
);
if (message.status === 'error')
return (
<article className="copilot-message assistant is-error">
@ -289,6 +646,10 @@ function Message({
</span>
<div className="copilot-bubble">
<div className="copilot-error-card">
<div className="copilot-error-title">
<AlertTriangle size={15} />
<strong>回答中断</strong>
</div>
<p role="alert">{plainText(message.content || '这次没能回答上,请重试。')}</p>
<button type="button" className="copilot-secondary" onClick={onRetry}>
<RefreshCw size={14} /> 重试
@ -297,6 +658,10 @@ function Message({
</div>
</article>
);
const showWishDraft =
message.status === 'complete' && (['bug', 'feature'].includes(message.kind ?? '') || forceShowWish || message.wish);
return (
<article className={`copilot-message assistant ${message.status}`}>
<span className="copilot-avatar" aria-hidden>
@ -309,7 +674,11 @@ function Message({
</p>
) : (
<>
<p className="copilot-answer">{plainText(message.content)}</p>
{steps?.length ? <ToolSteps steps={steps} /> : null}
<div className="copilot-answer">
<SafeMarkdown content={message.content} />
</div>
{message.kind ? (
<span className={`copilot-kind ${message.kind}`}>
{message.kind === 'bug' ? (
@ -322,10 +691,21 @@ function Message({
{kindLabels[message.kind]}
</span>
) : null}
{message.diagnosis ? (
<DiagnosisCard
diagnosis={message.diagnosis}
onProvideInfo={onProvideInfo}
onShowWish={() => setForceShowWish(true)}
/>
) : null}
<Sources message={message} />
{message.status === 'complete' && ['bug', 'feature'].includes(message.kind ?? '') ? (
{showWishDraft ? (
<WishDraft message={message} projectId={projectId} sessionId={sessionId} onCreated={onCreated} />
) : null}
{message.status === 'complete' && message.quickReplies?.length ? (
<div className="copilot-quick-replies">
{message.quickReplies.map(reply => (
@ -335,6 +715,8 @@ function Message({
))}
</div>
) : null}
{message.status === 'complete' && message.content ? <MessageActionBar content={message.content} /> : null}
</>
)}
</div>
@ -366,18 +748,24 @@ export function CopilotPanel({
const [pendingUser, setPendingUser] = useState('');
const [lastPrompt, setLastPrompt] = useState('');
const [pictures, setPictures] = useState<PendingPicture[]>([]);
const [showScrollBottom, setShowScrollBottom] = useState(false);
const [lastSteps, setLastSteps] = useState<CopilotStreamStep[]>([]);
const stream = useCopilotStream();
const streaming = stream.state.streaming;
const scroller = useRef<HTMLDivElement>(null);
useEffect(() => {
setChosenProject(current => current || localStorage.getItem('wishforge.copilot.project') || '');
}, []);
useEffect(() => {
if (routeProject && variant === 'drawer') {
localStorage.setItem('wishforge.copilot.project', routeProject);
setChosenProject(routeProject);
}
}, [routeProject, variant]);
useEffect(() => {
if (projectId) localStorage.setItem('wishforge.copilot.project', projectId);
setSessionId(projectId ? (localStorage.getItem(sessionKey(projectId)) ?? '') : '');
@ -385,36 +773,69 @@ export function CopilotPanel({
setPendingUser('');
setPictures([]);
stream.reset();
// A project switch starts a fresh conversation view; the stored sessions are per project.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId]);
// A streaming answer replaces polling: while it runs the transcript is local, and when it ends
// the stored session is read once. Polling stays for a session opened on another device.
useEffect(() => {
if (sessionId) {
try {
const saved = sessionStorage.getItem(`wishforge.copilot.steps.${sessionId}`);
if (saved) setLastSteps(JSON.parse(saved));
else setLastSteps([]);
} catch {
setLastSteps([]);
}
} else {
setLastSteps([]);
}
}, [sessionId]);
const sessionResource = useResource<CopilotSession>(
open && projectId && sessionId ? `/projects/${projectId}/copilot/sessions/${sessionId}` : null,
0,
);
const pending = sessionResource.data?.messages.some(message => message.status === 'pending');
useEffect(() => {
if (!pending || !open || streaming) return;
const timer = window.setInterval(() => void sessionResource.mutate(), 3000);
return () => window.clearInterval(timer);
}, [pending, open, streaming, sessionResource.mutate]);
const messages = sessionResource.data?.projectId === projectId ? sessionResource.data.messages : [];
// One answer, one place. While it streams the local copy is the only one; once the stored message
// is in the transcript that becomes the answer, so the streamed text steps aside.
const streamedText = stream.state.content.trim();
const answerAlreadyStored =
Boolean(streamedText) &&
messages.some(message => message.role === 'assistant' && message.content.trim() === streamedText);
const showStream =
streaming || Boolean(stream.state.error) || (Boolean(stream.state.content) && !answerAlreadyStored);
// A new message scrolls itself into view, so the answer is never written below the fold.
const transcript = messages.length + (pendingUser ? 1 : 0);
// Auto-scroll threshold: only stick to bottom if user is already within 120px from bottom
useEffect(() => {
const element = scroller.current;
if (element) element.scrollTop = element.scrollHeight;
}, [transcript, stream.state.content, stream.state.progress]);
if (!element) return;
const isNearBottom = element.scrollHeight - element.scrollTop - element.clientHeight < 120;
if (isNearBottom) {
element.scrollTop = element.scrollHeight;
}
}, [transcript, stream.state.content, stream.state.progress, stream.state.steps]);
const handleScroll = () => {
const element = scroller.current;
if (!element) return;
const isNearBottom = element.scrollHeight - element.scrollTop - element.clientHeight < 120;
setShowScrollBottom(!isNearBottom);
};
const scrollToBottom = () => {
const element = scroller.current;
if (element) {
element.scrollTo({ top: element.scrollHeight, behavior: 'smooth' });
setShowScrollBottom(false);
}
};
const ensureSession = async () => {
if (sessionId) return sessionId;
@ -424,6 +845,7 @@ export function CopilotPanel({
setSessionId(created.id);
return created.id;
};
const upload = async (file: File, id: string) => {
const response = await fetch(
`/api/projects/${projectId}/copilot/sessions/${id}/attachments?name=${encodeURIComponent(file.name)}`,
@ -439,6 +861,7 @@ export function CopilotPanel({
if (!response.ok) throw new Error(payload?.error?.message ?? '图片没能上传,请重试。');
return payload.data as { id: string; name: string; size: number; contentType: string; url: string };
};
const pickFiles = async (files: File[]) => {
if (!projectId) {
setError('请先选择一个项目。');
@ -468,8 +891,6 @@ export function CopilotPanel({
problem ? { ...picture, status: 'error' as const, error: problem } : picture,
),
]);
// The session has to exist before a picture can belong to it; creating it here also keeps the
// upload and the question in the same conversation.
let id = '';
try {
id = await ensureSession();
@ -499,6 +920,7 @@ export function CopilotPanel({
}
}
};
const newSession = () => {
if (projectId) localStorage.removeItem(sessionKey(projectId));
setSessionId('');
@ -507,6 +929,7 @@ export function CopilotPanel({
setPictures([]);
stream.reset();
};
const send = async (text?: string) => {
const content = (text ?? input).trim();
if (!projectId || !content || streaming) return;
@ -523,17 +946,29 @@ export function CopilotPanel({
setPictures([]);
try {
const id = await ensureSession();
// Extract task / request ID if present in content
const taskMatch = content.match(/\bannotation-task-[A-Za-z0-9_-]{1,100}\b/);
const reqMatch = content.match(/\b[a-f0-9]{32}\b/);
const context: { pathname?: string; taskId?: string; requestId?: string } = { pathname };
if (taskMatch) context.taskId = taskMatch[0];
if (reqMatch) context.requestId = reqMatch[0];
await stream.start({
projectId,
sessionId: id,
content,
clientId: browserId(),
...(attached.length ? { attachments: attached } : {}),
context: { pathname },
context,
onDone: () => {
setPendingUser('');
// The stored message replaces the streamed one. Read it back first, then clear the stream,
// so the answer is never on screen twice and never blinks away in between.
if (stream.state.steps.length) {
setLastSteps(stream.state.steps);
try {
sessionStorage.setItem(`wishforge.copilot.steps.${id}`, JSON.stringify(stream.state.steps));
} catch {}
}
void sessionResource
.mutate()
.catch(() => undefined)
@ -561,7 +996,7 @@ export function CopilotPanel({
</span>
<span>
<strong>项目 Copilot</strong>
<small>问项目、报问题、提需求</small>
<small>问项目、报问题、排查故障</small>
</span>
</div>
<div className="copilot-header-actions">
@ -605,35 +1040,59 @@ export function CopilotPanel({
))}
</select>
</div>
<div className="copilot-messages" aria-live="polite" ref={scroller}>
{!projectId ? <Notice>选择一个项目后,可以询问它的用法、报告问题或提出需求。</Notice> : null}
<div className="copilot-messages" aria-live="polite" ref={scroller} onScroll={handleScroll}>
{!projectId ? <Notice>选择一个项目后,可以询问它的用法、报告问题或排障定位。</Notice> : null}
{projectId && !messages.length && !showStream && !sessionResource.isLoading ? (
<div className="copilot-welcome">
<span className="copilot-welcome-icon">
<Sparkles size={22} />
</span>
<h2>你好!我是 WishForge 助手 👋</h2>
<p>可以帮你定位问题、提改进建议。试试这些:</p>
<h2>你好!我是项目 Copilot 👋</h2>
<p>我可以结合当前项目资料帮你排查问题或提出改动:</p>
<div className="copilot-quick-replies">
{scenes.map(scene => (
<button type="button" key={scene} onClick={() => void send(scene)}>
<button
type="button"
key={scene}
onClick={() => {
if (scene.includes('填入编号')) {
setInput('平台任务报错了,编号是 annotation-task-,现象是:');
const inputEl = document.querySelector<HTMLTextAreaElement>('.copilot-composer textarea');
inputEl?.focus();
} else {
void send(scene);
}
}}
>
{scene}
</button>
))}
</div>
</div>
) : null}
{messages.map(message => (
<Message
key={message.id}
message={message}
projectId={projectId}
sessionId={sessionId}
onCreated={() => void sessionResource.mutate()}
onQuickReply={reply => void send(reply)}
onRetry={() => void send(lastPrompt)}
/>
))}
{messages.map((message, idx) => {
const isLastAssistant =
message.role === 'assistant' && idx === messages.map(m => m.role).lastIndexOf('assistant');
return (
<Message
key={message.id}
message={message}
projectId={projectId}
sessionId={sessionId}
steps={isLastAssistant ? lastSteps : undefined}
onCreated={() => void sessionResource.mutate()}
onQuickReply={reply => void send(reply)}
onRetry={() => void send(lastPrompt)}
onProvideInfo={() => {
const inputEl = document.querySelector<HTMLTextAreaElement>('.copilot-composer textarea');
inputEl?.focus();
}}
/>
);
})}
{pendingUser && !messages.some(message => message.role === 'user' && message.content === pendingUser) ? (
<div className="copilot-message user">
<div className="copilot-bubble">
@ -641,7 +1100,16 @@ export function CopilotPanel({
</div>
</div>
) : null}
<StreamingAnswer state={stream.state} onRetry={() => void send(lastPrompt)} />
<StreamingAnswer
state={stream.state}
onRetry={() => void send(lastPrompt)}
onProvideInfo={() => {
const inputEl = document.querySelector<HTMLTextAreaElement>('.copilot-composer textarea');
inputEl?.focus();
}}
/>
{sessionResource.error ? (
<ErrorNotice error={sessionResource.error} retry={() => void sessionResource.mutate()} />
) : null}
@ -650,7 +1118,14 @@ export function CopilotPanel({
{error}
</p>
) : null}
{showScrollBottom && (
<button type="button" className="copilot-scroll-bottom" onClick={scrollToBottom}>
<ArrowDown size={13} /> 回到底部
</button>
)}
</div>
<CopilotComposer
value={input}
onChange={setInput}

View File

@ -0,0 +1,294 @@
# Copilot 定位问题:诊断工具与对话流程方案
状态:Chief 已确认,按此实现。日期 2026-11-10。
范围:本轮 8 小时基础版。不做 MCP、不做集群部署、不重构执行器。
## 0. 现状(已读代码)
- 流式回答走 `apps/api/src/domain/copilot-stream.ts` 的 `answerStreaming`,最多 6 轮、15 次工具调用,结束必须调用 `submit_answer`。
- 只读工具在 `apps/api/src/domain/copilot-tools.ts`:Wiki、代码(git service)、提交记录、Run 摘要、日志(`WF_COPILOT_LOG_URL`,未配置)。结果统一过 `redactSecrets`、截断 24 KiB。
- 回答落库前有三道闸:引文逐字校验(`verifiedCitations`)、泄密检查(`leaksAnything`)、客户可见过滤(`customerSafe`)。
- `StreamEvent` 已经预留了 `card: 'diagnosis'`,前端还没渲染。
- **缺口 1:没有多轮上下文。** `answerStreaming` 只把当前这一句发给模型(copilot-stream.ts 第 335 行),追问后模型不记得前一句。Grill-me 必须先补上。
- **缺口 2:没有线上证据。** 只读诊断包(`.wishforge/diagnostics/fanyu-agent-readonly-kit/`)还没接进来。`capabilities` 实测:v2,`tasks`、`logs` 已配置,`egress` 未接入,`mutations: false`。
- **缺口 3:droboticflow 仓库没有 `wiki/`。** 业务规则散在它的 `docs/`(如 `annotation-five-rules.md`、`annotation-boundaries.md`、`account-management-permissions.md`)。
## 1. 服务端诊断工具
### 1.1 新模块 `apps/api/src/domain/copilot-diagnostics.ts`
```ts
export type Evidence = {
id: string; // ev-1, ev-2…:本次回答内唯一,模型下结论时要引用它
tool: 'cluster_overview' | 'task_diagnosis' | 'request_trace' | 'egress';
available: boolean; // false = 拿不到,不是“正常”
observedAt?: string; // 接口返回的采集时间
subject?: string; // 任务 ID / 请求 ID / “全部节点”
facts: string[]; // 服务端从返回值里提炼的事实句子,不是模型写的
limitations: string[]; // 接口自带 limitations + 我们固定补充的覆盖范围说明
error?: 'unavailable' | 'rate_limited' | 'not_found' | 'invalid_id' | 'auth_failed';
};
export interface Diagnostics {
clusterOverview(): Promise<Evidence>;
task(taskId: string): Promise<Evidence>;
trace(requestId: string): Promise<Evidence>;
egress(): Promise<Evidence>;
}
export function fanyuDiagnostics(env: NodeJS.ProcessEnv): Diagnostics | undefined;
```
四个模型工具,一一对应:
| 工具 | 上游路径 | 入参校验 | 服务端整理成的事实 |
| --- | --- | --- | --- |
| `cluster_overview` | nodes + pods + node-usage + pod-usage | 无入参 | 节点可分配/使用率;未就绪、Pending、重启次数 >0 的 Pod;镜像版本;各自 observedAt |
| `task_diagnosis` | `tasks/{id}` | `^annotation-task-[A-Za-z0-9_-]{1,100}$` | 任务/条目/校验状态、尝试次数、错误类别、最近事件(≤20 条) |
| `request_trace` | `logs/api/{requestId}` | `^[a-f0-9]{32}$` | 匹配到的结构化请求记录:时间、路径模板、状态码、耗时 |
| `egress` | `egress` | 无入参 | 现在固定 503 → `available:false`,说明“带宽监控未接入,不代表零流量” |
`cluster_overview` 四个接口在服务端合并成一次工具调用,算 1 次工具、4 次上游请求。只返回提炼后的摘要,不把原始 JSON 整个塞给模型。
### 1.2 key 加载
- 只认一个环境变量:`WF_DIAGNOSTIC_KIT_DIR`(本地指向 `.wishforge/diagnostics/fanyu-agent-readonly-kit`)。也可分别用 `WF_DIAGNOSTIC_KEY_FILE`、`WF_DIAGNOSTIC_CA_FILE`。base URL 用 `WF_DIAGNOSTIC_BASE_URL`,默认 `https://120.48.180.80/agent`。
- key 在第一次调用时由服务端从**文件路径**读入,存在模块闭包里。不放进 `process.env`,不进 `ToolContext`,不进日志、错误信息、审计记录。
- 未配置任何一项 → `fanyuDiagnostics` 返回 `undefined`,四个工具不出现在工具列表里,模型也就不会调用。
- TLS:用 `node:https` 带 `ca` 选项校验,不关证书校验;不跟随重定向(3xx 当失败);超时 15 s;响应上限 1 MiB。
- 只对开了诊断的项目生效:`WF_COPILOT_DIAGNOSTICS_PROJECTS=<projectId,...>`(本轮只放 droboticflow 项目)。
### 1.3 限流
- 进程内令牌桶:**每分钟 40 次**(上限 60,这个 key 是多个 agent 共用的,留余量),并发 2。
- 拿不到令牌 → 直接返回 `error:'rate_limited'`,不排队等。模型照实告诉客户“查询太频繁,稍后再试”。
- 不做 ID 枚举:一次回答里 `task_diagnosis` 和 `request_trace` 各最多 3 次,超出返回固定提示。
### 1.4 缓存
| 资源 | TTL | 说明 |
| --- | --- | --- |
| nodes / pods / usage | 30 s | 上游本来就 30 s 刷新一次 |
| tasks / logs | 15 s | 上游也缓存 15 s,失败结果同样缓存 |
| egress | 60 s | 失败也缓存,避免每次都打一遍 503 |
同一个 key 的并发请求合并成一次(single-flight)。
### 1.5 错误处理
| 上游 | 处理 |
| --- | --- |
| 401 / 403 | 不重试。`auth_failed`,记 warn 日志(只记状态码),整个进程熔断 10 分钟 |
| 404 | `not_found`(任务不存在或已删除)。说明“查不到不等于没发生” |
| 400 | `invalid_id` |
| 429 | 等 15 s 重试 1 次,再不行 `rate_limited` |
| 503 / 网络错误 / 超时 | 等 15 s 重试 1 次,再不行 `available:false, error:'unavailable'`,limitations 写“证据暂时拿不到,不能当成正常” |
一次回答整体预算 240 s,重试最多吃掉 30 s,够用。
503 一律映射成 `available:false`。不允许把它整理成“0 个异常”之类的事实句子,单测覆盖这一点。
### 1.6 key 不进模型(四层)
1. **结构隔离**:key 只在 `copilot-diagnostics.ts` 的闭包里。模型拿到的是 `Evidence` 对象,没有任何字段能装 key。
2. **出口脱敏**:工具结果照常过 `redactSecrets`。
3. **固定错误文案**:错误只给枚举码,不透传上游 body 和异常 message。
4. **单测兜底**:用假 key `fake-key-0123456789abcdef0123456789abcdef` 跑全流程,断言它不出现在:工具结果、所有 `StreamEvent`、`copilot_session`、`copilot_provider_request`、`console.warn` 输出。
另外把 `deniedToolPath` 加上 `diagnostics`、`agent.key`、`ca.crt`,代码工具碰都碰不到诊断包目录。
### 1.7 审计
沿用 `ToolAudit`:工具名、参数 hash,`detail` 里只放任务 ID / 请求 ID(不是秘密),供事后复盘。
## 2. 「定位问题」的对话流程
### 2.1 先补多轮上下文
`answerStreaming` 增加 `history` 入参:本会话最近 **10 条**已完成消息(用户原话 + 助手 `content`,再附上上一轮的诊断摘要:已取证据的 ID、结论、缺失项)。
**不回放上一轮的原始工具结果**,省 token,也避免旧证据被当成新证据。
### 2.2 四个阶段
```
收集现象 → Grill-me 追问 → 调证据 → 结论
↑______________|(证据不够就回去追问)
```
1. **收集现象**:模型先判断这是不是“东西坏了 / 结果不对”的问题。是的话,核对五要素:
谁(角色)、什么时候、在哪个页面/哪个任务、做了什么、期望 vs 实际。
2. **Grill-me 追问**:一次只问最缺的 1~2 个,每个问题带 2~4 个 `quickReplies`。例如:
- “大概什么时间?” → `刚刚` `今天上午` `昨天` `记不清`
- “方便给一下任务编号吗?在任务详情页地址栏里,以 annotation-task- 开头。”
- 问题能马上复现时:“请再点一次,然后把浏览器开发者工具里那次请求的 X-Request-ID 发给我。”(日志只保留最近 15 分钟,历史请求基本查不到,所以复现后马上查最有效)
追问最多 **3 轮**。到第 3 轮还缺,就带着现有证据下结论,并写明缺什么。
3. **调证据**:按线索选工具:
- 有任务 ID → `task_diagnosis`
- 有请求 ID → `request_trace`
- 说“很慢 / 500 / 打不开” → `cluster_overview`(看 Pod 重启、未就绪、资源打满)
- 说“下载慢 / 视频卡” → `egress`(现在会返回未接入,照实说)
- 要解释“为什么会这样” → `search_wiki` 查业务规则,`search_code` / `read_file` 查实现
4. **结论**:三选一,由 `submit_answer` 的新字段 `diagnosis.verdict` 表达:
- `problem`:确实有问题。`kind:'bug'`,出诊断卡 + Wish 草稿。草稿的 `contextSummary` 自动带上证据 ID、任务 ID、请求 ID、证据时间。
- `expected`:系统按规则在工作。`kind:'faq'`,用业务规则引文解释,不出 Wish。
- `insufficient`:证据不够。`kind:'unknown'`,列出缺失证据和客户能补什么,可选“仍然提交给工程师”按钮(生成 Wish 草稿,标注“证据不足”)。
### 2.3 事实和推测分开:服务端校验
`submit_answer` 增加:
```ts
diagnosis?: {
verdict: 'problem' | 'expected' | 'insufficient';
facts: { text: string; evidenceId: string }[]; // 必须引用本轮工具返回的 evidence id
hypotheses: { text: string; confidence: 'high' | 'medium' | 'low' }[];
missing: string[];
}
```
服务端照 `verifiedCitations` 的思路做 `verifiedFacts`:
- `evidenceId` 不在本轮证据账本里,或那条证据 `available:false` → 这条“事实”降级为推测(`confidence:'low'`)。
- `verdict:'problem'` 但一条已核实事实都没有 → 降级为 `insufficient`。
- `verdict:'expected'` 必须至少有一条核实过的 Wiki 引文,否则降级为 `insufficient`。
- 所有 `available:false` 的证据,自动加进 `missing`(如“带宽监控未接入”“日志只覆盖前两个 API Pod、最近 15 分钟”)。
- 证据时间(`observedAt`)由服务端从账本里填,不信模型写的时间。
这样“已观察到的事实”永远来自接口,模型只能组织语言、不能造事实。
### 2.4 提示词补充(加在 `TOOL_GUIDANCE` 后,仅诊断项目)
- 客户反馈异常时,先按五要素核对;缺任务编号或时间,先问,别急着下结论。
- 线上证据工具只读,只查客户给出的编号,不猜编号。
- 返回“拿不到”的证据,绝不能说成“正常”或“没有问题”。
- 当前任务状态不能证明历史上第一次失败的原因;接口延迟不能单独证明是数据库或带宽问题。
- 结论里用“已确认”“可能”区分事实和推测。
注意:`SYSTEM` 禁止出现“集群”“命名空间”,诊断卡里来源写成“线上任务记录”“线上请求记录”“线上资源情况”“带宽监控”。
## 3. droboticflow 的问题怎么答
### 3.1 资料来源
客户可见范围不变:`wiki/index.md`、`wiki/features/**`、`wiki/glossary/**`。
droboticflow 仓库本身没有 `wiki/`,所以:
1. 在本地 WishForge 里把 droboticflow 建成平台项目,导入线上版本 `e36617c0`(只在平台 git service 的副本里,不动客户共享仓库)。
2. 在这个副本上补一套 Wiki(一次提交):
- `wiki/index.md`:产品简介和页面导航
- `wiki/glossary/business-rules.md`:从 `docs/annotation-five-rules.md`、`annotation-boundaries.md`、`account-management-permissions.md` 等提炼的业务规则(送检、验收、领取、作废切片、角色权限)
- `wiki/features/*.md`:标注、送检、验收、看板各一页
规则写成可逐字引用的短句,方便 `verifiedCitations` 命中。
3. 代码工具读同一个 ref,Wiki 和代码不会错版本。
### 3.2 回答策略
- **规则类**(“为什么不能领这个任务”“验收怎么算时长”):先 `search_wiki` 找业务规则,带逐字引文,`kind:'faq'`。
- **现象类**(“送检后任务回退了”):走第 2 节诊断流程;规则用来判断是 `expected` 还是 `problem`。
- **规则文档没写**:再 `search_code` / `read_file` 看实现。回答里只说行为,不提文件和函数。没有 Wiki 引文的 faq 会被降级为 unknown,同时记入 `wiki_gap`,作为下次补 Wiki 的清单。这是现有机制,不用改。
### 3.3 WishForge 平台用法问题
本仓库的 `wiki/features/**` 是平台说明,但 Copilot 按项目取 Wiki,droboticflow 项目里查不到。
建议:服务端启动时读本仓库的 `wiki/index.md`、`wiki/features/**`、`wiki/glossary/**`,作为只读的“平台帮助”页合并进检索,路径前缀 `platform:`。引文同样逐字校验,来源显示“平台帮助”,不链到项目 Wiki 页。(需要 Chief 拍板,见第 6 节第 2 条)
## 4. 契约改动(`packages/contracts/src/copilot.ts`)
```ts
export type CopilotEvidenceSource = 'task' | 'trace' | 'cluster' | 'egress';
export type CopilotEvidence = {
id: string;
source: CopilotEvidenceSource;
label: string; // “线上任务记录”等,给客户看
subject?: string; // 任务 ID / 请求 ID
available: boolean;
observedAt?: string;
};
export type CopilotDiagnosis = {
verdict: 'problem' | 'expected' | 'insufficient';
facts: { text: string; evidenceId: string }[];
hypotheses: { text: string; confidence: 'high' | 'medium' | 'low' }[];
missing: string[];
evidence: CopilotEvidence[];
};
// CopilotMessage 增加:
// diagnosis?: CopilotDiagnosis;
```
`copilotMessageInput.context` 增加可选的 `taskId`、`requestId`(同样的正则校验):页面能拿到时由前端带上,模型不用再问。
`kind` 枚举不变,老会话和现有测试不受影响。
流式事件不新增类型:
- `tool_use.progress` 新增四句:`正在查看任务状态…`、`正在查找这次请求的记录…`、`正在查看线上运行情况…`、`正在查看带宽情况…`
- `card` 用已有的 `cardType:'diagnosis'`,`object` 为 `CopilotDiagnosis`,在 `wish` 卡之前发
- `done.summary` 带上 `diagnosis`
### 4.1 SSE 帧(11-10 定稿,前端照此接)
```ts
// 每次查看发两帧,stepId 相同
{ type:'tool_use', stepId:'step-1', phase:'start', name, progress }
{ type:'tool_use', stepId:'step-1', phase:'end', name, progress,
outcome:'ok'|'missing'|'failed', evidenceId?:'ev-1', observedAt?:string }
// 线上证据拿不到(503、过期、查无)一律 outcome:'missing',不能画成绿勾
{ type:'card', cardType:'diagnosis', object: CopilotDiagnosis } // 在 wish 卡之前
{ type:'done', summary:{ ..., diagnosis? } }
{ type:'error', code, message }
// code: rate_limited | upstream_unavailable | upstream_refused | timeout
// | no_answer | not_configured | not_found | invalid_input | internal
```
刷新后从 `CopilotMessage.diagnosis` 恢复。步骤列表不落库,只在流式时显示。
没有 `thinking` 帧(11-10 Chief 决定):模型推理会复述内部规则和猜测,只留在服务端交回模型,不下发给客户。
## 5. 前端展示(`apps/web/src/features/copilot.tsx`)
新增 `DiagnosisCard`,位置在回答正文之下、Wish 卡之上:
```
┌ 诊断结论 ─────────────── [发现问题 | 符合规则 | 证据不足] ┐
│ 已确认 │
│ • 任务 annotation-task-xxx 校验失败,第 5 次尝试, │
│ 错误类别 imu_invalid [线上任务记录 · 09:41] │
│ 可能的原因 │
│ • 送检保存时与其他写入冲突(中) │
│ 还缺的证据 │
│ • 当时那次请求的记录(日志只保留最近 15 分钟) │
└────────────────────────────────────────────────────────────┘
```
- 结论徽标三色:发现问题(红)、符合规则(绿)、证据不足(黄)。
- 每条事实后面挂来源 chip:来源名 + 本地时间;`available:false` 的来源灰掉,悬停提示“暂时拿不到,不代表正常”。
- 推测用浅色、带“高/中/低”。
- `insufficient` 时底部给两个按钮:`我去补充信息`(聚焦输入框)、`仍然交给工程师`(展开 Wish 草稿)。
- 进度行复用现有 `copilot-progress`,显示上面四句中文。
- 刷新后从 `message.diagnosis` 恢复,和 Wish 卡一致。
## 6. 需要 Chief 拍板
1. droboticflow 的 Wiki 由谁写:建议我来写(我已经读过它的 docs),Dev 负责把项目导入本地平台。
2. 平台帮助页合并进 droboticflow 项目检索(第 3.3 节):本轮做,还是只回答 droboticflow?建议做,改动约 40 行。
3. 限流定 40 次/分钟(共享 key 留 1/3 给其他 agent),是否可以。
## 7. 实现顺序与时间
| 步骤 | 内容 | 预计 |
| --- | --- | --- |
| 1 | `copilot-diagnostics.ts`:key 加载、TLS、令牌桶、缓存、错误映射 + 单测 | 60 分钟 |
| 2 | 四个工具接入 `copilot-tools.ts`;`deniedToolPath` 补诊断包目录 | 20 分钟 |
| 3 | `answerStreaming` 加 `history`;证据账本;`submit_answer.diagnosis`;`verifiedFacts` + 单测 | 60 分钟 |
| 4 | 契约 + 落库 + `card:'diagnosis'` 事件 | 20 分钟 |
| 5 | droboticflow Wiki 补页(依赖 Dev 导入项目) | 40 分钟 |
| 6 | 前端 `DiagnosisCard` | 45 分钟 |
| 7 | 用 case-1 跑真实对话,截图贴群 | 30 分钟 |
验证只跑 `npm run typecheck` 和相关单测:`tests/copilot-diagnostics.test.ts`(新增)、`tests/copilot.test.ts`、`tests/copilot-security.test.ts`。
## 8. 验收
- 用 `.wishforge/cases/case-1.md` 的客户原话开场,Copilot 追问不超过 3 轮,至少调一次线上证据工具。
- 诊断卡里“已确认”每条都有来源和时间;拿不到的证据出现在“还缺的证据”里。
- 结论大致定位到 case-1 后来的真实结论;如果是 `problem`,确认后创建出真实 Run 链接。
- 假 key 单测通过:key 不出现在任何工具结果、事件、落库记录和日志里。

View File

@ -47,6 +47,21 @@ Copilot 和愿望优化走同一个模型通道:每次调用都显式带 `--mo
集群 POC 的 Secret `wishforge-claude` 由容器入口复制成 `claude-home-api/.claude/settings.json`,只服务上面第 2 条的本机登录路径(POC 是 development 模式);Copilot 代码不直接读它,生产部署也不依赖它。
## 线上诊断(只读)
开了诊断的项目,Copilot 在客户反馈异常时会先追问,再查线上证据,最后给出诊断卡:结论(发现问题 / 符合规则 / 证据不足)、已确认的事实(每条带来源和证据时间)、推测和还缺的证据。设计见 `docs/copilot-diagnostics-plan.md`。
| 设置 | 作用 |
| --- | --- |
| `WF_DIAGNOSTIC_KIT_DIR` | 只读诊断包目录,服务端从里面按文件读 `agent.key` 和 `ca.crt`;也可用 `WF_DIAGNOSTIC_KEY_FILE`、`WF_DIAGNOSTIC_CA_FILE` 分别指定 |
| `WF_DIAGNOSTIC_BASE_URL` | 诊断网关地址,默认 `https://120.48.180.80/agent` |
| `WF_COPILOT_DIAGNOSTICS_PROJECTS` | 逗号分隔的项目 ID;只有这些项目的 Copilot 能看到诊断工具 |
- key 只在服务端模块内部,不进环境变量、提示词、工具结果、日志或回答。
- 每分钟最多 40 次(共享 key 留余量),并发 2;资源快照缓存 30 秒,任务和请求记录缓存 15 秒。
- 429、503 和网络错误等 15 秒重试一次,仍失败就记为「拿不到」,不会当成正常;401/403 不重试,暂停 10 分钟。
- 请求记录只保留最近 15 分钟。查不到时,诊断卡会提示客户复现并记下 X-Request-ID。
## 运行与验证
```bash

View File

@ -0,0 +1,116 @@
# Copilot 前端借鉴清单(GitHub 调研)
> 调研人:searcher · 2026-11-10 · 状态:待 Chief 确认
> 目的:给 Copilot「对话定位客户问题」的前端改造提供有出处的借鉴点,按「投入小、效果大」排序。
> 现状代码:`apps/web/src/features/copilot.tsx`(676 行)、`apps/web/src/features/copilot-stream.ts`、`apps/web/src/features/copilot-composer.tsx`、契约 `packages/contracts/src/copilot.ts`、协议 `apps/api/src/domain/copilot-stream.ts`。
## 0. 复用总判断(先看这个)
- **本仓库没有 Tailwind/shadcn**:`apps/web` 只有 `next/react/swr/lucide-react`(package.json),样式全在 `apps/web/src/app/globals.css` 手写 `.copilot-*` 类(:3282 起)。
- 因此 **assistant-ui、ai-elements、streamdown、vercel/chatbot 都不整包引入**(它们依赖 Tailwind + shadcn CSS 变量,迁移成本 > 收益)。正确姿势:**借交互结构和文案模式,在现有组件里手写**;唯一建议新增的依赖是 `react-markdown`(见第 4 条)。
- ai-elements 注意:README 顶部声明 2026-11 底迁移进 shadcn/ui,引用时按「模式参考」而非长期依赖对待。
候选项目与量级(GitHub API 实测,2026-11-10):
| 项目 | stars | 参考价值 |
| --- | --- | --- |
| [open-webui](https://github.com/open-webui/open-webui) | 158,304 | 引用弹层、状态历史(多步过程)、错误态 |
| [LobeChat(lobehub)](https://github.com/lobehub/lobehub) | 84,848 | 思考折叠面板、自动滚动阈值、追问建议 |
| [vercel/chatbot(原 ai-chatbot)](https://github.com/vercel/ai-chatbot) | 21,042 | Next.js 对话模板整体结构、多会话管理 |
| [assistant-ui](https://github.com/assistant-ui/assistant-ui) | 13,046 | 工具调用状态语义、ActionBar、Suggestion |
| [microsoft/vscode-copilot-chat](https://github.com/microsoft/vscode-copilot-chat) | 9,939 | 请求步骤渐进披露、followup 数据流 |
| [streamdown](https://github.com/vercel/streamdown) | 5,752 | 流式 Markdown 的「未闭合块」处理思路 |
| [react-markdown](https://github.com/remarkjs/react-markdown) | 15,936 | 可直接引入的渲染器 |
| [ai-elements](https://github.com/vercel/ai-elements) | 2,514 | 组件语义清单(message/reasoning/sources/tool/confirmation…) |
---
## 借鉴点(按投入小→效果大排序)
### 1. 证据卡:区分「已观察事实 / 推测」,并带上证据时间与知识版本 —— 投入 ~1 小时
- **出处**:open-webui 引用实现 [`Citations.svelte`](https://github.com/open-webui/open-webui/blob/main/src/lib/components/chat/Messages/Citations.svelte):来源带相关度、点开是弹层,正文只留编号;ai-elements 的 [`sources`](https://elements.ai-sdk.dev/api/registry/sources.json) 与 [`inline-citation`](https://elements.ai-sdk.dev/api/registry/inline-citation.json) 组件也是同样分工(正文内联编号 + 底部来源列表)。
- **现状差距**:`copilot.tsx:21-36` 的 `Sources` 只渲染 title + excerpt;契约里 `CopilotSource.version`(contracts/copilot.ts:7)、`message.knowledgeVersion`(:34)、`message.createdAt`(:29)**字段都在、一个都没渲染**。群规则要求「写明证据时间和缺失的证据」,现在做不到。
- **改哪里**:
1. `Sources` 头部渲染「来源快照 · Wiki 版本 {knowledgeVersion 短 hash} · 回答于 {createdAt HH:mm}」(11px `--wf-text-muted`,对齐 `docs/design/tokens.md`)。
2. 每条来源标题后加序号上标 `[1]`,正文回答里的对应句子标同序号(纯文本方案即可,不做 hover 弹层)。
3. 诊断结论渲染走已定稿的 `CopilotMessage.diagnosis`(contracts/copilot.ts:24-43,claude 11-10 落库),字段映射:`verdict`(problem=发现问题/expected=符合规则/insufficient=证据不足)画成结论徽标;`facts[]`(text+evidenceId)画「已确认」,每条的时间取对应 `evidence[].observedAt`(服务端实测时间,勿用模型措辞);`hypotheses[]`(text+confidence)画「可能原因」;`missing[]` 画「还缺的证据」。`evidence[].available === false` 必须画灰/警示,绝不能进「已确认」。恢复历史消息和流式中(`card:'diagnosis'`)用同一组件。
### 2. 错误态分类:503 / 429 / 中断各说各话,不许显示成「正常」—— 投入 ~40 分钟
- **出处**:open-webui 在 [`ResponseMessage.svelte:886-954`](https://github.com/open-webui/open-webui/blob/main/src/lib/components/chat/Messages/ResponseMessage.svelte) 把 `message.error` 作为一等状态与正常回答互斥渲染;assistant-ui 的工具/消息状态语义(running→incomplete→error,[tools 文档](https://github.com/assistant-ui/assistant-ui/tree/main/apps/docs/content/docs/tools))同样是「错误必须可见、可重试」。
- **现状差距**:前端 SSE 类型里 `{type:'error'; code?: string}`(copilot-stream.ts:17)**声明了 code 但处理时丢弃**(:108-109 只取 message);服务端协议(apps/api/src/domain/copilot-stream.ts:30)压根**不发 code**。`docs/copilot.md:46` 定义的 `COPILOT_UNAVAILABLE`(503) 只能靠裸文案看出来,客户容易把「服务不通」误读成「没问题」。
- **改哪里**(服务端 11-10 已落地,取值为 claude 定稿的枚举,见 `docs/copilot-diagnostics-plan.md` §4.1):error 帧带 `code` ∈ `rate_limited`(429) / `upstream_unavailable`(503/5xx) / `upstream_refused`(其他 4xx) / `timeout` / `no_answer` / `not_configured` / `not_found` / `invalid_input` / `internal`;前端 `copilot-stream.ts` 把 code 存进 state,`StreamingAnswer`(copilot.tsx:245-252)按 code 出文案:`upstream_unavailable`→「诊断服务暂不可用,这不是正常结果」;`rate_limited`→「查询太频繁,约 Xs 后可再试」。**任何 error 帧都不得渲染成正常回答**(Chief 转 claude 规则)。样式用 `docs/design/tokens.md` 1.2 的 Danger/Warning 底色。
### 3. 滚动:用户往上读时别硬拽回底部,加「回到底部」胶囊 —— 投入 ~30 分钟
- **出处**:LobeChat 的思考面板用 `useAutoScroll({ threshold: 120 })` 控制跟滚([`Thinking/index.tsx`](https://github.com/lobehub/lobehub/blob/main/src/features/Conversation/components/Thinking/index.tsx),滚动仅在阈值内生效);vercel/chatbot 的 conversation 组件也是「贴底才跟流」。
- **现状差距**:`copilot.tsx:414-417` 每个 delta 都无条件 `scrollTop = scrollHeight`,流式期间客户翻历史记录会被不断拽回。
- **改哪里**:`CopilotPanel` 里先判断 `scrollHeight - scrollTop - clientHeight < 120` 才自动滚;否则在 `copilot-messages` 底部悬一个「↓ 回到底部」小胶囊(新 CSS 类,走现有 token)。十几行改动。
### 4. 回答用 Markdown 渲染(日志、步骤、小代码块)—— 投入 ~1.5 小时
- **出处**:[streamdown](https://github.com/vercel/streamdown) README(实测抓取):专为 AI 流式场景设计,处理「未闭合 Markdown 块」(remend)、GFM 表格、代码高亮、`rehype-harden` 安全渲染;它是 ai-elements `message` 组件的底座。但它要求 Tailwind `@source` 和 shadcn CSS 变量——本仓库没有 Tailwind,**不直接装**。
- **现状差距**:`copilot.tsx` 全文用 `plainText()`(:231、:277 等),Copilot 引日志片段、列复现步骤时全是糊在一起的一坨纯文本;`docs/design/pages.md:38-47` 线框里的编号列表/代码片段根本表达不出来。
- **改哪里**:`apps/web` 加依赖 `react-markdown` + `remark-gfm`(15.9k stars,无 Tailwind 依赖,输出 React 元素、不 innerHTML,XSS 面小)。渲染前仍先过现有 `plainText` 的源码路径/行号过滤——**过滤逻辑绝不能随 markdown 化丢掉**(`docs/copilot.md:16` 是客户可见范围的硬约束)。流式尾部按 streamdown 思路做简化处理:`**`、``` 未闭合时先按纯文本追加。样式在 globals.css 新增 `.copilot-md`(列表缩进、`code` 用 `--wf-bg-subtle` + 等宽栈)。思考折叠(:219-224)保持纯文本。
### 5. 工具调用「步骤列表」渐进披露,而不是一行覆盖一行 —— 投入 ~2 小时(前后端各一半)
- **出处**:assistant-ui 的 [Tool Status API](https://github.com/assistant-ui/assistant-ui/blob/main/apps/docs/content/docs/(reference)/api-reference/tools/status.mdx)(实测抓取):每步 running/success/error + `useToolArgsElapsed` 耗时;open-webui 的 [`StatusHistory.svelte`](https://github.com/open-webui/open-webui/blob/main/src/lib/components/chat/Messages/StatusHistory.svelte) 把多阶段状态存成列表渲染(ResponseMessage.svelte:741 传入 `statusHistory`)。
- **现状差距**:SSE 已发 `tool_use {name, progress}`(apps/api:27),前端只把 progress 存成**单个字符串**、每步把上一步顶掉(copilot-stream.ts:107),`name` 直接丢弃。诊断要连查 nodes→pods→tasks→logs 四五步,客户只能看见最后一句,过程感为零。
- **改哪里**(服务端 11-10 已落地,帧结构见 `docs/copilot-diagnostics-plan.md` §4.1):每步两帧 `tool_use{stepId, phase:'start'|'end', name, progress, outcome?, evidenceId?, observedAt?}`,`outcome` ∈ ok/missing/failed。前端把两帧按 stepId 收敛成 `steps[]`,`StreamingAnswer` 默认一行(当前步 + LoaderCircle 转圈),完成后可展开「排查步骤(N)」:ok=✓、failed=✗、**missing=灰/警示色,绝不画绿勾**(证据没拿到不是好消息)。步骤列表不落库:刷新后历史消息只靠 `diagnosis` 卡恢复,无步骤条。
### 6. 消息操作条:复制结论 / 复制整条回答 —— 投入 ~20 分钟
- **出处**:assistant-ui 的 [ActionBar primitive](https://github.com/assistant-ui/assistant-ui/blob/main/apps/docs/content/docs/primitives/action-bar.mdx)(copy/reload/edit 是标准件);vercel/chatbot 每条回答下有 actions 行。
- **现状差距**:全仓库没有任何复制按钮;而 `docs/design/pages.md:54` 线框明确画了「仅复制结论」——客户要把诊断结论贴回飞书群是主场景(Lark 的 case-1 就来自群聊)。
- **改哪里**:`Message` 完成态气泡尾部加 hover 显示的图标行(`Copy`/`RefreshCw` 已有 lucide):复制结论 = 复制 `content`;重试已有(:634)。`navigator.clipboard.writeText` + 「已复制」toast 文案,20 行内。
### 7. Grill-me 选项:选中即预览对目标的影响 —— 投入 ~30 分钟
- **出处**:ai-elements [`confirmation`](https://elements.ai-sdk.dev/api/registry/confirmation.json)(执行前把「将发生什么」摆出来确认)与 assistant-ui [`suggestion`](https://github.com/assistant-ui/assistant-ui/blob/main/apps/docs/content/docs/primitives/suggestion.mdx) 的「选一下 → 立刻反映到后续」语义。
- **现状差距**:`copilot.tsx:160-177` 的选项按钮选中后(168 行 `selected` 态),卡片其余部分**毫无变化**——`goal`/`criteria` 已经实时算好了(:100-101)却没展示,客户不知道点这个按钮会改变什么。
- **改哪里**:fieldset 下方加一行浅色预览「选这个后,需求目标会变成:…(新增验收标准:…)」;`quickReplies`(:329-337)保持现状即可,样式统一成 tokens.md 的胶囊。
### 8. Wish 草稿可编辑再提交 —— 投入 ~1 小时
- **出处**:assistant-ui 的 generative UI / form 语义(工具产出的确认卡允许用户改参数再放行,[tools 文档](https://github.com/assistant-ui/assistant-ui/tree/main/apps/docs/content/docs/tools));vercel/chatbot 的 artifact/编辑模式同理。
- **现状差距**:`WishDraft`(copilot.tsx:68-196)的目标和验收标准全是只读段落,客户只能原样提交或放弃;`goal` 短于 8 字时还靠 :111 自动拼前缀兜底,客户看不到拼完的样子。
- **改哪里**:goal / acceptanceCriteria 改成 `textarea`(默认值 = AI 草稿),提交用编辑后的值;校验沿用现有(≥8 字、非空)。契约不用动(`copilotWishInput` 已收 goal/criteria,contracts/copilot.ts:75-82)。
### 9. 空态与追问话术:引导客户给出任务 ID / 请求 ID —— 投入 ~20 分钟(文案级)
- **出处**:vercel/chatbot 的 prompt suggestions(空态胶囊 → 一键成句);LobeChat 空会话同样用可点问题引导。
- **现状差距**:`copilot.tsx:610-624` 空态已有 3 个 scene,但都不带信息量;`docs/design/pages.md:127-129` 要求空态说明「已挂载当前项目 Wiki 与集群只读监控」(该词仅内部线框用,对客户措辞见下)——现在客户不知道 Copilot 能查线上。Lark 已确认 case-1 的缺口正是**没有 annotation-task ID 和 X-Request-ID**(.wishforge/cases/case-1.md):客户不知道该给什么,Copilot 就只能瞎猜。
- **改哪里**:欢迎语加一句中性能力说明,如「我可以结合项目资料帮你排查问题,部分项目还能查线上运行情况和最近请求记录(只读)」——**客户可见文案不出现「集群/Pod/命名空间」(claude 11-10 评审定;我原措辞带「集群」,作废)**;scene 里加一个「任务失败了,我告诉你任务编号」示例(点开带出输入模板「平台地址是 …,任务编号 …,现象是 …」,编号=浏览器地址栏里的那串);诊断拿不到 ID 时的追问也用同一话术。**与 claude 的对话流程方案对齐,字段和文案以他为主**。
---
## 与并行工作的接缝
- 第 1/2/5/9 条涉及 SSE 帧与契约的**新增可选字段**(observations/inference、error.code、steps 帧),建议 claude 在 `docs/copilot-diagnostics-plan.md` 的契约节直接收编,避免两边各定一套。
- **11-10 对齐结果**:claude 方案已定契约加 `CopilotMessage.diagnosis`(结论/已确认/可能原因/还缺的证据),与本文第 1 条的「事实 vs 推测 + 缺证」是同一张卡——前端实现**以 claude 契约节的字段名为准**,本文第 1 条不再单独引入 observations/inference。第 2 条 `error.code` 与第 5 条 steps 帧仍需 claude 在 SSE 协议里落地,前端按此准备文案。
- 第 4 条要新增 `react-markdown + remark-gfm` 两个依赖,**Chief 已批准(11-10 群内)**;plainText 的路径过滤必须保留,这条 Chief 也点了名。
- 全部改动只动 `apps/web/src/features/copilot*` + `globals.css` + `packages/contracts`,不碰执行器与部署。
## 核验记录
- 现状行号均来自 `git@review/overhaul` 工作区实际文件(ops_read_files 全文读取);依赖缺失结论来自 `apps/web/package.json` 与 `ls tailwind.config.*`。
- 仓库 stars/描述:GitHub API `api.github.com/repos/...` 实测(2026-11-10)。
- streamdown/assistant-ui/open-webui/ai-elements 的行为描述:抓取对应 README 或源码原文(open-webui `Citations.svelte`、`ResponseMessage.svelte:211/741/886/954`;assistant-ui `tools/status.mdx`;LobeChat `Thinking/index.tsx`;ai-elements registry 实测:`message/conversation/reasoning/sources/tool/suggestion/code-block/confirmation/inline-citation/task/prompt-input/attachments` 均返回 200,`response/actions/branch/web-search-result` 返回 404——未引用)。
## 落地追踪(searcher 维护)
基线 2026-11-10 10:13 PT(复核 10:52 PT 首轮;11:05 PT 对 claude 评审 4+2 条修复二次核到代码行):`git status apps/web` 只有 `auth.ts`(第 1 阶段改动),以下 9 项全部未落地。Dev 每落地一项,searcher 收尾时逐项复核。
| # | 借鉴点 | 状态 |
| --- | --- | --- |
| 1 | 证据卡:时间 + Wiki 版本 + diagnosis 渲染 | ✅ 已落地(copilot.tsx:69-75 时间+版本、137-148 observedAt、180 missing 区、DiagnosisCard) |
| 2 | 错误态分类(error.code:503/429/中断) | ✅ 已落地(copilot-stream.ts:49 errorCode、:63-79 文案映射、:132 HTTP 层 code) |
| 3 | 流式不硬拽底 + 「回到底部」 | ✅ 已落地(copilot.tsx:793-810,120px 阈值+回到底部胶囊) |
| 4 | Markdown 渲染(react-markdown@10.1.0 + remark-gfm@4.0.1,先过滤后渲染) | ✅ 已落地(SafeMarkdown :51-61 先 plainText 过滤再渲染,流式 :559 / 历史 :670 双入口) |
| 5 | 工具步骤列表(steps) | ✅ 已落地,评审问题已修:折叠行四分支图标 copilot.tsx:219-226;running→failed 四处调用 copilot-stream.ts:95/207/234/245 |
| 6 | 复制结论/回答 | ✅ 已落地(:259-270 clipboard+「复制结论」) |
| 7 | Grill-me 选中即预览 | ✅ 已落地(copilot-choice-preview :471-485) |
| 8 | Wish 草稿可编辑 | ✅ 已落地(编辑草稿 :397) |
| 9 | 空态引导任务 ID / X-Request-ID | ✅ 已落地,评审问题已修:欢迎语无「集群」;快捷问题改为填入输入框模板(copilot.tsx:1036) |

1478
package-lock.json generated

File diff suppressed because it is too large Load Diff