Merge teacher reply cleanup with continuous conversations
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { ArrowUp, ChevronDown, ChevronRight, Loader2 } from 'lucide-react';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { teacherApi, teacherTopicsPath, legacyTopicBase, type TeacherCatalogState } from '@/lib/coding-teacher';
|
||||
@@ -10,8 +10,6 @@ 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';
|
||||
|
||||
@@ -21,6 +19,13 @@ const conversationViews = new Map<string, { topic: TeacherTopic | null; before:
|
||||
const messageOrderKey = (request: TeacherTopic['requests'][number]) => request.origin
|
||||
? [request.origin.projectId, request.origin.topicId, request.origin.requestId].join(':') : request.id;
|
||||
|
||||
function restorePendingSend(saved?: TeacherSend, legacyProjectId?: string): TeacherSend | null {
|
||||
if (!saved) return null;
|
||||
// Keep an interrupted send retryable without restoring retired UI protocol fields.
|
||||
const { requestId, text, references, intent, sourceConversationId, projectId } = saved;
|
||||
return { requestId, text, references, intent, sourceConversationId, ...(projectId || legacyProjectId ? { projectId: projectId ?? legacyProjectId } : {}) };
|
||||
}
|
||||
|
||||
export function TeacherChatPanel({
|
||||
projectId,
|
||||
projectName,
|
||||
@@ -76,7 +81,6 @@ export function TeacherChatPanel({
|
||||
try { localStorage.setItem(draftKey, JSON.stringify({ text, references, pending, ...referenceScopeRef.current })); } catch { /* Draft remains in the open panel. */ }
|
||||
}, [draftKey]);
|
||||
const label = '智能体';
|
||||
const discussionEnabled = !draftRevision;
|
||||
const [historyOpen, setHistoryOpen] = useState(false);
|
||||
const [before, setBefore] = useState<string | null>(cachedView?.before ?? null);
|
||||
const [loadingOlder, setLoadingOlder] = useState(false);
|
||||
@@ -84,7 +88,6 @@ export function TeacherChatPanel({
|
||||
const followBottom = useRef(cachedView?.follow ?? true);
|
||||
const restoreTop = useRef(cachedView?.top);
|
||||
const scrollPosition = useRef(cachedView?.top ?? 0);
|
||||
const [focus, setFocus] = useState<{ topicId: string; id: string; label: string } | null>(null);
|
||||
const [localDefinition, setDefinition] = useState<TeacherDefinition | null>(null);
|
||||
const catalogStateRef = useRef(catalogState);
|
||||
catalogStateRef.current = catalogState;
|
||||
@@ -96,10 +99,7 @@ export function TeacherChatPanel({
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const focusedOnce = useRef(false);
|
||||
const [topics, setTopics] = useState<TeacherTopicList>({ items: [], lastSelectedTopicId: null });
|
||||
const [storedTopic, setTopic] = useState<TeacherTopic | null>(cachedView?.topic ?? null);
|
||||
const topic = useMemo(() => storedTopic && continuous ? { ...storedTopic,
|
||||
discussion: storedTopic.projectId === projectId ? storedTopic.discussion : storedTopic.conversation?.discussions[projectId] }
|
||||
: storedTopic, [storedTopic, continuous, projectId]);
|
||||
const [topic, setTopic] = useState<TeacherTopic | null>(cachedView?.topic ?? null);
|
||||
const legacyFriend = topic?.role === 'friend';
|
||||
const legacyView = Boolean(continuous && topic && !topic.conversation);
|
||||
const viewingLegacy = useRef(false);
|
||||
@@ -133,7 +133,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, continuous ? saved.projectId ?? projectId : undefined));
|
||||
useEffect(() => {
|
||||
persistDraft(text, references, pending.current);
|
||||
}, [text, references, persistDraft]);
|
||||
@@ -147,12 +147,6 @@ export function TeacherChatPanel({
|
||||
if (continuous && draftKey && !viewingLegacy.current) conversationViews.set(draftKey, { topic: topicRef.current,
|
||||
before: beforeRef.current, top: scrollPosition.current, follow: followBottom.current });
|
||||
}, [continuous, draftKey]);
|
||||
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;
|
||||
useLayoutEffect(() => {
|
||||
const pane = scrollRef.current;
|
||||
if (!pane) return;
|
||||
@@ -384,14 +378,16 @@ 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;
|
||||
if (continuous && questionReferences.length && (referenceScope.projectId !== projectId || referenceScope.sourceId !== sourceId)) {
|
||||
setError('引用来自另一个项目或操作对话,请切回来源,或移除引用后再提问。'); return;
|
||||
}
|
||||
if (continuous && pending.current?.text === question && pending.current.projectId && pending.current.projectId !== projectId) {
|
||||
if (continuous && pending.current && !topicRef.current?.requests.some(request => request.id === pending.current?.requestId)
|
||||
&& (pending.current.text === question || (action?.intent === 'suggestions' && pending.current.intent === 'suggestions'))
|
||||
&& pending.current.projectId && pending.current.projectId !== projectId) {
|
||||
setError('上次提问仍绑定原项目,请切回原项目确认结果后重试。'); return;
|
||||
}
|
||||
const version = generation.current;
|
||||
@@ -410,27 +406,22 @@ 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;
|
||||
// Copy changes must not create another charge for an uncertain hint request.
|
||||
const retrySuggestions = action?.intent === 'suggestions' && previous?.intent === 'suggestions';
|
||||
const input =
|
||||
previous &&
|
||||
previous.text === question &&
|
||||
(!continuous || previous.projectId === projectId) &&
|
||||
previous.sourceConversationId === (sourceId || undefined) &&
|
||||
previous.presentation === presentation &&
|
||||
JSON.stringify(previous.discussion) === JSON.stringify(discussion) &&
|
||||
(previous.intent ?? 'question') === (action?.intent ?? 'question') &&
|
||||
JSON.stringify(previous.references) === JSON.stringify(questionReferences)
|
||||
previous && (!continuous || previous.projectId === projectId) && (retrySuggestions || (
|
||||
previous.text === question &&
|
||||
(!continuous || previous.sourceConversationId === (sourceId || undefined)) &&
|
||||
(previous.intent ?? 'question') === (action?.intent ?? 'question') &&
|
||||
JSON.stringify(previous.references) === JSON.stringify(questionReferences)
|
||||
))
|
||||
? previous
|
||||
: {
|
||||
requestId: crypto.randomUUID(), text: question, references: questionReferences,
|
||||
...(continuous ? { projectId } : {}),
|
||||
...(presentation ? { presentation } : {}), ...(discussion ? { discussion } : {}),
|
||||
...(action?.intent ? { intent: action.intent } : {}),
|
||||
...(sourceId ? { sourceConversationId: sourceId } : {}),
|
||||
};
|
||||
@@ -460,36 +451,7 @@ 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, endpointId, {
|
||||
...(continuous ? { projectId } : {}),
|
||||
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 askForSuggestions = () => void send({ text: '继续看看👀', intent: 'suggestions' });
|
||||
const changeText = (next: string) => { setText(next); persistDraft(next, references, pending.current); };
|
||||
const removeReferences = () => { setReferences([]); persistDraft(text, [], pending.current); };
|
||||
const questions = definition?.suggested_questions ?? [];
|
||||
@@ -517,13 +479,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"
|
||||
onScroll={() => { const pane = scrollRef.current; if (!pane) return;
|
||||
scrollPosition.current = pane.scrollTop;
|
||||
@@ -559,16 +514,14 @@ 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>)}
|
||||
{['failed', 'cancelled', 'interrupted'].includes(request.status) && <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-retry">继续看看👀</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>
|
||||
@@ -602,13 +555,13 @@ 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>
|
||||
: <span />}
|
||||
<div className="mt-2 flex min-h-11 items-center justify-between gap-2" data-testid="consultation-composer-actions">
|
||||
<div className="min-w-0 flex-1">
|
||||
{!draftRevision && !text.trim() && <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-hint">继续看看👀</button>}
|
||||
</div>
|
||||
{running ? <button type="button" className="rounded-lg border px-3 py-2 text-xs" onClick={() => void teacherApi.cancel(topicBase, endpointId, 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>}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user