✨ Show the Copilot's answer as it arrives, and confirm a wish on one card
The drawer reads a stream instead of polling every 1.5 s. A thinking block folds away, a short progress sentence says what is being looked at in the customer's words, the answer types itself with a cursor, and stopping is a button rather than closing the drawer. The wish draft becomes one card: what will change, how it will be checked, confirm. The two text areas and the eight-character minimum are gone; the card already holds the Copilot's phrasing, and the customer's job is to say yes. The drawer is wider (520px) and the composer grows with what is typed: Enter sends, Shift+Enter breaks the line.
This commit is contained in:
parent
9d9254f94d
commit
ec0978acfd
@ -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);
|
||||
|
||||
147
apps/web/src/features/copilot-stream.ts
Normal file
147
apps/web/src/features/copilot-stream.ts
Normal file
@ -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<string, unknown> }
|
||||
| { 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<string, unknown>;
|
||||
};
|
||||
const EMPTY: CopilotStreamState = { content: '', thinking: '', progress: '', streaming: false, error: '' };
|
||||
|
||||
export function useCopilotStream() {
|
||||
const [state, setState] = useState<CopilotStreamState>(EMPTY);
|
||||
const active = useRef<AbortController | null>(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 };
|
||||
}
|
||||
@ -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 (
|
||||
<div className="copilot-sources">
|
||||
<strong>依据 · Wiki {message.knowledgeVersion?.slice(0, 8)}</strong>
|
||||
<strong>参考资料</strong>
|
||||
{message.sources.map(source => (
|
||||
<div className="copilot-source" key={source.path}>
|
||||
<Link href={source.url} target="_blank">
|
||||
@ -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<Record<number, number>>({});
|
||||
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({
|
||||
))}
|
||||
</ol>
|
||||
) : (
|
||||
<p>尚未提供复现步骤,请在 Wish 中补充。</p>
|
||||
<p>还没提供复现步骤,工程师会再确认。</p>
|
||||
)}
|
||||
<strong>当前上下文</strong>
|
||||
<p>{message.contextSummary || '未提供额外上下文。'}</p>
|
||||
<strong>当时的情况</strong>
|
||||
<p>{message.contextSummary || '没有额外说明。'}</p>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="copilot-card-goal">
|
||||
<strong>要做的改动</strong>
|
||||
<p>{goal}</p>
|
||||
</div>
|
||||
<div className="copilot-card-goal">
|
||||
<strong>做完怎么确认</strong>
|
||||
<ul>{criteria.length ? criteria.map(item => <li key={item}>{item}</li>) : <li>改动完成即可。</li>}</ul>
|
||||
</div>
|
||||
{message.questions?.map((question, questionIndex) => (
|
||||
<fieldset className="grill-card" key={question.question}>
|
||||
<legend>Grill me · {question.question}</legend>
|
||||
<small>依据 {question.sourcePath}</small>
|
||||
<legend>{question.question}</legend>
|
||||
<div>
|
||||
{question.options.map((option, optionIndex) => (
|
||||
<button
|
||||
@ -126,14 +135,6 @@ function WishDraft({
|
||||
</div>
|
||||
</fieldset>
|
||||
))}
|
||||
<label>
|
||||
Wish 目标
|
||||
<textarea rows={4} value={goal} onChange={event => setGoal(event.target.value)} />
|
||||
</label>
|
||||
<label>
|
||||
验收标准(每行一条)
|
||||
<textarea rows={4} value={criteria} onChange={event => setCriteria(event.target.value)} />
|
||||
</label>
|
||||
{error ? (
|
||||
<p role="alert" className="copilot-error">
|
||||
{error}
|
||||
@ -141,32 +142,82 @@ function WishDraft({
|
||||
) : null}
|
||||
{created || message.wish ? (
|
||||
<Link className="button button-secondary copilot-wish-link" href={(created ?? message.wish)!.url}>
|
||||
查看真实 Wish 运行 <ExternalLink size={14} />
|
||||
查看这次改动 <ExternalLink size={14} />
|
||||
</Link>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
busy={busy}
|
||||
disabled={goal.trim().length < 8 || !criteria.trim()}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
确认并创建 Wish
|
||||
<Button type="button" busy={busy} disabled={!goal} onClick={() => void submit()}>
|
||||
确认,开始处理
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The answer as it arrives: reasoning folded away, a short progress line, then the words. */
|
||||
function StreamingAnswer({
|
||||
state,
|
||||
onRetry,
|
||||
}: {
|
||||
state: {
|
||||
content: string;
|
||||
thinking: string;
|
||||
progress: string;
|
||||
streaming: boolean;
|
||||
error: string;
|
||||
};
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
if (!state.streaming && !state.content && !state.error && !state.thinking) return null;
|
||||
return (
|
||||
<article className={`copilot-message assistant${state.error ? ' error' : ''}`}>
|
||||
{state.thinking ? (
|
||||
<details className="copilot-thinking">
|
||||
<summary>思考过程</summary>
|
||||
<p>{state.thinking}</p>
|
||||
</details>
|
||||
) : null}
|
||||
{state.progress ? (
|
||||
<p className="copilot-progress" role="status">
|
||||
{state.progress}
|
||||
</p>
|
||||
) : null}
|
||||
{state.content ? (
|
||||
<p className="copilot-answer">
|
||||
{state.content}
|
||||
{state.streaming ? <span className="copilot-cursor" aria-hidden /> : null}
|
||||
</p>
|
||||
) : null}
|
||||
{state.streaming && !state.content && !state.progress ? (
|
||||
<p className="copilot-progress" role="status">
|
||||
正在准备回答…
|
||||
</p>
|
||||
) : null}
|
||||
{state.error ? (
|
||||
<>
|
||||
<p role="alert" className="copilot-error">
|
||||
{state.error}
|
||||
</p>
|
||||
<button type="button" className="button button-secondary" onClick={onRetry}>
|
||||
<RefreshCw size={14} /> 重试
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function Message({
|
||||
message,
|
||||
projectId,
|
||||
sessionId,
|
||||
onCreated,
|
||||
onQuickReply,
|
||||
}: {
|
||||
message: CopilotMessage;
|
||||
projectId: string;
|
||||
sessionId: string;
|
||||
onCreated: () => void;
|
||||
onQuickReply: (reply: string) => void;
|
||||
}) {
|
||||
if (message.role === 'user')
|
||||
return (
|
||||
@ -176,7 +227,7 @@ function Message({
|
||||
);
|
||||
return (
|
||||
<article className={`copilot-message assistant ${message.status}`}>
|
||||
{message.status === 'pending' ? <p role="status">正在检索项目 Wiki 并生成有依据的回答…</p> : null}
|
||||
{message.status === 'pending' ? <p className="copilot-progress">正在查找资料…</p> : null}
|
||||
{message.status !== 'pending' ? <p className="copilot-answer">{message.content}</p> : null}
|
||||
{message.kind ? (
|
||||
<span className={`copilot-kind ${message.kind}`}>
|
||||
@ -194,12 +245,20 @@ function Message({
|
||||
{message.status === 'complete' && ['bug', 'feature'].includes(message.kind ?? '') ? (
|
||||
<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 => (
|
||||
<button type="button" key={reply} onClick={() => onQuickReply(reply)}>
|
||||
{reply}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const { mutate } = useSWRConfig();
|
||||
const pathname = usePathname();
|
||||
const projects = useResource<Project[]>('/projects');
|
||||
const routeProject = pathname.match(/^\/projects\/([^/]+)/)?.[1];
|
||||
@ -207,8 +266,12 @@ export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () =
|
||||
const projectId = routeProject || chosenProject || projects.data?.[0]?.id || '';
|
||||
const [sessionId, setSessionId] = useState('');
|
||||
const [input, setInput] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [pendingUser, setPendingUser] = useState('');
|
||||
const [lastPrompt, setLastPrompt] = useState('');
|
||||
const composer = useRef<HTMLTextAreaElement>(null);
|
||||
const stream = useCopilotStream();
|
||||
const streaming = stream.state.streaming;
|
||||
useEffect(() => {
|
||||
setChosenProject(current => current || localStorage.getItem('wishforge.copilot.project') || '');
|
||||
}, []);
|
||||
@ -222,27 +285,43 @@ export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () =
|
||||
if (projectId) localStorage.setItem('wishforge.copilot.project', projectId);
|
||||
setSessionId(projectId ? (localStorage.getItem(sessionKey(projectId)) ?? '') : '');
|
||||
setError('');
|
||||
setPendingUser('');
|
||||
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.
|
||||
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) return;
|
||||
const timer = window.setInterval(() => void sessionResource.mutate(), 1500);
|
||||
if (!pending || !open || streaming) return;
|
||||
const timer = window.setInterval(() => void sessionResource.mutate(), 3000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [pending, open, sessionResource.mutate]);
|
||||
}, [pending, open, streaming, sessionResource.mutate]);
|
||||
useEffect(() => {
|
||||
const element = composer.current;
|
||||
if (!element) return;
|
||||
element.style.height = 'auto';
|
||||
element.style.height = `${Math.min(element.scrollHeight, 160)}px`;
|
||||
}, [input]);
|
||||
const newSession = () => {
|
||||
if (projectId) localStorage.removeItem(sessionKey(projectId));
|
||||
setSessionId('');
|
||||
setError('');
|
||||
setPendingUser('');
|
||||
stream.reset();
|
||||
};
|
||||
const send = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!projectId || !input.trim() || busy) return;
|
||||
setBusy(true);
|
||||
const send = async (text?: string) => {
|
||||
const content = (text ?? input).trim();
|
||||
if (!projectId || !content || streaming) return;
|
||||
setError('');
|
||||
setInput('');
|
||||
setPendingUser(content);
|
||||
setLastPrompt(content);
|
||||
try {
|
||||
let id = sessionId;
|
||||
if (!id) {
|
||||
@ -251,23 +330,25 @@ export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () =
|
||||
localStorage.setItem(sessionKey(projectId), id);
|
||||
setSessionId(id);
|
||||
}
|
||||
const result = await mutateApi<CopilotSession>(`/projects/${projectId}/copilot/sessions/${id}/messages`, {
|
||||
content: input.trim(),
|
||||
await stream.start({
|
||||
projectId,
|
||||
sessionId: id,
|
||||
content,
|
||||
clientId: browserId(),
|
||||
context: { pathname },
|
||||
onDone: () => {
|
||||
setPendingUser('');
|
||||
void sessionResource.mutate().catch(() => undefined);
|
||||
},
|
||||
});
|
||||
setInput('');
|
||||
// A newly created session is absent from this render's bound SWR key.
|
||||
// Populate the actual session key so its first answer appears immediately.
|
||||
await mutate(`/projects/${projectId}/copilot/sessions/${id}`, result, { revalidate: false });
|
||||
} catch (failure) {
|
||||
setPendingUser('');
|
||||
setError(messageOf(failure));
|
||||
await sessionResource.mutate().catch(() => undefined);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
stream.reset();
|
||||
}
|
||||
};
|
||||
const messages = sessionResource.data?.projectId === projectId ? sessionResource.data.messages : [];
|
||||
const showStream = streaming || Boolean(stream.state.content) || Boolean(stream.state.error);
|
||||
return (
|
||||
<aside
|
||||
className={`copilot-sidebar ${open ? 'is-open' : ''}`}
|
||||
@ -279,7 +360,7 @@ export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () =
|
||||
<Bot size={19} />
|
||||
<span>
|
||||
<strong>项目 Copilot</strong>
|
||||
<small>Wiki 有源问答</small>
|
||||
<small>问项目、报问题、提需求</small>
|
||||
</span>
|
||||
</div>
|
||||
<button className="icon-button" onClick={onClose} aria-label="收起 AI Copilot">
|
||||
@ -314,12 +395,19 @@ export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () =
|
||||
</button>
|
||||
</div>
|
||||
<div className="copilot-messages" aria-live="polite">
|
||||
{!projectId ? <Notice>选择一个项目后,可以询问它的配置、使用方式和需求。</Notice> : null}
|
||||
{projectId && !messages.length && !sessionResource.isLoading ? (
|
||||
{!projectId ? <Notice>选择一个项目后,可以询问它的用法、报告问题或提出需求。</Notice> : null}
|
||||
{projectId && !messages.length && !showStream && !sessionResource.isLoading ? (
|
||||
<div className="copilot-welcome">
|
||||
<Bot size={28} />
|
||||
<h2>先问这个项目</h2>
|
||||
<p>FAQ 会引用 Wiki;疑似 Bug 和需求会整理成草稿,只有你确认后才会创建 Wish。</p>
|
||||
<p>说清楚在哪一步、点了什么、本来想看到什么,我就能查资料帮你定位。</p>
|
||||
<div className="copilot-quick-replies">
|
||||
{['你能帮我做什么?', '某个按钮点了没反应', '想把首页那句介绍改个说法'].map(scene => (
|
||||
<button type="button" key={scene} onClick={() => void send(scene)}>
|
||||
{scene}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{messages.map(message => (
|
||||
@ -329,8 +417,15 @@ export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () =
|
||||
projectId={projectId}
|
||||
sessionId={sessionId}
|
||||
onCreated={() => void sessionResource.mutate()}
|
||||
onQuickReply={reply => void send(reply)}
|
||||
/>
|
||||
))}
|
||||
{pendingUser && !messages.some(message => message.role === 'user' && message.content === pendingUser) ? (
|
||||
<div className="copilot-message user">
|
||||
<span>{pendingUser}</span>
|
||||
</div>
|
||||
) : null}
|
||||
<StreamingAnswer state={stream.state} onRetry={() => void send(lastPrompt)} />
|
||||
{sessionResource.error ? (
|
||||
<ErrorNotice error={sessionResource.error} retry={() => void sessionResource.mutate()} />
|
||||
) : null}
|
||||
@ -340,24 +435,42 @@ export function CopilotSidebar({ open, onClose }: { open: boolean; onClose: () =
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<form className="copilot-composer" onSubmit={send}>
|
||||
<form
|
||||
className="copilot-composer"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}}
|
||||
>
|
||||
<label htmlFor="copilot-question" className="sr-only">
|
||||
询问项目 Copilot
|
||||
</label>
|
||||
<textarea
|
||||
id="copilot-question"
|
||||
rows={3}
|
||||
ref={composer}
|
||||
rows={1}
|
||||
maxLength={8000}
|
||||
value={input}
|
||||
onChange={event => setInput(event.target.value)}
|
||||
placeholder="询问配置、报告 Bug 或描述需求…"
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}
|
||||
}}
|
||||
placeholder="问用法、报问题或说需求…(Enter 发送,Shift+Enter 换行)"
|
||||
/>
|
||||
<div>
|
||||
<small>回答仅使用当前项目授权 Wiki</small>
|
||||
<Button busy={busy} disabled={!projectId || !input.trim() || pending}>
|
||||
<Send size={15} />
|
||||
发送
|
||||
</Button>
|
||||
<small>{streaming ? '正在回答,可随时停止' : '回答只依据本项目的资料'}</small>
|
||||
{streaming ? (
|
||||
<Button type="button" variant="secondary" onClick={() => stream.stop()}>
|
||||
<Square size={13} /> 停止
|
||||
</Button>
|
||||
) : (
|
||||
<Button disabled={!projectId || !input.trim()}>
|
||||
<Send size={15} /> 发送
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</aside>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user