refactor(teacher): retire discussion components and keep text replies

This commit is contained in:
鲨鱼辣椒 committed 2026-09-28 13:54:55 +08:00
1 parent ae0f72d8fa
commit 998796d77c
32 files changed
+1060 -1794

No files matched your search

+14 -60
View File
@@ -10,11 +10,16 @@ import type {
TeacherTopic,
TeacherTopicList,
} from '../../../shared/coding-teacher';
import { TeacherDiscussionPanel, DiscussionFocus } from './TeacherDiscussionPanel';
import type { TeacherDiscussionAction } from '../../../shared/coding-teacher';
import { TeacherAvatar } from './TeacherAvatar';
import { TeacherReply } from './TeacherReply';
function restorePendingSend(saved?: TeacherSend): TeacherSend | null {
if (!saved) return null;
// Keep an interrupted send retryable without restoring retired UI protocol fields.
const { requestId, text, references, intent, sourceConversationId } = saved;
return { requestId, text, references, intent, sourceConversationId };
}
export function TeacherChatPanel({
projectId,
sourceId,
@@ -57,9 +62,7 @@ export function TeacherChatPanel({
try { localStorage.setItem(draftKey, JSON.stringify({ text, references, pending })); } catch { /* Draft remains in the open panel. */ }
}, [draftKey]);
const label = '智能体';
const discussionEnabled = !draftRevision;
const [historyOpen, setHistoryOpen] = useState(false);
const [focus, setFocus] = useState<{ topicId: string; id: string; label: string } | null>(null);
const [definition, setDefinition] = useState<TeacherDefinition | null>(null);
const externalTopicRef = useRef(externalTopic);
externalTopicRef.current = externalTopic;
@@ -88,7 +91,7 @@ export function TeacherChatPanel({
: topic.definition.config_id
? teachers.some((item) => item.teacher_id === topic.definition.config_id)
: legacyEnabled;
const pending = useRef<TeacherSend | null>(saved.pending ?? null);
const pending = useRef<TeacherSend | null>(restorePendingSend(saved.pending));
useEffect(() => {
persistDraft(text, references, pending.current);
}, [text, references, persistDraft]);
@@ -96,12 +99,6 @@ export function TeacherChatPanel({
const topicRef = useRef(topic);
topicRef.current = topic;
const scrollRef = useRef<HTMLDivElement>(null);
const content = topic?.discussion?.content;
const activeFocus = focus && focus.topicId === topic?.id && content && topic?.discussion?.status === 'active' && (
content.kind === 'ideas' ? content.items.some(item => item.id === focus.id)
: content.kind === 'comparison' ? content.rows.some(row => content.columns.some(column => `${row.id}:${column.id}` === focus.id))
: content.nodes.some(node => node.id === focus.id)
) ? focus : null;
useEffect(() => {
const pane = scrollRef.current;
if (pane) pane.scrollTop = pane.scrollHeight;
@@ -274,7 +271,7 @@ export function TeacherChatPanel({
if (version === generation.current) setBusy(false);
}
};
const send = async (action?: Pick<TeacherSend, 'text' | 'intent' | 'discussion'>) => {
const send = async (action?: Pick<TeacherSend, 'text' | 'intent'>) => {
const question = action?.text ?? text;
const questionReferences = action ? [] : references;
if (!question.trim() || busy || !topicEnabled || topicRef.current?.requests.some((request) => ['preparing', 'running'].includes(request.status))) return;
@@ -294,24 +291,17 @@ export function TeacherChatPanel({
consume(current);
setDefinition(current.definition);
}
const presentation = discussionEnabled && (!action?.intent || action.intent === 'question' || action.intent === 'guided-help') ? 'discussion-v1' as const : undefined;
const discussion = presentation && current.discussion?.status === 'active'
? action?.discussion ?? { toolId: current.discussion.id, revision: current.discussion.revision,
...(activeFocus?.topicId === current.id ? { focusId: activeFocus.id } : {}) } : undefined;
const previous = pending.current && !current.requests.some((request) => request.id === pending.current?.requestId)
? pending.current
: null;
const input =
previous &&
previous.text === question &&
previous.presentation === presentation &&
JSON.stringify(previous.discussion) === JSON.stringify(discussion) &&
(previous.intent ?? 'question') === (action?.intent ?? 'question') &&
JSON.stringify(previous.references) === JSON.stringify(questionReferences)
? previous
: {
requestId: crypto.randomUUID(), text: question, references: questionReferences,
...(presentation ? { presentation } : {}), ...(discussion ? { discussion } : {}),
...(action?.intent ? { intent: action.intent } : {}),
...(sourceId ? { sourceConversationId: sourceId } : {}),
};
@@ -340,33 +330,6 @@ export function TeacherChatPanel({
(request) => request.status === 'preparing' || request.status === 'running'
);
const helpUnavailable = busy || !topicEnabled || Boolean(running);
const updateDiscussion = async (action: TeacherDiscussionAction['action'], itemId?: string) => {
const current = topicRef.current;
if (!current?.discussion || helpUnavailable) return;
const version = generation.current;
setBusy(true);
setError('');
try {
const next = await teacherApi.updateDiscussion(topicBase, current.id, {
toolId: current.discussion.id, revision: current.discussion.revision, action, ...(itemId ? { itemId } : {}),
});
if (version === generation.current) { consume(next); setFocus(null); }
} catch (e) {
if (version === generation.current) setError(e instanceof Error ? e.message : '内容还没更新,请再试一次。');
} finally { if (version === generation.current) setBusy(false); }
};
const focusItem = (id: string, label: string) => {
if (!topic) return;
setFocus({ topicId: topic.id, id, label });
inputRef.current?.focus();
};
const structureIdeas = () => {
if (!topic?.discussion) return;
setFocus(null);
void send({ text: '把我留下的想法理一理,看看它们怎么联系。', discussion: {
toolId: topic.discussion.id, revision: topic.discussion.revision, transition: 'structure',
} });
};
const askForSuggestions = () => void send({ text: '帮我看看', intent: 'suggestions' });
const askForGuidance = () => void send({ text: '我也说不清,你带我看看', intent: 'guided-help' });
const changeText = (next: string) => { setText(next); persistDraft(next, references, pending.current); };
@@ -386,13 +349,6 @@ export function TeacherChatPanel({
className="shrink-0 rounded-lg px-2 text-xs text-muted-foreground hover:bg-white hover:text-foreground disabled:opacity-40">新话题</button>
</div>}
</div>}
{discussionEnabled && topic?.discussion && <TeacherDiscussionPanel key={topic.id} discussion={topic.discussion}
disabled={helpUnavailable} focusId={activeFocus?.id}
onAction={(action, itemId) => void updateDiscussion(action, itemId)} onFocus={focusItem} onStructure={structureIdeas}
onDiscuss={(id, question) => {
focusItem(id, question);
void send({ text: question, discussion: { toolId: topic.discussion!.id, revision: topic.discussion!.revision, focusId: id } });
}} />}
<div ref={scrollRef} className="consultation-messages min-h-0 flex-1 overflow-y-auto px-5 py-6">
{!topic?.requests.length && <div className="flex min-h-full flex-col items-center justify-center pb-5 text-center">
<TeacherAvatar className="mb-6 h-[68px] w-[68px] rounded-3xl" definition={definition} />
@@ -421,16 +377,15 @@ export function TeacherChatPanel({
: request.status === 'completed' && <>
<TeacherReply text={request.response} />
<div className="consultation-follow-ups" aria-label="可以和智能体聊的问题">
{request.suggestedQuestions?.map((question) => <button key={question} type="button" disabled={helpUnavailable} onClick={() => void send({ text: question })} className="consultation-follow-up"><span className="min-w-0 flex-1">{question}</span><ChevronRight className="h-4 w-4 shrink-0 opacity-70" aria-hidden="true" /></button>)}
{request.suggestedQuestions?.map((question, index) => <button key={`${request.id}:${index}`} type="button" disabled={helpUnavailable} onClick={() => void send({ text: question })} className="consultation-follow-up"><span className="min-w-0 flex-1">{question}</span><ChevronRight className="h-4 w-4 shrink-0 opacity-70" aria-hidden="true" /></button>)}
</div>
<button type="button" disabled={helpUnavailable} onClick={askForGuidance} className="consultation-guided-help min-h-10 text-left text-xs leading-6 underline decoration-current/30 underline-offset-4 disabled:cursor-not-allowed disabled:opacity-50">我也说不清,你带我看看</button>
</>}
{['failed', 'cancelled', 'interrupted'].includes(request.status) && <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-guided-help min-h-10 text-xs underline underline-offset-4 disabled:opacity-50">再请智能体看看</button>}
</> : request.response ? <TeacherReply text={request.response} /> : <div className="text-[13px] leading-7">{['running', 'preparing'].includes(request.status) ? <span role="status" className="inline-flex items-center gap-2 text-muted-foreground"><Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />{request.discussionContext ? '正在梳理你的新想法…' : `${label}正在想…`}</span> : ['cancelled', 'interrupted'].includes(request.status) ? '这次先停在这里。想继续时可以再说说。' : ''}</div>}
{discussionEnabled && request.intent !== 'suggestions' && request.status === 'completed' && topic.discussion?.status !== 'active' && topic.discussion?.status !== 'offered' && Boolean(request.suggestedQuestions?.length) && <div className="consultation-follow-ups" aria-label="接着聊">
{request.suggestedQuestions?.map(question => <button type="button" key={question} disabled={helpUnavailable} onClick={() => void send({ text: question })} className="consultation-follow-up"><span className="min-w-0 flex-1">{question}</span><ChevronRight className="h-4 w-4 shrink-0 opacity-70" aria-hidden="true" /></button>)}
</> : request.response ? <TeacherReply text={request.response} /> : <div className="text-[13px] leading-7">{['running', 'preparing'].includes(request.status) ? <span role="status" className="inline-flex items-center gap-2 text-muted-foreground"><Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />{label}正在想…</span> : ['cancelled', 'interrupted'].includes(request.status) ? '这次先停在这里。想继续时可以再说说。' : ''}</div>}
{request.intent !== 'suggestions' && request.status === 'completed' && Boolean(request.suggestedQuestions?.length) && <div className="consultation-follow-ups" aria-label="接着聊">
{request.suggestedQuestions?.map((question, index) => <button type="button" key={`${request.id}:${index}`} disabled={helpUnavailable} onClick={() => void send({ text: question })} className="consultation-follow-up"><span className="min-w-0 flex-1">{question}</span><ChevronRight className="h-4 w-4 shrink-0 opacity-70" aria-hidden="true" /></button>)}
</div>}
{request.discussionError && <p className="text-xs leading-6 text-muted-foreground">{request.discussionError}</p>}
{request.unparsedResponse && <details className="min-w-0 text-xs text-muted-foreground">
<summary className="cursor-pointer">查看收到的原始内容</summary>
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-lg border p-3">{request.unparsedResponse}</pre>
@@ -463,12 +418,11 @@ export function TeacherChatPanel({
</details>}
{references.length > 0 && <div className="mb-2 rounded-lg bg-white p-3 text-xs"><p className="line-clamp-3 whitespace-pre-wrap">{references.map((ref) => ref.text).join('\n')}</p><button type="button" className="mt-1 underline" onClick={removeReferences}>移除引用</button></div>}
<div className="consultation-composer rounded-2xl border bg-white p-3 focus-within:ring-2 focus-within:ring-black/5">
{activeFocus && <DiscussionFocus label={activeFocus.label} onClear={() => setFocus(null)} />}
<textarea ref={inputRef} aria-label={`向${label}提问`} value={text} disabled={busy} maxLength={6000} onChange={(e) => changeText(e.target.value)} placeholder="和老师聊聊" rows={2}
onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); void send(); } }}
className="min-h-[60px] w-full resize-none border-0 bg-transparent text-[13px] leading-6 outline-none placeholder:text-muted-foreground/65" />
<div className="mt-2 flex items-center justify-between gap-2" data-testid="consultation-composer-actions">
{discussionEnabled ? <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-help-prompt flex min-h-9 cursor-pointer items-center gap-1.5 rounded-full px-3 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50">帮我看看<ChevronRight className="h-3 w-3" aria-hidden="true" /></button>
{!draftRevision ? <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-help-prompt flex min-h-9 cursor-pointer items-center gap-1.5 rounded-full px-3 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50">帮我看看<ChevronRight className="h-3 w-3" aria-hidden="true" /></button>
: <span />}
{running ? <button type="button" className="rounded-lg border px-3 py-2 text-xs" onClick={() => void teacherApi.cancel(topicBase, topic!.id, running.id).then(consume).catch(() => setError('暂时无法停止,请稍后重试。'))}>停止回复</button>
: <button type="submit" aria-label="提问" title={busy ? '正在发送…' : '发送'} disabled={busy || !topicEnabled || !text.trim()} className="consultation-send flex h-8 w-8 items-center justify-center rounded-full text-white disabled:opacity-30"><ArrowUp className="h-4 w-4" /></button>}