feat: integrate pixel teacher presence and resilient classroom preview

This commit is contained in:
鲨鱼辣椒 committed 2026-09-23 18:23:53 +08:00
1 parent 12d800ec51
commit 7951cca700
60 files changed
+3313 -180

No files matched your search

+43 -19
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowUp, ChevronDown, ChevronRight, Loader2, Maximize2, Plus, X } from 'lucide-react';
import { useAuthStore } from '@/stores/auth';
import teacherAvatar from '@/assets/consultations/teacher.png';
import teacherAvatar from '@/assets/consultations/teacher-pixel.png';
import friendAvatar from '@/assets/consultations/friend.png';
import { cn } from '@/lib/utils';
import { teacherApi, teacherTopicsPath } from '@/lib/coding-teacher';
@@ -26,7 +26,9 @@ export function TeacherChatPanel({
role,
expanded,
onExpand,
onReturnToWork,
externalTopic,
onTopicChange,
onComposingChange,
}: {
projectId: string;
sourceId: string;
@@ -39,7 +41,9 @@ export function TeacherChatPanel({
projectName?: string;
expanded?: boolean;
onExpand?(): void;
onReturnToWork?(): void;
externalTopic?: TeacherTopic | null;
onTopicChange?(topic: TeacherTopic): void;
onComposingChange?(composing: boolean): void;
}) {
const base = teacherTopicsPath(projectId, sourceId, role);
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
@@ -52,14 +56,20 @@ export function TeacherChatPanel({
try { localStorage.setItem(draftKey, JSON.stringify({ text, references, pending })); } catch { /* Draft remains in the open panel. */ }
}, [draftKey]);
const label = role === 'friend' ? '朋友' : '老师';
const avatar = role === 'friend' ? friendAvatar : teacherAvatar;
const studentTeacher = role === 'teacher' && !draftRevision;
const [historyOpen, setHistoryOpen] = useState(false);
const [definition, setDefinition] = useState<TeacherDefinition | null>(null);
const avatar = role === 'friend' ? friendAvatar : draftRevision && definition ? getAgentAvatarSrc(definition.avatar_id) : teacherAvatar;
const externalTopicRef = useRef(externalTopic);
externalTopicRef.current = externalTopic;
const inputRef = useRef<HTMLTextAreaElement>(null);
const focusedOnce = useRef(false);
const [topics, setTopics] = useState<TeacherTopicList>({ items: [], lastSelectedTopicId: null });
const [topic, setTopic] = useState<TeacherTopic | null>(null);
const [text, setText] = useState(saved.text ?? '');
const [references, setReferences] = useState<TeacherReference[]>(quote ? [quote] : saved.references ?? []);
useEffect(() => { onComposingChange?.(Boolean(text.trim() || references.length)); }, [text, references.length, onComposingChange]);
useEffect(() => () => onComposingChange?.(false), [onComposingChange]);
const draftRef = useRef({ text, references });
draftRef.current = { text, references };
const [error, setError] = useState('');
@@ -89,6 +99,19 @@ export function TeacherChatPanel({
},
[persistDraft]
);
useEffect(() => {
if (externalTopic && externalTopic.projectId === projectId) {
consume(externalTopic);
setDefinition(externalTopic.definition);
}
}, [externalTopic, projectId, consume]);
useEffect(() => { if (topic) onTopicChange?.(topic); }, [topic, onTopicChange]);
useEffect(() => {
if (role && !busy && !focusedOnce.current) {
focusedOnce.current = true;
inputRef.current?.focus();
}
}, [role, busy]);
useEffect(() => {
if (quote) setReferences([quote]);
}, [quote]);
@@ -111,7 +134,10 @@ export function TeacherChatPanel({
const listed = await teacherApi.list(base);
if (!alive) return;
setTopics(listed);
if (listed.lastSelectedTopicId) {
if (externalTopicRef.current) {
consume(externalTopicRef.current);
setDefinition(externalTopicRef.current.definition);
} else if (listed.lastSelectedTopicId) {
const current = await teacherApi.read(base, listed.lastSelectedTopicId);
if (alive && (!draftRevision || current.draftRevision === draftRevision)) {
consume(current);
@@ -259,7 +285,7 @@ export function TeacherChatPanel({
(request) => request.status === 'preparing' || request.status === 'running'
);
const helpUnavailable = busy || !enabled || Boolean(running);
const askForSuggestions = () => void send({ text: '老师,帮我看看', intent: 'suggestions' });
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); };
const removeReferences = () => { setReferences([]); persistDraft(text, [], pending.current); };
@@ -270,7 +296,7 @@ export function TeacherChatPanel({
<aside className={cn('consultation-pane flex h-full min-h-0 w-full flex-col', role === 'friend' && 'consultation-friend')}
data-testid="teacher-chat-panel" data-role={role ?? 'teacher'} aria-label={`${label}聊天`}>
<header className="flex h-[68px] shrink-0 items-center gap-3 px-5">
<img className="h-9 w-9 rounded-xl [image-rendering:pixelated]" src={role ? avatar : definition ? getAgentAvatarSrc(definition.avatar_id) : avatar} alt="" />
<img className="h-9 w-9 rounded-xl [image-rendering:pixelated]" src={avatar} alt="" />
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{definition?.name ?? (role === 'friend' ? '小麦' : '麦洛老师')}</h2>
<p className="mt-1 text-[11px] text-muted-foreground">{draftRevision ? '运营草稿试聊' : role === 'friend' ? '陪你体验,也听你说' : '一起想清楚,再动手'}</p></div>
{onExpand && <button className="consult-icon" aria-label={expanded ? '恢复咨询栏宽度' : '展开咨询栏'} onClick={onExpand}><Maximize2 className="h-4 w-4" /></button>}
@@ -291,13 +317,12 @@ export function TeacherChatPanel({
<p className="mb-6 mt-3 text-[13px] leading-6 text-muted-foreground">{studentTeacher
? <>有问题可以直接问我。<br />还没想好问什么,也没关系。</>
: role === 'friend' ? <>好玩的地方、困惑的瞬间,<br />我们一起发现。</> : <>想法、做法,或遇到的困难,<br />都可以慢慢聊。</>}</p>
{studentTeacher ? <div className="w-full max-w-64">
<button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-help-start flex min-h-11 w-full items-center justify-center gap-2 rounded-xl px-4 py-3 text-[13px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50">老师,帮我看看<ChevronRight className="h-3.5 w-3.5" /></button>
<p className="mt-3 text-xs leading-6 text-muted-foreground">我会结合你做到的地方,<br />找几个可以一起聊的问题。</p>
</div> : <div className="flex w-full max-w-64 flex-col gap-2">{questions.map((question) => <button key={question} onClick={() => changeText(question)} className="consultation-suggestion flex items-center justify-between gap-2 rounded-lg border bg-white px-3 py-3 text-left text-xs">{question}<ChevronRight className="h-3 w-3 shrink-0 opacity-50" /></button>)}</div>}
{!studentTeacher && <div className="flex w-full max-w-64 flex-col gap-2">{questions.map((question) => <button key={question} onClick={() => changeText(question)} className="consultation-suggestion flex items-center justify-between gap-2 rounded-lg border bg-white px-3 py-3 text-left text-xs">{question}<ChevronRight className="h-3 w-3 shrink-0 opacity-50" /></button>)}</div>}
</div>}
{topic?.requests.map((request) => <div key={request.id} className="mb-7 space-y-4">
<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>
{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>}
{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"><img src={avatar} alt="" className="h-6 w-6 rounded-lg [image-rendering:pixelated]" />{definition?.name ?? label}</div>
{request.intent === 'suggestions' ? <>
@@ -315,10 +340,8 @@ export function TeacherChatPanel({
</> : <div className="whitespace-pre-wrap break-words text-[13px] leading-7">{request.response || (['running', 'preparing'].includes(request.status) ? `${label}正在想…` : '')}</div>}
{request.omittedMessages > 0 && <p className="text-[10px] text-muted-foreground">本轮参考了较近的讨论,省略了 {request.omittedMessages} 条较早内容。</p>}
{request.error && <p className="text-xs text-destructive">{request.error}</p>}
{request.response && request.intent !== 'suggestions' && <div className="flex flex-wrap gap-4 text-[11px] text-muted-foreground">
{onReturnToWork && request.status === 'completed' && <button onClick={onReturnToWork} className="hover:text-foreground">我去试一试 <ChevronRight className="inline h-3 w-3" /></button>}
<button onClick={() => void navigator.clipboard.writeText(request.response).catch(() => setError('暂时无法复制,请选中文字复制。'))}>复制</button>
{!role && onBringBack && request.status === 'completed' && <button onClick={() => onBringBack(request.response)}>带回主会话草稿</button>}
{!role && onBringBack && request.response && request.intent !== 'suggestions' && request.status === 'completed' && <div className="text-[11px] text-muted-foreground">
<button onClick={() => onBringBack(request.response)}>带回主会话草稿</button>
</div>}
</div>)}
</div>
@@ -326,13 +349,14 @@ export function TeacherChatPanel({
{topic?.unsaved && <div className="px-5 py-2 text-xs text-destructive">回复尚未保存,请复制或重试保存。<button className="ml-2 underline" onClick={() => void teacherApi.save(base, topic.id).then(consume).catch(() => setError('保存失败,请先复制回复。'))}>重试保存</button></div>}
{!enabled && !error && !busy && <p className="px-5 pb-2 text-xs text-muted-foreground">{label}暂未开放,历史仍可查看。</p>}
<form className="px-4 pb-4 pt-2" onSubmit={(e) => { e.preventDefault(); void send(); }}>
{studentTeacher && Boolean(topic?.requests.length) && <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-help-again mb-2 flex min-h-9 items-center gap-1.5 rounded-lg px-2 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50">老师,帮我看看<ChevronRight className="h-3 w-3" /></button>}
{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">
<textarea aria-label={`向${label}提问`} value={text} disabled={busy} maxLength={6000} onChange={(e) => changeText(e.target.value)} placeholder={`想和${label}聊些什么?`} rows={2}
<textarea ref={inputRef} aria-label={`向${label}提问`} value={text} disabled={busy} maxLength={6000} onChange={(e) => changeText(e.target.value)} placeholder={`想和${label}聊些什么?`} 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"><span className="text-[10px] text-muted-foreground">{role === 'friend' ? '聊感受,也聊你的新发现' : '把你的困惑说出来就好'}</span>
<div className="mt-2 flex items-center justify-between gap-2" data-testid="consultation-composer-actions">
{studentTeacher ? <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 className="text-[10px] text-muted-foreground">{role === 'friend' ? '聊感受,也聊你的新发现' : ''}</span>}
{running ? <button type="button" className="rounded-lg border px-3 py-2 text-xs" onClick={() => void teacherApi.cancel(base, topic!.id, running.id).then(consume).catch(() => setError('暂时无法停止,请稍后重试。'))}>停止回复</button>
: <button type="submit" aria-label={role === 'friend' ? '发送给朋友' : '提问'} title={busy ? '正在发送…' : '发送'} disabled={busy || !enabled || !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>