Integrate project classroom with teacher and friend consultations

This commit is contained in:
鲨鱼辣椒
2026-09-22 15:50:18 +08:00
parent e5d271bc45
commit 68e676cb62
28 changed files with 957 additions and 314 deletions

View File

@@ -1,7 +1,12 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { MessageCircle, Plus, X } from 'lucide-react';
import { ArrowUp, ChevronDown, ChevronRight, FolderOpen, Maximize2, Plus, X } from 'lucide-react';
import { useAuthStore } from '@/stores/auth';
import teacherAvatar from '@/assets/consultations/teacher.png';
import friendAvatar from '@/assets/consultations/friend.png';
import { cn } from '@/lib/utils';
import { teacherApi, teacherTopicsPath } from '@/lib/coding-teacher';
import type {
ConsultationRole,
TeacherDefinition,
TeacherReference,
TeacherSend,
@@ -18,6 +23,11 @@ export function TeacherChatPanel({
quote,
draftRevision,
sampleContext,
role,
projectName,
expanded,
onExpand,
onReturnToWork,
}: {
projectId: string;
sourceId: string;
@@ -26,17 +36,38 @@ export function TeacherChatPanel({
quote?: TeacherReference;
draftRevision?: number;
sampleContext?: string;
role?: ConsultationRole;
projectName?: string;
expanded?: boolean;
onExpand?(): void;
onReturnToWork?(): void;
}) {
const base = teacherTopicsPath(projectId, sourceId);
const base = teacherTopicsPath(projectId, sourceId, role);
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
const draftKey = role ? `makelore-consultation-draft:${account}:${projectId}:${role}` : null;
const [saved] = useState<{ text?: string; references?: TeacherReference[]; pending?: TeacherSend }>(() => {
try { return draftKey ? JSON.parse(localStorage.getItem(draftKey) ?? '{}') : {}; } catch { return {}; }
});
const persistDraft = useCallback((text: string, references: TeacherReference[], pending?: TeacherSend | null) => {
if (!draftKey) return;
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 [contextOpen, setContextOpen] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
const [definition, setDefinition] = useState<TeacherDefinition | null>(null);
const [topics, setTopics] = useState<TeacherTopicList>({ items: [], lastSelectedTopicId: null });
const [topic, setTopic] = useState<TeacherTopic | null>(null);
const [text, setText] = useState('');
const [references, setReferences] = useState<TeacherReference[]>(quote ? [quote] : []);
const [text, setText] = useState(saved.text ?? '');
const [references, setReferences] = useState<TeacherReference[]>(quote ? [quote] : saved.references ?? []);
const [error, setError] = useState('');
const [busy, setBusy] = useState(true);
const [enabled, setEnabled] = useState(true);
const pending = useRef<TeacherSend | null>(null);
const [enabled, setEnabled] = useState(false);
const pending = useRef<TeacherSend | null>(saved.pending ?? null);
useEffect(() => {
persistDraft(text, references, pending.current);
}, [text, references, persistDraft]);
const generation = useRef(0);
const topicRef = useRef(topic);
topicRef.current = topic;
@@ -62,13 +93,13 @@ export function TeacherChatPanel({
try {
const config = draftRevision
? { definition: (await teacherApi.preview(draftRevision)).payload, enabled: true }
: await teacherApi.config();
: await teacherApi.config(role);
if (alive) {
setDefinition(config.definition);
setEnabled(config.enabled);
}
} catch (e) {
if (alive) setError(e instanceof Error ? e.message : '老师配置暂不可用');
if (alive) setError(e instanceof Error ? e.message : `${label}配置暂不可用`);
}
try {
const listed = await teacherApi.list(base);
@@ -82,7 +113,7 @@ export function TeacherChatPanel({
}
}
} catch (e) {
if (alive) setError(e instanceof Error ? e.message : '老师历史暂不可用');
if (alive) setError(e instanceof Error ? e.message : `${label}历史暂不可用`);
} finally {
if (alive) setBusy(false);
}
@@ -93,7 +124,7 @@ export function TeacherChatPanel({
// eslint-disable-next-line react-hooks/exhaustive-deps
generation.current++;
};
}, [base, draftRevision]);
}, [base, draftRevision, role, label]);
useEffect(() => {
if (!topic?.id) return;
const streamTopicId = topic.id;
@@ -119,20 +150,20 @@ export function TeacherChatPanel({
);
});
source.onerror = () => {
if (!closed) setError('连接暂时中断,正在恢复老师回复。');
if (!closed) setError(`连接暂时中断,正在恢复${label}回复。`);
};
source.onopen = () => {
if (!closed) setError('');
};
})
.catch((e) => {
if (!closed) setError(e instanceof Error ? e.message : '连接老师失败');
if (!closed) setError(e instanceof Error ? e.message : `连接${label}失败`);
});
return () => {
closed = true;
stream?.close();
};
}, [base, topic?.id, consume]);
}, [base, topic?.id, consume, label]);
const choose = async (id: string) => {
const version = ++generation.current;
setBusy(true);
@@ -164,13 +195,13 @@ export function TeacherChatPanel({
}
} catch (e) {
if (version === generation.current)
setError(e instanceof Error ? e.message : '无法新建老师话题');
setError(e instanceof Error ? e.message : `无法新建${label}话题`);
} finally {
if (version === generation.current) setBusy(false);
}
};
const send = async () => {
if (!text.trim() || busy) return;
if (!text.trim() || busy || !enabled || topicRef.current?.requests.some((request) => ['preparing', 'running'].includes(request.status))) return;
const version = generation.current;
setBusy(true);
setError('');
@@ -187,13 +218,15 @@ export function TeacherChatPanel({
previous.text === text &&
JSON.stringify(previous.references) === JSON.stringify(references)
? previous
: { requestId: crypto.randomUUID(), text, references };
: { requestId: crypto.randomUUID(), text, references, ...(role && sourceId ? { sourceConversationId: sourceId } : {}) };
pending.current = input;
persistDraft(text, references, input);
const next = await teacherApi.send(base, current.id, input);
if (version !== generation.current) return;
consume(next);
setText('');
setReferences([]);
persistDraft('', []);
pending.current = null;
setTopics(await teacherApi.list(base));
} catch (e) {
@@ -206,186 +239,68 @@ export function TeacherChatPanel({
const running = topic?.requests.find(
(request) => request.status === 'preparing' || request.status === 'running'
);
const changeText = (next: string) => { setText(next); persistDraft(next, references, pending.current); };
const removeReferences = () => { setReferences([]); persistDraft(text, [], pending.current); };
const questions = definition?.suggested_questions.length ? definition.suggested_questions : role === 'friend'
? ['想听听你对作品的第一印象', '我想和你聊聊刚才的体验']
: ['我还没想好下一步做什么', '帮我理一理现在的思路'];
return (
<aside
className="flex h-full min-h-0 w-full flex-col border-l border-border bg-background"
data-testid="teacher-chat-panel"
aria-label="老师聊天"
>
<header className="flex items-center gap-2 border-b p-3">
{definition ? (
<img
className="h-8 w-8 rounded-lg"
src={getAgentAvatarSrc(definition.avatar_id)}
alt=""
/>
) : (
<MessageCircle className="h-5 w-5" />
)}
<div className="min-w-0 flex-1">
<h2 className="truncate text-sm font-semibold">{definition?.name ?? '编程老师'}</h2>
<p className="text-xs text-muted-foreground">
{draftRevision ? '运营草稿试聊' : '结合当前编程会话答疑'}
</p>
</div>
<button
aria-label="老师新话题"
title="新话题"
disabled={busy || !enabled}
onClick={() => void newTopic()}
className="rounded p-2 hover:bg-muted"
>
<Plus className="h-4 w-4" />
</button>
{onClose && (
<button aria-label="关闭老师" onClick={onClose} className="rounded p-2 hover:bg-muted">
<X className="h-4 w-4" />
</button>
)}
<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="" />
<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>}
{onClose && <button className="consult-icon" aria-label={`关闭${label}`} onClick={onClose}><X className="h-4 w-4" /></button>}
</header>
{topics.items.length > 0 && (
<select
aria-label="老师话题"
value={topic?.id ?? ''}
disabled={busy}
onChange={(e) => void choose(e.target.value)}
className="mx-3 mt-2 rounded border bg-background p-2 text-xs"
>
{!topic && <option value="">选择话题</option>}
{topics.items.map((item) => (
<option key={item.id} value={item.id}>
{item.title}
</option>
))}
</select>
)}
<div ref={scrollRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
{!topic?.requests.length && (
<div className="text-sm leading-6">
<p>{definition?.welcome_message ?? '有问题可以在这里与老师讨论。'}</p>
{definition?.suggested_questions.map((question) => (
<button
key={question}
onClick={() => setText(question)}
className="mt-2 block w-full rounded-lg border px-3 py-2 text-left hover:bg-muted"
>
{question}
</button>
))}
</div>
)}
{topic?.requests.map((request) => (
<div key={request.id} className="space-y-3">
<p className="whitespace-pre-wrap rounded-xl bg-brand-soft p-3 text-sm">
{request.text}
</p>
{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="whitespace-pre-wrap break-words text-sm leading-7">
{request.response ||
(['running', 'preparing'].includes(request.status) ? '老师正在思考…' : '')}
</div>
{request.omittedMessages > 0 && (
<p className="text-xs text-muted-foreground">
本轮上下文已省略 {request.omittedMessages} 条较早消息。
</p>
)}
{request.error && <p className="text-xs text-destructive">{request.error}</p>}
{request.response && (
<div className="flex gap-3 text-xs text-muted-foreground">
<button onClick={() => void navigator.clipboard.writeText(request.response)}>
复制
</button>
{onBringBack && request.status === 'completed' && (
<button onClick={() => onBringBack(request.response)}>带回主会话草稿</button>
)}
</div>
)}
</div>
))}
{!draftRevision && <>
<button className="consultation-context flex items-center gap-2 px-5 py-3 text-left text-xs" aria-expanded={contextOpen} onClick={() => setContextOpen(!contextOpen)}>
<FolderOpen className="h-3.5 w-3.5" /><span className="min-w-0 flex-1 truncate">{projectName ?? '当前项目'}</span><span className="text-[10px] opacity-70">当前项目</span><ChevronDown className="h-3 w-3" /></button>
{contextOpen && <p className="px-5 py-3 text-xs leading-6 text-muted-foreground">{role === 'friend' ? '结合你的描述和操作对话聊感受;还没有实际看到或试玩的地方,会先和你确认。' : '围绕你的项目一起思考,可以参考当前操作对话。由你决定接下来怎么做。'}</p>}
</>}
{(topics.items.length > 0 || draftRevision) && <div className="px-5 pt-2">
<button className="text-[11px] text-muted-foreground" onClick={() => setHistoryOpen(!historyOpen)} aria-expanded={historyOpen}>以往讨论 <ChevronDown className="inline h-3 w-3" /></button>
{(historyOpen || !role) && <div className="mt-2 flex gap-2">
<select aria-label={`${label}话题`} value={topic?.id ?? ''} disabled={busy} onChange={(e) => void choose(e.target.value)} className="min-w-0 flex-1 rounded-lg border bg-background p-2 text-xs">
{!topic && <option value="">选择话题</option>}{topics.items.map((item) => <option key={item.id} value={item.id}>{item.title}</option>)}
</select><button aria-label={`${label}新话题`} title="新话题" disabled={busy || !enabled} onClick={() => void newTopic()} className="consult-icon"><Plus className="h-4 w-4" /></button>
</div>}
</div>}
<div ref={scrollRef} className="consultation-messages min-h-0 flex-1 overflow-y-auto px-5 py-6">
{!topic?.requests.length && <div className="flex min-h-full flex-col items-center justify-center pb-5 text-center">
<img className="mb-6 h-[68px] w-[68px] rounded-3xl [image-rendering:pixelated]" src={avatar} alt="" />
<h3 className="text-lg font-medium tracking-tight">{definition?.welcome_message || (role === 'friend' ? '一起看看你的作品' : '哪里需要一起想一想?')}</h3>
<p className="mb-6 mt-3 text-xs leading-6 text-muted-foreground">{role === 'friend' ? <>好玩的地方、困惑的瞬间,<br />我们一起发现。</> : <>想法、做法,或遇到的困难,<br />都可以慢慢聊。</>}</p>
<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.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>
<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 && <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>}
</div>}
</div>)}
</div>
{error && (
<p role="alert" className="px-4 py-2 text-xs text-destructive">
{error}
</p>
)}
{topic?.unsaved && (
<div className="px-4 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 && (
<p className="px-4 text-xs text-muted-foreground">老师暂未开放,历史仍可查看。</p>
)}
<form
className="border-t p-3"
onSubmit={(e) => {
e.preventDefault();
void send();
}}
>
{references.length > 0 && (
<div className="mb-2 rounded bg-muted p-2 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={() => setReferences([])}>
移除引用
</button>
{error && <p role="alert" className="px-5 py-2 text-xs leading-5 text-destructive">{error}</p>}
{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(); }}>
{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}
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>
{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>
)}
<textarea
aria-label="向老师提问"
value={text}
disabled={busy}
maxLength={6000}
onChange={(e) => setText(e.target.value)}
placeholder="问问老师…"
rows={3}
className="w-full resize-none rounded-lg border bg-background p-3 text-sm"
/>
<div className="mt-2 flex justify-end">
{running ? (
<button
type="button"
className="rounded border px-3 py-2 text-xs"
onClick={() =>
void teacherApi
.cancel(base, topic!.id, running.id)
.then(consume)
.catch(() => setError('暂时无法停止,请稍后重试。'))
}
>
停止回复
</button>
) : (
<button
type="submit"
disabled={busy || !enabled || !text.trim()}
className="rounded-lg bg-brand px-4 py-2 text-xs text-white disabled:opacity-40"
>
{busy ? '正在发送…' : '提问'}
</button>
)}
</div>
</form>
</aside>