feat(consultation): unify server-distributed agents without fixed roles

This commit is contained in:
2026-09-24 11:56:42 +08:00
parent 248776d855
commit 8a157be4f6
35 changed files with 625 additions and 668 deletions

View File

@@ -1,6 +1,5 @@
import { hostApiFetch, createHostEventSource, ensureHostApiToken } from './host-api';
import type {
ConsultationRole,
TeacherAvailability,
TeacherCheckInInput,
TeacherCheckInResult,
@@ -11,11 +10,14 @@ import type {
TeacherTopic,
TeacherTopicList,
} from '../../shared/coding-teacher';
export function teacherTopicsPath(projectId: string, sourceId: string, role?: ConsultationRole) {
if (role && projectId !== 'preview') return `/api/coding/projects/${encodeURIComponent(projectId)}/${role}-topics`;
export function teacherTopicsPath(projectId: string) {
return projectId === 'preview'
? '/api/coding/teacher-preview/topics'
: `/api/coding/projects/${encodeURIComponent(projectId)}/conversations/${encodeURIComponent(sourceId)}/teacher-topics`;
: `/api/coding/projects/${encodeURIComponent(projectId)}/agent-topics`;
}
/** Read old locally-generated friend histories without copying or rebinding them. */
export function legacyTopicBase(base: string, legacyFriend: boolean) {
return legacyFriend ? base.replace(/agent-topics$/, 'friend-topics') : base;
}
export const teacherApi = {
catalog: () => hostApiFetch<TeacherCatalog>('/api/coding/teacher/teachers'),
@@ -24,9 +26,9 @@ export const teacherApi = {
method: 'POST',
body: JSON.stringify(input),
}),
config: (role: ConsultationRole = 'teacher') =>
config: () =>
hostApiFetch<TeacherAvailability & { definition: TeacherDefinition | null }>(
`/api/coding/${role}/config`
'/api/coding/teacher/config'
),
preview: (draftRevision: number) =>
hostApiFetch<{ payload: TeacherDefinition; draft_revision: number }>(

View File

@@ -49,7 +49,6 @@ import { CodingInteractionPanel } from './CodingInteractionPanel';
import { CodingWelcomeHero } from './CodingWelcomeHero';
import { createLocalConversationSnapshot } from './coding-chat-snapshot';
import { useAuthStore } from '@/stores/auth';
import type { ConsultationRole } from '../../../shared/coding-teacher';
import { TeacherChatPanel } from './TeacherChatPanel';
import { TeacherCompanion } from './TeacherCompanion';
import { useTeacherCompanion } from './use-teacher-companion';
@@ -185,7 +184,7 @@ export function CodingChatPanel({
const [readyWorkProjectId, setReadyWorkProjectId] = useState<string | null>(null);
const recoveryFlight = useRef(false);
const appliedRecovery = useRef<string | null>(null);
const [consultationRole, setConsultationRole] = useState<ConsultationRole | null>(null);
const [consultationOpen, setConsultationOpen] = useState(false);
const [teacherComposing, setTeacherComposing] = useState(false);
const [consultationWidth, setConsultationWidth] = useState(508);
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
@@ -244,13 +243,13 @@ export function CodingChatPanel({
const snapshot = useCodingConversationStore(selectSnapshot);
const runStatus = snapshot?.run.status ?? 'idle';
const running = ['queued', 'running', 'retrying', 'compacting', 'aborting'].includes(runStatus);
const teacherCompanion = useTeacherCompanion({ projectId: activeProject?.id ?? null, sourceId: targetConversationId, sourceBusy: running, sourceArchived: Boolean(selectedConversation?.archivedAt), teacherOpen: consultationRole === 'teacher', teacherComposing });
const teacherCompanion = useTeacherCompanion({ projectId: activeProject?.id ?? null, sourceId: targetConversationId, sourceBusy: running, sourceArchived: Boolean(selectedConversation?.archivedAt), teacherOpen: consultationOpen, teacherComposing });
const [teacherBubble, setTeacherBubble] = useState<HTMLDivElement | null>(null);
const openTeacher = () => {
const selectedText = window.getSelection()?.toString().trim();
setTeacherQuote(selectedText ? { kind: 'code', text: selectedText.slice(0, 12000) } : undefined);
setTeacherQuoteSource(`${activeProject?.id}:${targetConversationId}`);
setConsultationRole('teacher');
setConsultationOpen(true);
setAgentBrowserOpen(true);
};
const promptMode = running && draftKey ? modesByDraftKey[draftKey] ?? 'prompt' : 'prompt';
@@ -741,7 +740,7 @@ export function CodingChatPanel({
}
return (
<section className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background text-foreground" data-testid="coding-chat-panel" data-consultation-open={Boolean(consultationRole)}>
<section className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background text-foreground" data-testid="coding-chat-panel" data-consultation-open={consultationOpen}>
<div className="classroom-main flex min-w-0 flex-1 flex-col">
<CodingConversationHeader
key={`header:${targetConversationId ?? 'none'}`}
@@ -760,9 +759,8 @@ export function CodingChatPanel({
browserAvailable={Boolean(activeProject)}
onToggleBrowser={() => setAgentBrowserOpen((current) => !current)}
projectName={activeProject?.name}
consultationRole={consultationRole}
teacherEntry={activeProject ? <TeacherCompanion companion={teacherCompanion} open={consultationRole === 'teacher'} onOpen={openTeacher} bubbleRef={setTeacherBubble} /> : undefined}
onAskFriend={() => { setTeacherQuote(undefined); setConsultationRole((current) => current === 'friend' ? null : 'friend'); }}
consultationOpen={consultationOpen}
teacherEntry={activeProject ? <TeacherCompanion companion={teacherCompanion} open={consultationOpen} onOpen={openTeacher} bubbleRef={setTeacherBubble} /> : undefined}
/>
<div className="classroom-tabs" role="tablist" aria-label="当前工作">
@@ -885,7 +883,7 @@ export function CodingChatPanel({
</div>
) : selectedAgent && (!selectedAgent.enabled || selectedAgent.archivedAt) ? (
<div className="m-4 rounded-xl border bg-surface-subtle px-4 py-3 text-sm">
此历史会话的编程配置已停用,当前可查看历史与向老师提问。
此历史会话的编程配置已停用,当前可查看历史与向智能体提问。
</div>
) : <CodingComposer
value={draft}
@@ -947,22 +945,22 @@ export function CodingChatPanel({
</div>
</div>
{consultationRole && activeProject && (
{consultationOpen && activeProject && (
<div id="coding-consultation-dock" className="classroom-consultation-dock relative min-h-0 shrink-0 border-l" style={{ width: consultationWidth }}
onKeyDown={(event) => { if (event.key === 'Escape') { setConsultationRole(null); document.querySelector<HTMLButtonElement>(`[aria-label="${consultationRole === 'friend' ? '朋友' : '老师'}"]`)?.focus(); } }}>
onKeyDown={(event) => { if (event.key === 'Escape') { setConsultationOpen(false); document.querySelector<HTMLButtonElement>(`[aria-label="智能体"]`)?.focus(); } }}>
<div role="separator" aria-label="调整咨询栏宽度" aria-orientation="vertical" aria-valuemin={320} aria-valuemax={640} aria-valuenow={consultationWidth} tabIndex={0} className="classroom-consultation-resizer"
onPointerDown={(event) => { if (event.button === 0) { event.preventDefault(); event.currentTarget.setPointerCapture(event.pointerId); } }}
onPointerMove={(event) => { if (event.currentTarget.hasPointerCapture(event.pointerId)) setConsultationWidth(Math.max(320, Math.min(640, window.innerWidth - event.clientX))); }}
onPointerUp={(event) => { if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); }}
onKeyDown={(event) => { if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { event.preventDefault(); setConsultationWidth((width) => Math.max(320, Math.min(640, width + (event.key === 'ArrowLeft' ? 20 : -20)))); } }} />
<TeacherChatPanel key={`${account}:${activeProject.id}:${consultationRole}`}
projectId={activeProject.id} projectName={activeProject.name} sourceId={targetConversationId ?? ''} role={consultationRole}
externalTopic={consultationRole === 'teacher' ? teacherCompanion.topic : undefined}
onTopicChange={consultationRole === 'teacher' ? teacherCompanion.noteTopic : undefined}
onComposingChange={consultationRole === 'teacher' ? setTeacherComposing : undefined}
<TeacherChatPanel key={`${account}:${activeProject.id}`}
projectId={activeProject.id} projectName={activeProject.name} sourceId={targetConversationId ?? ''}
externalTopic={teacherCompanion.topic}
onTopicChange={teacherCompanion.noteTopic}
onComposingChange={setTeacherComposing}
expanded={consultationWidth > 508} onExpand={() => setConsultationWidth((width) => width > 508 ? 508 : 640)}
quote={consultationRole === 'teacher' && teacherQuoteSource === `${activeProject.id}:${targetConversationId}` ? teacherQuote : undefined}
onClose={() => { setConsultationRole(null); document.querySelector<HTMLButtonElement>(`[aria-label="${consultationRole === 'friend' ? '朋友' : '老师'}"]`)?.focus(); }} />
quote={consultationOpen && teacherQuoteSource === `${activeProject.id}:${targetConversationId}` ? teacherQuote : undefined}
onClose={() => { setConsultationOpen(false); document.querySelector<HTMLButtonElement>(`[aria-label="智能体"]`)?.focus(); }} />
</div>
)}
</section>

View File

@@ -9,9 +9,6 @@ import {
Square,
ChevronRight,
} from 'lucide-react';
import teacherAvatar from '@/assets/consultations/teacher-pixel.png';
import friendAvatar from '@/assets/consultations/friend.png';
import type { ConsultationRole } from '../../../shared/coding-teacher';
import { Button } from '@/components/ui/button';
import { CodingConversationRenameDialog } from './CodingConversationRenameDialog';
import { cn } from '@/lib/utils';
@@ -57,9 +54,8 @@ export function CodingConversationHeader({
browserAvailable = false,
onToggleBrowser,
onAskTeacher,
onAskFriend,
teacherEntry,
consultationRole,
consultationOpen,
projectName,
}: {
conversation: CodingConversationMetadata | null;
@@ -71,9 +67,8 @@ export function CodingConversationHeader({
browserAvailable?: boolean;
onToggleBrowser?(): void;
onAskTeacher?(): void;
onAskFriend?(): void;
teacherEntry?: ReactNode;
consultationRole?: ConsultationRole | null;
consultationOpen?: boolean;
projectName?: string;
}) {
const sidebarCollapsed = useSettingsStore((state) => state.sidebarCollapsed);
@@ -137,13 +132,8 @@ export function CodingConversationHeader({
</div>
{teacherEntry}
{([{ role: 'teacher', label: '老师', avatar: teacherAvatar, action: teacherEntry ? undefined : onAskTeacher }, { role: 'friend', label: '朋友', avatar: friendAvatar, action: onAskFriend }] as const).map((person) => person.action && (
<button key={person.role} type="button" aria-label={person.label} aria-expanded={consultationRole === person.role} aria-controls="coding-consultation-dock"
className={cn('no-drag flex h-9 shrink-0 items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-surface-subtle', consultationRole === person.role && 'bg-[#eef1e8] text-[#42543a]')}
onMouseDown={(event) => event.preventDefault()} onClick={person.action}>
<img src={person.avatar} alt="" className="h-6 w-6 rounded-md [image-rendering:pixelated]" /><span>{person.label}</span>
</button>
))}
{!teacherEntry && onAskTeacher && <button type="button" aria-label="智能体" aria-expanded={consultationOpen} aria-controls="coding-consultation-dock"
className="no-drag shrink-0 rounded-lg px-2 py-1 text-xs" onClick={onAskTeacher}>智能体</button>}
{onToggleBrowser ? (
<Button
type="button"

View File

@@ -1,12 +1,8 @@
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-pixel.png';
import friendAvatar from '@/assets/consultations/friend.png';
import { cn } from '@/lib/utils';
import { teacherApi, teacherTopicsPath } from '@/lib/coding-teacher';
import { teacherApi, teacherTopicsPath, legacyTopicBase } from '@/lib/coding-teacher';
import type {
ConsultationRole,
TeacherDefinition,
TeacherCatalog,
TeacherReference,
@@ -26,7 +22,6 @@ export function TeacherChatPanel({
quote,
draftRevision,
sampleContext,
role,
expanded,
onExpand,
externalTopic,
@@ -40,7 +35,6 @@ export function TeacherChatPanel({
quote?: TeacherReference;
draftRevision?: number;
sampleContext?: string;
role?: ConsultationRole;
projectName?: string;
expanded?: boolean;
onExpand?(): void;
@@ -48,28 +42,34 @@ export function TeacherChatPanel({
onTopicChange?(topic: TeacherTopic): void;
onComposingChange?(composing: boolean): void;
}) {
const base = teacherTopicsPath(projectId, sourceId, role);
const base = teacherTopicsPath(projectId);
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
const draftKey = role ? `makelore-consultation-draft:${account}:${projectId}:${role}` : null;
// Retain the existing project draft key; its suffix is a storage identifier, not a role.
const draftKey = !draftRevision ? `makelore-consultation-draft:${account}:${projectId}:teacher` : null;
const [saved] = useState<{ text?: string; references?: TeacherReference[]; pending?: TeacherSend }>(() => {
try { return draftKey ? JSON.parse(localStorage.getItem(draftKey) ?? '{}') : {}; } catch { return {}; }
});
const [legacyDraft] = useState<{ text?: string; references?: TeacherReference[] }>(() => {
try { return draftKey ? JSON.parse(localStorage.getItem(`makelore-consultation-draft:${account}:${projectId}:friend`) ?? '{}') : {}; } 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 studentTeacher = role === 'teacher' && !draftRevision;
const label = '智能体';
const discussionEnabled = !draftRevision;
const [historyOpen, setHistoryOpen] = useState(false);
const [focus, setFocus] = useState<{ topicId: string; id: string; label: string } | null>(null);
const [definition, setDefinition] = useState<TeacherDefinition | null>(null);
const avatar = role === 'friend' ? friendAvatar : draftRevision && definition ? getAgentAvatarSrc(definition.avatar_id) : teacherAvatar;
const avatar = getAgentAvatarSrc(definition?.avatar_id);
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 legacyFriend = topic?.role === 'friend';
const topicBase = legacyTopicBase(base, legacyFriend);
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]);
@@ -82,7 +82,7 @@ export function TeacherChatPanel({
const [legacyEnabled, setLegacyEnabled] = useState(false);
const [teachers, setTeachers] = useState<TeacherCatalog['items']>([]);
const [selectedTeacherVersion, setSelectedTeacherVersion] = useState<number>();
const topicEnabled = !topic ? enabled
const topicEnabled = legacyFriend ? false : !topic ? enabled
: topic.definition.config_id
? teachers.some((item) => item.teacher_id === topic.definition.config_id)
: legacyEnabled;
@@ -124,11 +124,11 @@ export function TeacherChatPanel({
}, [externalTopic, projectId, consume]);
useEffect(() => { if (topic) onTopicChange?.(topic); }, [topic, onTopicChange]);
useEffect(() => {
if (role && !busy && !focusedOnce.current) {
if (!busy && !focusedOnce.current) {
focusedOnce.current = true;
inputRef.current?.focus();
}
}, [role, busy]);
}, [busy]);
useEffect(() => {
if (quote) setReferences([quote]);
}, [quote]);
@@ -139,7 +139,7 @@ export function TeacherChatPanel({
try {
const config = draftRevision
? { definition: (await teacherApi.preview(draftRevision)).payload, enabled: true }
: await teacherApi.config(role);
: await teacherApi.config();
if (alive) {
setDefinition(config.definition);
setEnabled(config.enabled);
@@ -150,11 +150,9 @@ export function TeacherChatPanel({
if (alive) {
setTeachers(catalog.items);
const selected = catalog.items.find((item) => item.is_default) ?? catalog.items[0];
if (role !== 'friend') {
setSelectedTeacherVersion(selected?.version);
setEnabled(catalog.items.length > 0 || (config.enabled && !config.definition?.config_id));
if (selected) setDefinition(selected.definition);
}
setSelectedTeacherVersion(selected?.version);
setEnabled(catalog.items.length > 0 || (config.enabled && !config.definition?.config_id));
if (selected) setDefinition(selected.definition);
}
}
} catch (e) {
@@ -186,14 +184,14 @@ export function TeacherChatPanel({
// eslint-disable-next-line react-hooks/exhaustive-deps
generation.current++;
};
}, [base, draftRevision, role, label, consume]);
}, [base, draftRevision, label, consume]);
useEffect(() => {
if (!topic?.id) return;
if (!topic?.id || legacyFriend) return;
const streamTopicId = topic.id;
let closed = false,
stream: EventSource | undefined;
void teacherApi
.events(base, topic.id)
.events(topicBase, topic.id)
.then((source) => {
if (closed) {
source.close();
@@ -225,13 +223,13 @@ export function TeacherChatPanel({
closed = true;
stream?.close();
};
}, [base, topic?.id, consume, label]);
}, [topicBase, topic?.id, legacyFriend, consume, label]);
const choose = async (id: string) => {
const version = ++generation.current;
setBusy(true);
setError('');
try {
const next = await teacherApi.read(base, id);
const next = await teacherApi.read(legacyTopicBase(base, topics.items.some(item => item.id === id && item.legacyRole === 'friend')), id);
if (version === generation.current) {
consume(next);
setDefinition(next.definition);
@@ -287,7 +285,7 @@ export function TeacherChatPanel({
consume(current);
setDefinition(current.definition);
}
const presentation = studentTeacher && (!action?.intent || action.intent === 'question' || action.intent === 'guided-help') ? 'discussion-v1' as const : undefined;
const presentation = discussionEnabled && (!action?.intent || action.intent === 'question' || action.intent === 'guided-help') ? 'discussion-v1' as const : undefined;
const discussion = presentation && current.discussion?.status === 'active'
? action?.discussion ?? { toolId: current.discussion.id, revision: current.discussion.revision,
...(activeFocus?.topicId === current.id ? { focusId: activeFocus.id } : {}) } : undefined;
@@ -306,11 +304,11 @@ export function TeacherChatPanel({
requestId: crypto.randomUUID(), text: question, references: questionReferences,
...(presentation ? { presentation } : {}), ...(discussion ? { discussion } : {}),
...(action?.intent ? { intent: action.intent } : {}),
...(role && sourceId ? { sourceConversationId: sourceId } : {}),
...(sourceId ? { sourceConversationId: sourceId } : {}),
};
pending.current = input;
persistDraft(text, references, input);
const next = await teacherApi.send(base, current.id, input);
const next = await teacherApi.send(topicBase, current.id, input);
if (version !== generation.current) return;
consume(next);
pending.current = null;
@@ -340,7 +338,7 @@ export function TeacherChatPanel({
setBusy(true);
setError('');
try {
const next = await teacherApi.updateDiscussion(base, current.id, {
const next = await teacherApi.updateDiscussion(topicBase, current.id, {
toolId: current.discussion.id, revision: current.discussion.revision, action, ...(itemId ? { itemId } : {}),
});
if (version === generation.current) { consume(next); setFocus(null); }
@@ -360,28 +358,27 @@ export function TeacherChatPanel({
toolId: topic.discussion.id, revision: topic.discussion.revision, transition: 'structure',
} });
};
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); };
const questions = definition?.suggested_questions.length ? definition.suggested_questions : role === 'friend'
? ['想听听你对作品的第一印象', '我想和你聊聊刚才的体验']
: ['我还没想好下一步做什么', '帮我理一理现在的思路'];
const questions = definition?.suggested_questions ?? [];
return (
<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}聊天`}>
<aside className="consultation-pane flex h-full min-h-0 w-full flex-col"
data-testid="teacher-chat-panel" 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={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' ? '陪你体验,也听你说' : !role ? '结合当前会话和项目文件答疑' : '一起想清楚,再动手'}</p></div>
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{definition?.name ?? '智能体'}</h2>
<p className="mt-1 text-[11px] text-muted-foreground">{draftRevision ? '运营草稿试聊' : definition?.description}</p></div>
<button aria-label={`${label}新话题`} title="新话题" disabled={busy || !enabled} onClick={() => void newTopic()} className="consult-icon"><Plus className="h-4 w-4" /></button>
{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>
{!draftRevision && role !== 'friend' && teachers.length > 1 && (
{!draftRevision && teachers.length > 0 && (
<label className="px-5 pb-2 text-[11px] text-muted-foreground">
新话题使用的老师
<select aria-label="新话题使用的老师" value={selectedTeacherVersion ?? ''} disabled={busy}
onChange={(event) => setSelectedTeacherVersion(Number(event.target.value))}
新话题使用的智能体
<select aria-label="新话题使用的智能体" value={selectedTeacherVersion ?? ''} disabled={busy}
onChange={(event) => { const selected = teachers.find(item => item.version === Number(event.target.value)); setSelectedTeacherVersion(selected?.version); if (!topic && selected) setDefinition(selected.definition); }}
className="mt-1 w-full rounded-lg border bg-background p-2 text-xs text-foreground">
{teachers.map((item) => <option key={item.teacher_id} value={item.version}>
{item.definition.name}{item.is_default ? '(默认)' : ''}
@@ -391,13 +388,13 @@ export function TeacherChatPanel({
)}
{(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">
{(historyOpen || draftRevision) && <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>
{!topic && <option value="">选择话题</option>}{topics.items.map((item) => <option key={item.id} value={item.id}>{item.title}{item.legacyRole ? '(旧版,仅查看)' : ''}</option>)}
</select>
</div>}
</div>}
{studentTeacher && topic?.discussion && <TeacherDiscussionPanel key={topic.id} discussion={topic.discussion}
{discussionEnabled && topic?.discussion && <TeacherDiscussionPanel key={topic.id} discussion={topic.discussion}
disabled={helpUnavailable} focusId={activeFocus?.id}
onAction={(action, itemId) => void updateDiscussion(action, itemId)} onFocus={focusItem} onStructure={structureIdeas}
onDiscuss={(id, question) => {
@@ -407,15 +404,12 @@ export function TeacherChatPanel({
<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">{studentTeacher ? '有问题,随时来找我' : definition?.welcome_message || (role === 'friend' ? '一起看看你的作品' : '哪里需要一起想一想?')}</h3>
<p className="mb-6 mt-3 text-[13px] leading-6 text-muted-foreground">{studentTeacher
? <>有问题可以直接问我。<br />还没想好问什么,也没关系。</>
: role === 'friend' ? <>好玩的地方、困惑的瞬间,<br />我们一起发现。</> : <>想法、做法,或遇到的困难,<br />都可以慢慢聊。</>}</p>
{!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>}
<h3 className="text-lg font-medium tracking-tight">{definition?.welcome_message || '开始对话'}</h3>
<div className="mt-6 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">
{request.intent === 'check-in'
? <p className="text-[11px] text-muted-foreground">老师来看看你的进展</p>
? <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>
@@ -424,31 +418,38 @@ export function TeacherChatPanel({
? <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' && <>
<p className="whitespace-pre-wrap break-words text-[13px] leading-7">{request.response}</p>
<div className="flex flex-col gap-2" aria-label="可以和老师聊的问题">
<div className="flex flex-col gap-2" aria-label="可以和智能体聊的问题">
{request.suggestedQuestions?.map((question) => <button key={question} type="button" disabled={helpUnavailable} onClick={() => void send({ text: question })} className="consultation-suggestion flex min-h-11 items-center justify-between gap-3 rounded-xl border bg-white px-3 py-3 text-left text-[13px] leading-6 transition-colors disabled:cursor-not-allowed disabled:opacity-50">{question}<ChevronRight className="h-3.5 w-3.5 shrink-0 opacity-60" /></button>)}
</div>
<button type="button" disabled={helpUnavailable} onClick={askForGuidance} className="consultation-guided-help min-h-10 text-left text-xs leading-6 underline decoration-current/30 underline-offset-4 disabled:cursor-not-allowed disabled:opacity-50">我也说不清,你带我看看</button>
<p className="text-[11px] leading-5 text-muted-foreground">也可以直接在下面说说你的想法。</p>
</>}
{['failed', 'cancelled', 'interrupted'].includes(request.status) && <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-guided-help min-h-10 text-xs underline underline-offset-4 disabled:opacity-50">再请老师看看</button>}
{['failed', 'cancelled', 'interrupted'].includes(request.status) && <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-guided-help min-h-10 text-xs underline underline-offset-4 disabled:opacity-50">再请智能体看看</button>}
</> : <div className="whitespace-pre-wrap break-words text-[13px] leading-7">{request.response || (['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" />{request.discussionContext ? '正在梳理你的新想法…' : `${label}正在想…`}</span> : ['cancelled', 'interrupted'].includes(request.status) ? '这次先停在这里。想继续时可以再说说。' : '')}</div>}
{studentTeacher && request.intent !== 'suggestions' && request.status === 'completed' && topic.discussion?.status !== 'active' && topic.discussion?.status !== 'offered' && Boolean(request.suggestedQuestions?.length) && <div className="flex flex-col gap-2" aria-label="接着聊">
{discussionEnabled && request.intent !== 'suggestions' && request.status === 'completed' && topic.discussion?.status !== 'active' && topic.discussion?.status !== 'offered' && Boolean(request.suggestedQuestions?.length) && <div className="flex flex-col gap-2" aria-label="接着聊">
{request.suggestedQuestions?.map(question => <button type="button" key={question} disabled={helpUnavailable} onClick={() => void send({ text: question })} className="consultation-suggestion rounded-xl border px-3 py-2 text-left text-xs leading-6">{question}<ChevronRight className="ml-1 inline h-3 w-3" /></button>)}
</div>}
{request.discussionError && <p className="text-xs leading-6 text-muted-foreground">{request.discussionError}</p>}
{request.progress && ['running', 'preparing'].includes(request.status) && <p role="status" className="text-xs text-muted-foreground">{request.progress}</p>}
{(request.truncatedMessages ?? 0) > 0 && <p className="text-xs text-muted-foreground">{draftRevision ? '较长的上下文已节选。' : '较长的上下文已节选,老师可按需读取原文。'}</p>}
{(request.truncatedMessages ?? 0) > 0 && <p className="text-xs text-muted-foreground">{draftRevision ? '较长的上下文已节选。' : '较长的上下文已节选,智能体可按需读取原文。'}</p>}
{request.omittedMessages > 0 && <p className="text-[10px] text-muted-foreground">本轮参考了较近的讨论,省略了 {request.omittedMessages} 条较早内容。</p>}
{request.error && <p className="text-xs text-destructive">{request.error}</p>}
{!role && onBringBack && request.response && request.intent !== 'suggestions' && request.status === 'completed' && <div className="text-[11px] text-muted-foreground">
{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>
{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>}
{!topicEnabled && !error && !busy && <p className="px-5 pb-2 text-xs text-muted-foreground">{label}暂未开放,历史仍可查看。</p>}
{topic?.unsaved && <div className="px-5 py-2 text-xs text-destructive">回复尚未保存,请复制或重试保存。<button className="ml-2 underline" onClick={() => void teacherApi.save(topicBase, topic.id).then(consume).catch(() => setError('保存失败,请先复制回复。'))}>重试保存</button></div>}
{!topicEnabled && !error && !busy && <p className="px-5 pb-2 text-xs text-muted-foreground">{legacyFriend ? '这是旧版内置朋友的话题,仅供查看。请选择智能体新建话题。' : `${label}暂未开放,历史仍可查看。`}</p>}
<form className="px-4 pb-4 pt-2" onSubmit={(e) => { e.preventDefault(); void send(); }}>
{(legacyDraft.text?.trim() || legacyDraft.references?.length) && <details className="mb-2 text-xs text-muted-foreground">
<summary>查看旧版朋友草稿</summary>
<div className="max-h-40 overflow-auto whitespace-pre-wrap rounded-lg border p-2">
{legacyDraft.text}
{legacyDraft.references?.map((ref, index) => <pre className="mt-2 whitespace-pre-wrap" key={index}>{ref.text}</pre>)}
</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>}
<div className="consultation-composer rounded-2xl border bg-white p-3 focus-within:ring-2 focus-within:ring-black/5">
{activeFocus && <DiscussionFocus label={activeFocus.label} onClear={() => setFocus(null)} />}
@@ -456,10 +457,10 @@ export function TeacherChatPanel({
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" 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 || !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>}
{discussionEnabled ? <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 />}
{running ? <button type="button" className="rounded-lg border px-3 py-2 text-xs" onClick={() => void teacherApi.cancel(topicBase, topic!.id, 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>}
</div>
</div>
</form>

View File

@@ -1,6 +1,6 @@
import { ArrowUpRight, Loader2, X } from 'lucide-react';
import type { Ref } from 'react';
import teacherAvatar from '@/assets/consultations/teacher-pixel.png';
import { getAgentAvatarSrc } from '@/lib/agent-avatars';
import type { useTeacherCompanion } from './use-teacher-companion';
type Companion = ReturnType<typeof useTeacherCompanion>;
@@ -11,32 +11,33 @@ export function TeacherCompanion({ companion, open, onOpen, bubbleRef }: {
bubbleRef?: Ref<HTMLDivElement>;
}) {
const { definition, invitation, welcome, loading, enabled, checking, error } = companion;
const name = definition?.name || '老师';
const name = definition?.name || '智能体';
const avatar = getAgentAvatarSrc(definition?.avatar_id);
const viewConversation = () => { companion.dismiss(); onOpen(); };
const status = loading ? '正在连接老师…'
: checking ? '老师在看看你最近的进展…'
: error || (!enabled ? '老师暂未开放,仍可查看以往讨论' : open ? '我们慢慢聊,想到什么都可以说' : '点我聊聊,想到什么都可以说');
const status = loading ? '正在连接智能体…'
: checking ? '智能体在看看你最近的进展…'
: error || (!enabled ? '智能体暂未开放,仍可查看以往讨论' : open ? '我们慢慢聊,想到什么都可以说' : '点我聊聊,想到什么都可以说');
return (
<section className="teacher-companion no-drag" aria-label="老师陪伴" data-testid="teacher-companion">
<button type="button" className="teacher-companion-person" title={status} aria-label="老师" aria-expanded={open} aria-controls="coding-consultation-dock" onMouseDown={(event) => event.preventDefault()} onClick={onOpen}>
<span className="teacher-companion-avatar"><img src={teacherAvatar} alt="" />{invitation && <span className="teacher-companion-unread" aria-hidden="true" />}</span>
<section className="teacher-companion no-drag" aria-label="智能体陪伴" data-testid="teacher-companion">
<button type="button" className="teacher-companion-person" title={status} aria-label="智能体" aria-expanded={open} aria-controls="coding-consultation-dock" onMouseDown={(event) => event.preventDefault()} onClick={onOpen}>
<span className="teacher-companion-avatar"><img src={avatar} alt="" />{invitation && <span className="teacher-companion-unread" aria-hidden="true" />}</span>
<span className="teacher-companion-name">{name}</span>
{checking && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" aria-label="老师正在思考" />}
{checking && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" aria-label="智能体正在思考" />}
</button>
{(invitation || welcome) && <div ref={bubbleRef} className="teacher-companion-presence" data-testid="teacher-presence">
<div className="teacher-companion-bubble" data-testid="teacher-invitation" data-bubble-kind={invitation ? 'check-in' : 'welcome'}>
<div className="teacher-companion-bubble-heading">
<div className="teacher-companion-invitation-label">{name}</div>
<button type="button" className="teacher-companion-dismiss" aria-label="收起老师气泡" onClick={companion.dismiss}><X className="h-3.5 w-3.5" aria-hidden="true" /></button>
<button type="button" className="teacher-companion-dismiss" aria-label="收起智能体气泡" onClick={companion.dismiss}><X className="h-3.5 w-3.5" aria-hidden="true" /></button>
</div>
<p className="teacher-companion-message" role="status">{invitation?.response ?? welcome}</p>
<div className="teacher-companion-actions">
<button type="button" onClick={viewConversation}>{open ? '看看老师说的' : '和老师聊聊'} <ArrowUpRight aria-hidden="true" className="h-3 w-3" /></button>
<button type="button" onClick={viewConversation}>{open ? '看看智能体说的' : '和智能体聊聊'} <ArrowUpRight aria-hidden="true" className="h-3 w-3" /></button>
<button type="button" onClick={companion.dismiss}>等会儿聊</button>
</div>
</div>
<button type="button" className="teacher-companion-speaker" aria-label="打开这条老师消息" onMouseDown={(event) => event.preventDefault()} onClick={viewConversation}>
<img src={teacherAvatar} alt="" />
<button type="button" className="teacher-companion-speaker" aria-label="打开这条智能体消息" onMouseDown={(event) => event.preventDefault()} onClick={viewConversation}>
<img src={avatar} alt="" />
</button>
</div>}
</section>

View File

@@ -26,7 +26,7 @@ export function TeacherPreviewPage() {
return (
<main className="flex h-full min-h-0 flex-col gap-4 p-5">
<div>
<h1 className="text-lg font-semibold">编程老师 · 草稿试聊</h1>
<h1 className="text-lg font-semibold">智能体 · 草稿试聊</h1>
<p className="mt-1 text-sm text-muted-foreground">
使用当前运营账号的词元点数。填写示例上下文后新建话题,不会读取学生项目。
</p>

View File

@@ -28,12 +28,6 @@
.consultation-send { background: #536947; }
.consult-icon { display: flex; flex-shrink: 0; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 6px; color: #8c9781; }
.consult-icon:hover { background: #eaf0e1; color: #45563b; }
.consultation-friend { background: #fcfaf6; color: #756347; }
.consultation-friend .consultation-user { background: #f0e9db; }
.consultation-friend .consultation-composer, .consultation-friend .consultation-suggestion { border-color: #e6ddca; }
.consultation-friend .consultation-suggestion { color: #8b7657; }
.consultation-friend .consultation-suggestion:hover, .consultation-friend .consult-icon:hover { background: #f4eddf; }
.consultation-friend .consultation-send { background: #8c7858; }
@media (max-width: 1100px) { .classroom-tabs { padding: 0 18px; } }
@media (max-width: 900px) { .classroom-consultation-dock { position: absolute; inset: 0 0 0 auto; z-index: 45; max-width: 100%; box-shadow: -12px 0 36px #24311b0d; } .classroom-consultation-resizer { display: none; } }
@media (max-width: 600px) { .classroom-consultation-dock { width: 100%!important; } .classroom-workspace [data-testid="coding-message-composer"] { width: calc(100% - 24px); } }

View File

@@ -83,9 +83,9 @@ export function useTeacherCompanion(options: Options) {
setState((current) => ({ ...current, loading: false }));
return () => { alive = false; };
}
const base = teacherTopicsPath(projectId, '', 'teacher');
const base = teacherTopicsPath(projectId);
const loadConfig = async () => {
const config = await teacherApi.config('teacher');
const config = await teacherApi.config();
if (alive) setState((current) => ({ ...current, definition: config.definition, enabled: config.enabled, loading: false }));
return config;
};
@@ -98,7 +98,7 @@ export function useTeacherCompanion(options: Options) {
const topic = await teacherApi.read(base, topics.lastSelectedTopicId);
if (alive && (!latest.current.state.topic || latest.current.state.topic.id === topic.id)) noteTopic(topic);
} catch {
if (alive) setState((current) => ({ ...current, loading: false, error: '老师暂时没连上,稍后再来看看。' }));
if (alive) setState((current) => ({ ...current, loading: false, error: '智能体暂时没连上,稍后再来看看。' }));
}
})();
// Keep the deadline across Renderer reloads/project switches, but allow a
@@ -109,6 +109,7 @@ export function useTeacherCompanion(options: Options) {
writeLocal(storageKey + ':last-attempt', lastAttempt);
const check = async () => {
const { options: current, state: currentState } = latest.current;
if (currentState.topic?.role === 'friend') return;
if (!alive || inFlight.current || document.visibilityState !== 'visible' || currentState.loading) return;
// A dropped event stream must not leave a completed reply stuck as thinking.
if (currentState.topic?.requests.some((request) => ['preparing', 'running'].includes(request.status))) {
@@ -146,7 +147,7 @@ export function useTeacherCompanion(options: Options) {
} catch (error) {
if (!alive) return;
if (error instanceof AppError && typeof error.details?.status === 'number' && error.details.status >= 400 && error.details.status < 500 && error.details.status !== 408) writeLocal(storageKey + ':pending', null);
setState((value) => ({ ...value, error: '老师这次没连上,可以点头像找老师聊聊。' }));
setState((value) => ({ ...value, error: '智能体这次没连上,可以点头像找智能体聊聊。' }));
} finally {
if (alive) inFlight.current = false;
}
@@ -167,10 +168,10 @@ export function useTeacherCompanion(options: Options) {
const topicId = topic?.id;
const topicProjectId = topic?.projectId;
useEffect(() => {
if (!topicId || !topicProjectId) return;
if (!topicId || !topicProjectId || topic?.role === 'friend') return;
let alive = true;
let stream: EventSource | undefined;
const base = teacherTopicsPath(topicProjectId, '', 'teacher');
const base = teacherTopicsPath(topicProjectId);
void teacherApi.events(base, topicId).then((source) => {
if (!alive) { source.close(); return; }
stream = source;
@@ -180,18 +181,19 @@ export function useTeacherCompanion(options: Options) {
});
}).catch(() => { /* The consultation can still be opened and reloaded. */ });
return () => { alive = false; stream?.close(); };
}, [topicId, topicProjectId, noteTopic]);
}, [topicId, topicProjectId, topic?.role, noteTopic]);
const last = topic?.requests.at(-1);
const invitation = unreadInvitation({ topic, seen: state.seen });
const visibleState = stateScope.current === scope ? state : { definition: null, enabled: false, loading: true, topic: null, seen: [], welcomeDismissed: true, error: '' };
// This is the published greeting, not a fabricated project assessment.
const welcome = !visibleState.loading && visibleState.enabled && !visibleState.welcomeDismissed
? visibleState.definition?.welcome_message.trim() || null : null;
const selectedDefinition = topic?.definition ?? visibleState.definition;
const welcome = topic?.role !== 'friend' && !visibleState.loading && visibleState.enabled && !visibleState.welcomeDismissed
? selectedDefinition?.welcome_message.trim() || null : null;
return {
...visibleState,
error: last?.intent === 'check-in' && ['failed', 'interrupted'].includes(last.status) ? '老师这次没连上,可以点头像找老师聊聊。' : visibleState.error,
definition: topic?.definition ?? visibleState.definition,
error: last?.intent === 'check-in' && ['failed', 'interrupted'].includes(last.status) ? '智能体这次没连上,可以点头像找智能体聊聊。' : visibleState.error,
definition: selectedDefinition,
topic,
invitation,
welcome,