Add teacher microphone and per-question model selection

This commit is contained in:
鲨鱼辣椒 committed 2026-09-29 19:43:45 +08:00
1 parent cd1ba41e21
commit 78cfde6734
20 files changed
+517 -37

No files matched your search

+41 -10
View File
@@ -14,6 +14,10 @@ import type {
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.
@@ -24,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({
@@ -131,6 +135,8 @@ export function TeacherChatPanel({
? 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)
@@ -394,7 +400,7 @@ export function TeacherChatPanel({
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;
}
@@ -441,6 +447,7 @@ export function TeacherChatPanel({
? 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 } : {}),
@@ -461,8 +468,16 @@ export function TeacherChatPanel({
}
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);
@@ -473,7 +488,18 @@ export function TeacherChatPanel({
);
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 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 (
@@ -540,7 +566,7 @@ export function TeacherChatPanel({
: request.status === 'completed' && <>
<TeacherReply text={request.response} />
</>}
{['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>}
<MessageTimestamp value={request.finishedAt} pending={['running', 'preparing'].includes(request.status)} />
</div>
@@ -584,12 +610,17 @@ export function TeacherChatPanel({
<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-[68px] 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 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="min-w-0 grow">
{!draftRevision && !text.trim() && <button type="button" disabled={helpUnavailable || voiceInput.state !== 'idle'} onClick={askForSuggestions} className="consultation-hint">帮我整体看🧠</button>}
</div>
<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>