Merge teacher composer and compact prompt UI into main

This commit is contained in:
鲨鱼辣椒
2026-09-29 20:40:09 +08:00
62 changed files with 2327 additions and 158 deletions

View File

@@ -13,6 +13,11 @@ import type {
} from '../../../shared/coding-teacher';
import { TeacherAvatar } from './TeacherAvatar';
import { TeacherReply } from './TeacherReply';
import { MessageTimestamp } from './MessageTimestamp';
import { ComposerVoiceButton } from './ComposerVoiceButton';
import { useWorksVoiceInput } from '@/hooks/use-works-voice-input';
import { TeacherModelSelect } from './TeacherModelSelect';
import { useTeacherModelChoice } from '@/hooks/use-teacher-model-choice';
// Preserve loaded pages and the reading anchor while moving between contacts.
// Durable messages remain Main-owned; this is only the current window's view.
@@ -23,8 +28,8 @@ const messageOrderKey = (request: TeacherTopic['requests'][number]) => request.o
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 } : {}) };
const { requestId, text, references, intent, sourceConversationId, projectId, modelId } = saved;
return { requestId, text, references, intent, sourceConversationId, ...(modelId ? { modelId } : {}), ...(projectId || legacyProjectId ? { projectId: projectId ?? legacyProjectId } : {}) };
}
export function TeacherChatPanel(props: Parameters<typeof ProjectTeacherChatPanel>[0]) {
@@ -141,6 +146,8 @@ function ProjectTeacherChatPanel({
? selectedTeacher?.definition ?? selectedAgent?.definition ?? localDefinition
: topic?.definition ?? (catalogState
? selectedTeacher?.definition ?? selectedAgent?.definition ?? catalogState.config.definition : localDefinition);
const modelScope = `${account}:${selectedAgentId ?? definition?.config_id ?? definition?.teacher_id ?? 'teacher'}:${draftRevision ?? 'published'}`;
const modelChoice = useTeacherModelChoice(modelScope);
const topicEnabled = legacyFriend || legacyView ? false : !topic ? enabled
: topic.definition.config_id
? teachers.some((item) => item.teacher_id === topic.definition.config_id)
@@ -405,7 +412,7 @@ function ProjectTeacherChatPanel({
const questionSourceId = retry
? retry.sourceConversationId ?? (continuous || topic?.sourceConversationId === 'project' ? undefined : topic?.sourceConversationId)
: sourceId;
if (!question.trim() || busy || sendInFlight.current || !topicEnabled || topicRef.current?.requests.some((request) => ['preparing', 'running'].includes(request.status))) return;
if (voiceInput.state !== 'idle' || !question.trim() || busy || sendInFlight.current || !topicEnabled || topicRef.current?.requests.some((request) => ['preparing', 'running'].includes(request.status))) return;
if (continuous && !retry && questionReferences.length && (referenceScope.projectId !== projectId || referenceScope.sourceId !== sourceId)) {
setError('引用来自另一个项目或操作对话,请切回来源,或移除引用后再提问。'); return;
}
@@ -452,6 +459,7 @@ function ProjectTeacherChatPanel({
? previous
: {
requestId: crypto.randomUUID(), text: question, references: questionReferences,
...((retry ? retry.modelId : modelChoice.modelId) ? { modelId: retry ? retry.modelId : modelChoice.modelId } : {}),
...(continuous ? { projectId } : {}),
...(action?.intent ? { intent: action.intent } : {}),
...(questionSourceId ? { sourceConversationId: questionSourceId } : {}),
@@ -472,8 +480,16 @@ function ProjectTeacherChatPanel({
}
if (!continuous) setTopics(await teacherApi.list(base));
} catch (e) {
if (version === generation.current)
if (version === generation.current) {
const code = (e as { details?: { backendCode?: string } } | null)?.details?.backendCode;
// These Main validation failures precede acceptance; allow correcting the selection.
// Uncertain transport failures retain the original request and model to avoid double charging.
if (code === 'teacher_model_unavailable' || code === 'teacher_model_invalid') {
pending.current = null;
persistDraft(draftRef.current.text, draftRef.current.references);
}
setError(e instanceof Error ? e.message : '提问失败,请保留问题后重试');
}
} finally {
sendInFlight.current = false;
if (version === generation.current) setBusy(false);
@@ -483,8 +499,19 @@ function ProjectTeacherChatPanel({
(request) => request.status === 'preparing' || request.status === 'running'
);
const helpUnavailable = busy || !topicEnabled || Boolean(running);
const askForSuggestions = () => void send({ text: '继续看看👀', intent: 'suggestions' });
const changeText = (next: string) => { setText(next); persistDraft(next, references, pending.current); };
const askForSuggestions = () => void send({ text: '帮我整体看🧠', intent: 'suggestions' });
const changeText = (next: string) => { draftRef.current.text = next; setText(next); persistDraft(next, references, pending.current); };
const voiceInput = useWorksVoiceInput({
enabled: !busy && topicEnabled && !running,
scopeKey: `${modelScope}:${projectId}:${sourceId}:${topic?.id ?? 'new'}:${modelChoice.modelId ?? 'default'}`,
onTranscript: transcript => {
const current = draftRef.current.text;
const next = current.trim() ? `${current.trimEnd()}\n${transcript}` : transcript;
if (next.length > 6000) { setError('文字超过 6000 字,请缩短输入后重新录音。'); return; }
changeText(next);
},
});
const removeReferences = () => { setReferences([]); persistDraft(text, [], pending.current); };
const questions = definition?.suggested_questions ?? [];
return (
@@ -526,8 +553,8 @@ function ProjectTeacherChatPanel({
{topic?.requests.map((request, index) => <div key={request.id} className="mb-7 space-y-4">
{continuous && request.projectId && (index === 0 || request.projectId !== topic.requests[index - 1].projectId) && <p className="text-center text-[10px] text-muted-foreground">{request.projectName || '之前的项目'}</p>}
{request.intent === 'check-in'
? <p className="text-[11px] text-muted-foreground">智能体来看看你的进展</p>
: <div className="flex justify-end"><p className="consultation-user max-w-[92%] whitespace-pre-wrap break-words rounded-2xl rounded-br-sm px-4 py-3 text-[13px] leading-7">{request.text}</p></div>}
? <div className="space-y-1"><p className="text-[11px] text-muted-foreground">智能体来看看你的进展</p><MessageTimestamp value={request.createdAt} label="主动检查时间" /></div>
: <div className="flex flex-col items-end gap-1"><p className="consultation-user max-w-[92%] whitespace-pre-wrap break-words rounded-2xl rounded-br-sm px-4 py-3 text-[13px] leading-7">{request.text}</p><MessageTimestamp value={request.createdAt} label="发送时间" className="text-right" /></div>}
{request.references.length > 0 && <details className="text-xs text-muted-foreground"><summary>本轮引用 {request.references.length} 项</summary>{request.references.map((ref, index) => <pre className="whitespace-pre-wrap" key={index}>{ref.text}</pre>)}</details>}
<div className="flex items-center gap-2 text-[11px] text-muted-foreground"><TeacherAvatar definition={definition} className="h-6 w-6 rounded-lg" />{definition?.name ?? label}</div>
{!!request.toolActivity?.length && <details className="text-xs text-muted-foreground">
@@ -540,6 +567,7 @@ function ProjectTeacherChatPanel({
</li>)}
</ul>
</details>}
<div className="space-y-1.5">
{request.status === 'completed' && request.replyIncomplete ? <div className="space-y-3">
<p role="status" className="text-[13px] leading-7 text-muted-foreground">这次回复未能完整显示</p>
{request.intent !== 'check-in' && request.text.trim() && <button type="button" disabled={helpUnavailable || !retryScopeMatches(request)} onClick={() => void send({ text: request.text, intent: request.intent }, request)} className="consultation-retry">重新回答</button>}
@@ -549,13 +577,12 @@ function ProjectTeacherChatPanel({
? <p role="status" className="flex items-center gap-2 text-[13px] leading-7 text-muted-foreground"><Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />我看看你最近做到了哪里…</p>
: request.status === 'completed' && <>
<TeacherReply text={request.response} />
<div className="consultation-follow-ups" aria-label="可以和智能体聊的问题">
{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>
</>}
{['failed', 'cancelled', 'interrupted'].includes(request.status) && <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-retry">继续看看👀</button>}
{['failed', 'cancelled', 'interrupted'].includes(request.status) && <button type="button" disabled={helpUnavailable || voiceInput.state !== 'idle'} 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' && !request.replyIncomplete && Boolean(request.suggestedQuestions?.length) && <div className="consultation-follow-ups" aria-label="接着聊">
<MessageTimestamp value={request.finishedAt} pending={['running', 'preparing'].includes(request.status)} />
</div>
{request.status === 'completed' && !request.replyIncomplete && Boolean(request.suggestedQuestions?.length) && <div className="consultation-follow-ups" aria-label={request.intent === 'suggestions' ? '可以和智能体聊的问题' : '接着聊'}>
{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.status === 'completed' && !request.replyIncomplete && request.replyParseError && <p role="status" className="text-xs text-muted-foreground">回答正文已保留,部分附加内容未能显示。</p>}
@@ -591,22 +618,28 @@ function ProjectTeacherChatPanel({
</div>
</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>}
{!draftRevision && !text.trim() && (definition?.shortcuts == null || definition.shortcuts.length > 0) &&
<div className="consultation-shortcuts" role="group" aria-label="快捷提问" data-testid="consultation-shortcuts">
{definition?.shortcuts == null
? <button type="button" disabled={helpUnavailable || voiceInput.state !== 'idle'} onClick={askForSuggestions} className="consultation-hint">帮我整体看🧠</button>
: definition.shortcuts.map((shortcut, index) => <button
key={index} type="button" disabled={helpUnavailable || voiceInput.state !== 'idle'}
onClick={() => void send({ text: shortcut.prompt })}
className="consultation-hint"
>{shortcut.label}</button>)}
</div>}
<div className="consultation-composer rounded-2xl border bg-white p-3 focus-within:ring-2 focus-within:ring-black/5">
<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 min-h-12 items-center justify-between gap-2" data-testid="consultation-composer-actions">
<div className="flex max-h-48 min-w-0 flex-1 flex-wrap gap-2 overflow-y-auto pb-1">
{!draftRevision && !text.trim() && (definition?.shortcuts == null
? <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-hint">继续看看👀</button>
: definition.shortcuts.map((shortcut, index) => <button
key={index} type="button" disabled={helpUnavailable}
onClick={() => void send({ text: shortcut.prompt })}
className="consultation-hint max-w-full whitespace-normal break-words text-left"
>{shortcut.label}</button>))}
</div>
<div className="mt-2 flex min-h-[68px] flex-wrap items-center justify-between gap-x-2 gap-y-2" data-testid="consultation-composer-actions">
<div className="ml-auto flex min-w-0 max-w-full items-center gap-1" data-testid="teacher-composer-runtime-controls">
<TeacherModelSelect key={modelScope + (definition?.runtime ?? 'local')} runtime={definition?.runtime ?? 'local'} scope={modelScope} defaultModel={definition?.model.model_id}
modelId={modelChoice.modelId} onChange={modelChoice.select} disabled={busy || !topicEnabled || Boolean(running)} />
<ComposerVoiceButton voiceInput={voiceInput} />
{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>}
: <button type="submit" aria-label="提问" title={busy ? '正在发送…' : '发送'} disabled={busy || !topicEnabled || !text.trim() || voiceInput.state !== 'idle'} className="consultation-send flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-white disabled:opacity-30"><ArrowUp className="h-4 w-4" /></button>}
</div>
</div>
</div>
</form>