Add teacher microphone and per-question model selection
This commit is contained in:
20
src/hooks/use-teacher-model-choice.ts
Normal file
20
src/hooks/use-teacher-model-choice.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
function readModel(key: string): string | undefined {
|
||||
try {
|
||||
const value = localStorage.getItem(key);
|
||||
return value && value.length <= 200 ? value : undefined;
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
export function useTeacherModelChoice(scope: string) {
|
||||
const key = 'makelore-teacher-model:' + scope;
|
||||
const [choice, setChoice] = useState(() => ({ key, modelId: readModel(key) }));
|
||||
const modelId = choice.key === key ? choice.modelId : readModel(key);
|
||||
const select = (id: string | undefined) => {
|
||||
setChoice({ key, modelId: id });
|
||||
try { if (id) localStorage.setItem(key, id); else localStorage.removeItem(key); } catch { /* Current window retains the choice. */ }
|
||||
};
|
||||
return { modelId, select };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { hostApiFetch, createHostEventSource, ensureHostApiToken } from './host-api';
|
||||
import type {
|
||||
TeacherModelCatalog,
|
||||
TeacherAvailability,
|
||||
TeacherCheckInInput,
|
||||
TeacherCheckInResult,
|
||||
@@ -24,6 +25,7 @@ export function legacyTopicBase(base: string, legacyFriend: boolean) {
|
||||
return legacyFriend ? base.replace(/agent-topics$/, 'friend-topics') : base;
|
||||
}
|
||||
export const teacherApi = {
|
||||
models: (runtime: 'local' | 'yuxi') => hostApiFetch<TeacherModelCatalog>('/api/coding/teacher/models?runtime=' + runtime),
|
||||
legacyHistory: (projectId: string) => hostApiFetch<TeacherTopicList>(`/api/coding/projects/${encodeURIComponent(projectId)}/agent-history`),
|
||||
legacyRead: (projectId: string, item: TeacherTopicList['items'][number]) => hostApiFetch<TeacherTopic>(
|
||||
`/api/coding/projects/${encodeURIComponent(projectId)}/agent-history/${encodeURIComponent(item.id)}?source=${encodeURIComponent(item.legacySourceId ?? 'project')}&friend=${item.legacyRole === 'friend'}`),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LoaderCircle, Mic, Plus, RotateCcw, Send, Square, X } from 'lucide-react';
|
||||
import { LoaderCircle, Plus, RotateCcw, Send, Square, X } from 'lucide-react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useProviderStore } from '@/stores/providers';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
} from '@/types/coding-conversation';
|
||||
import type { CodingConversationMetadata } from '@/types/coding-project';
|
||||
import { CodingComposerRuntimeControls } from './CodingComposerRuntimeControls';
|
||||
import { ComposerVoiceButton } from './ComposerVoiceButton';
|
||||
|
||||
export interface CodingComposerProps {
|
||||
value: string;
|
||||
@@ -236,29 +237,7 @@ export function CodingComposer({
|
||||
onRefresh={onRefreshRuntime}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'h-8 w-8 shrink-0 rounded-full bg-transparent p-0 text-muted-foreground shadow-none hover:bg-surface-subtle hover:text-foreground',
|
||||
voiceInput.state !== 'idle' && 'bg-surface-subtle text-foreground',
|
||||
)}
|
||||
disabled={!voiceInput.canToggle}
|
||||
aria-busy={voiceInput.state === 'transcribing'}
|
||||
aria-label={voiceInput.state === 'recording'
|
||||
? '停止语音输入'
|
||||
: voiceInput.state === 'transcribing'
|
||||
? '正在识别语音'
|
||||
: '语音输入'}
|
||||
title={voiceInput.supported ? '语音输入' : '当前环境不支持语音输入'}
|
||||
onClick={() => void voiceInput.toggle()}
|
||||
>
|
||||
{voiceInput.state === 'transcribing'
|
||||
? <LoaderCircle className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
: voiceInput.state === 'recording'
|
||||
? <Square className="h-3.5 w-3.5 fill-current" aria-hidden="true" />
|
||||
: <Mic className="h-4 w-4" aria-hidden="true" />}
|
||||
</Button>
|
||||
<ComposerVoiceButton voiceInput={voiceInput} />
|
||||
<Button
|
||||
type={showAbort ? 'button' : 'submit'}
|
||||
className={cn(
|
||||
|
||||
17
src/pages/Chat/ComposerVoiceButton.tsx
Normal file
17
src/pages/Chat/ComposerVoiceButton.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { LoaderCircle, Mic, Square } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { useWorksVoiceInput } from '@/hooks/use-works-voice-input';
|
||||
|
||||
export function ComposerVoiceButton({ voiceInput }: { voiceInput: ReturnType<typeof useWorksVoiceInput> }) {
|
||||
return <Button type="button" variant="ghost"
|
||||
className={cn('h-8 w-8 shrink-0 rounded-full bg-transparent p-0 text-muted-foreground shadow-none hover:bg-surface-subtle hover:text-foreground',
|
||||
voiceInput.state !== 'idle' && 'bg-surface-subtle text-foreground')}
|
||||
disabled={!voiceInput.canToggle} aria-busy={voiceInput.state === 'transcribing'}
|
||||
aria-label={voiceInput.state === 'recording' ? '停止语音输入' : voiceInput.state === 'transcribing' ? '正在识别语音' : '语音输入'}
|
||||
title={voiceInput.supported ? '语音输入' : '当前环境不支持语音输入'} onClick={() => void voiceInput.toggle()}>
|
||||
{voiceInput.state === 'transcribing' ? <LoaderCircle className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
: voiceInput.state === 'recording' ? <Square className="h-3.5 w-3.5 fill-current" aria-hidden="true" />
|
||||
: <Mic className="h-4 w-4" aria-hidden="true" />}
|
||||
</Button>;
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
60
src/pages/Chat/TeacherModelSelect.tsx
Normal file
60
src/pages/Chat/TeacherModelSelect.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
|
||||
import { Check, ChevronDown, LoaderCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { teacherApi } from '@/lib/coding-teacher';
|
||||
import type { TeacherModelCatalog } from '../../../shared/coding-teacher';
|
||||
|
||||
export function TeacherModelSelect({ runtime, scope, defaultModel, modelId, disabled, onChange }: {
|
||||
runtime: 'local' | 'yuxi'; scope: string; defaultModel?: string | null;
|
||||
modelId?: string; disabled: boolean; onChange(id: string | undefined): void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [result, setResult] = useState<TeacherModelCatalog | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
// Fetch on opening so account changes, availability and a newly deployed service are respected.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let alive = true;
|
||||
void teacherApi.models(runtime).then(value => { if (alive) setResult(value); })
|
||||
.catch(() => { if (alive) setError('模型列表暂不可用,请关闭后重试。'); })
|
||||
.finally(() => { if (alive) setLoading(false); });
|
||||
return () => { alive = false; };
|
||||
}, [open, runtime, scope]);
|
||||
const label = modelId ?? defaultModel ?? '老师配置';
|
||||
const itemClass = 'relative flex min-h-8 cursor-default select-none items-center rounded-xl px-2.5 pr-9 outline-none data-[highlighted]:bg-surface-subtle';
|
||||
return <DropdownMenu.Root open={open} onOpenChange={value => {
|
||||
if (value) { setLoading(true); setResult(null); setError(''); }
|
||||
setOpen(value);
|
||||
}}>
|
||||
<DropdownMenu.Trigger asChild>
|
||||
<Button type="button" variant="ghost" disabled={disabled}
|
||||
className="h-8 min-w-0 max-w-48 gap-1 rounded-full bg-transparent px-2 text-xs font-normal shadow-none hover:bg-surface-subtle"
|
||||
aria-label={`老师模型:${label}${modelId ? '' : ',跟随老师配置'}`} title={label}>
|
||||
<span className="min-w-0 truncate text-foreground/85">{label}</span>
|
||||
<span className="shrink-0 text-brand">{modelId ? '模型默认' : '老师配置'}</span>
|
||||
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
</Button>
|
||||
</DropdownMenu.Trigger>
|
||||
<DropdownMenu.Portal>
|
||||
<DropdownMenu.Content side="top" align="end" sideOffset={8} collisionPadding={12} aria-label="选择老师模型"
|
||||
className="z-[101] max-h-[min(24rem,var(--radix-dropdown-menu-content-available-height))] w-64 max-w-[calc(100vw-24px)] overflow-y-auto rounded-[18px] border border-border/80 bg-background p-1.5 text-sm shadow-[0_18px_50px_rgba(26,31,42,0.16)] outline-none">
|
||||
<DropdownMenu.Label className="px-2.5 py-2 text-xs text-muted-foreground">用于接下来的老师提问</DropdownMenu.Label>
|
||||
<DropdownMenu.RadioGroup value={modelId ?? ''} onValueChange={value => onChange(value || undefined)}>
|
||||
<DropdownMenu.RadioItem value="" className={itemClass}>跟随老师配置
|
||||
<DropdownMenu.ItemIndicator className="absolute right-2.5"><Check className="h-4 w-4" /></DropdownMenu.ItemIndicator>
|
||||
</DropdownMenu.RadioItem>
|
||||
{result?.supported && result.models.map(model => <DropdownMenu.RadioItem key={model.id} value={model.id} className={itemClass} title={model.id}>
|
||||
<span className="min-w-0 truncate">{model.id}</span>
|
||||
<DropdownMenu.ItemIndicator className="absolute right-2.5"><Check className="h-4 w-4" /></DropdownMenu.ItemIndicator>
|
||||
</DropdownMenu.RadioItem>)}
|
||||
</DropdownMenu.RadioGroup>
|
||||
{loading && <div role="status" className="flex items-center gap-2 px-2.5 py-2 text-xs text-muted-foreground"><LoaderCircle className="h-3.5 w-3.5 animate-spin" />正在读取模型…</div>}
|
||||
{result?.supported && !result.models.length && <p role="status" className="px-2.5 py-2 text-xs text-muted-foreground">暂无可切换的模型,可以继续使用老师配置。</p>}
|
||||
{(error || result?.message || (result?.supported && modelId && !result.models.some(model => model.id === modelId))) &&
|
||||
<p role="status" className="px-2.5 py-2 text-xs leading-5 text-muted-foreground">{error || result?.message || '已选模型暂不可用,请重新选择后再提问。'}</p>}
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
</DropdownMenu.Root>;
|
||||
}
|
||||
Reference in New Issue
Block a user