merge: retain agent refresh in the updated teacher trial

This commit is contained in:
鲨鱼辣椒 committed 2026-09-28 14:09:50 +08:00
commit 9adab45388
14 files changed
+527 -60

No files matched your search

+2
View File
@@ -972,6 +972,8 @@ export function CodingChatPanel({
<TeacherChatPanel key={`${account}:${activeProject.id}:${teacherCompanion.selectedAgent?.teacher_id ?? 'history'}`}
projectId={activeProject.id} projectName={activeProject.name} sourceId={targetConversationId ?? ''}
selectedAgent={teacherCompanion.selectedAgent}
catalogState={teacherCompanion.catalogState}
reloadCatalog={teacherCompanion.reloadCatalog}
externalTopic={teacherCompanion.topic}
onTopicChange={teacherCompanion.noteTopic}
onComposingChange={setTeacherComposing}
+47 -25
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowUp, ChevronDown, ChevronRight, Loader2 } from 'lucide-react';
import { useAuthStore } from '@/stores/auth';
import { teacherApi, teacherTopicsPath, legacyTopicBase } from '@/lib/coding-teacher';
import { teacherApi, teacherTopicsPath, legacyTopicBase, type TeacherCatalogState } from '@/lib/coding-teacher';
import type {
TeacherDefinition,
TeacherCatalog,
@@ -31,6 +31,8 @@ export function TeacherChatPanel({
onTopicChange,
onComposingChange,
selectedAgent,
catalogState,
reloadCatalog,
}: {
projectId: string;
sourceId: string;
@@ -43,6 +45,8 @@ export function TeacherChatPanel({
onTopicChange?(topic: TeacherTopic): void;
onComposingChange?(composing: boolean): void;
selectedAgent?: TeacherCatalog['items'][number];
catalogState?: TeacherCatalogState;
reloadCatalog?(): Promise<void>;
}) {
const base = teacherTopicsPath(projectId);
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
@@ -63,7 +67,9 @@ export function TeacherChatPanel({
}, [draftKey]);
const label = '智能体';
const [historyOpen, setHistoryOpen] = useState(false);
const [definition, setDefinition] = useState<TeacherDefinition | null>(null);
const [localDefinition, setDefinition] = useState<TeacherDefinition | null>(null);
const catalogStateRef = useRef(catalogState);
catalogStateRef.current = catalogState;
const externalTopicRef = useRef(externalTopic);
externalTopicRef.current = externalTopic;
const selectedAgentId = selectedAgent?.teacher_id;
@@ -83,10 +89,20 @@ export function TeacherChatPanel({
draftRef.current = { text, references };
const [error, setError] = useState('');
const [busy, setBusy] = useState(true);
const [enabled, setEnabled] = useState(false);
const [legacyEnabled, setLegacyEnabled] = useState(false);
const [teachers, setTeachers] = useState<TeacherCatalog['items']>([]);
const [selectedTeacherVersion, setSelectedTeacherVersion] = useState<number>();
const [localEnabled, setEnabled] = useState(false);
const [localLegacyEnabled, setLegacyEnabled] = useState(false);
const [localTeachers, setTeachers] = useState<TeacherCatalog['items']>([]);
const [localTeacherVersion, setSelectedTeacherVersion] = useState<number>();
// Share the current catalog with the topbar without reloading the topic or its draft.
const teachers = catalogState?.catalog.items ?? localTeachers;
const selectedTeacher = selectedAgentId ? teachers.find((item) => item.teacher_id === selectedAgentId)
: teachers.find((item) => item.is_default) ?? teachers[0];
const enabled = catalogState ? (selectedAgentId ? Boolean(selectedTeacher)
: teachers.length > 0 || (catalogState.config.enabled && !catalogState.config.definition?.config_id)) : localEnabled;
const legacyEnabled = catalogState?.config.enabled ?? localLegacyEnabled;
const selectedTeacherVersion = catalogState ? selectedTeacher?.version : localTeacherVersion;
const definition = topic?.definition ?? (catalogState
? selectedTeacher?.definition ?? selectedAgent?.definition ?? catalogState.config.definition : localDefinition);
const topicEnabled = legacyFriend ? false : !topic ? enabled
: topic.definition.config_id
? teachers.some((item) => item.teacher_id === topic.definition.config_id)
@@ -137,25 +153,31 @@ export function TeacherChatPanel({
setBusy(true);
void (async () => {
try {
const config = draftRevision
? { definition: (await teacherApi.preview(draftRevision)).payload, enabled: true }
: await teacherApi.config();
if (alive) {
setDefinition(config.definition);
setEnabled(config.enabled);
setLegacyEnabled(config.enabled);
}
if (!draftRevision) {
const catalog = await teacherApi.catalog();
if (!draftRevision && reloadCatalog) {
// Opening the panel still checks for updates through the shared loader.
// A failed background read leaves the last usable catalog in place.
await reloadCatalog().catch(() => undefined);
} else if (draftRevision || !catalogStateRef.current) {
const config = draftRevision
? { definition: (await teacherApi.preview(draftRevision)).payload, enabled: true }
: await teacherApi.config();
if (alive) {
setTeachers(catalog.items);
const selected = selectedAgentId
? catalog.items.find((item) => item.teacher_id === selectedAgentId)
: catalog.items.find((item) => item.is_default) ?? catalog.items[0];
setSelectedTeacherVersion(selected?.version);
setEnabled(selectedAgentId ? Boolean(selected) : catalog.items.length > 0 || (config.enabled && !config.definition?.config_id));
const visibleAgent = selected ?? selectedAgentRef.current;
if (visibleAgent) setDefinition(visibleAgent.definition);
setDefinition(config.definition);
setEnabled(config.enabled);
setLegacyEnabled(config.enabled);
}
if (!draftRevision) {
const catalog = await teacherApi.catalog();
if (alive) {
setTeachers(catalog.items);
const selected = selectedAgentId
? catalog.items.find((item) => item.teacher_id === selectedAgentId)
: catalog.items.find((item) => item.is_default) ?? catalog.items[0];
setSelectedTeacherVersion(selected?.version);
setEnabled(selectedAgentId ? Boolean(selected) : catalog.items.length > 0 || (config.enabled && !config.definition?.config_id));
const visibleAgent = selected ?? selectedAgentRef.current;
if (visibleAgent) setDefinition(visibleAgent.definition);
}
}
}
} catch (e) {
@@ -190,7 +212,7 @@ export function TeacherChatPanel({
// eslint-disable-next-line react-hooks/exhaustive-deps
generation.current++;
};
}, [base, draftRevision, label, consume, selectedAgentId]);
}, [base, draftRevision, label, consume, selectedAgentId, reloadCatalog]);
useEffect(() => {
if (!topic?.id || legacyFriend) return;
const streamTopicId = topic.id;
+11 -1
View File
@@ -1,4 +1,4 @@
import { ArrowUpRight, Loader2, X } from 'lucide-react';
import { ArrowUpRight, Loader2, RefreshCw, X } from 'lucide-react';
import { useState, type Ref } from 'react';
import { Provider as TooltipProvider } from '@radix-ui/react-tooltip';
import { TeacherAvatar } from './TeacherAvatar';
@@ -28,6 +28,9 @@ export function TeacherCompanion({ companion, open, onOpen, onToggle, bubbleRef,
const status = loading ? '正在连接智能体…'
: checking ? '智能体在看看你最近的进展…'
: error || (!enabled ? '智能体暂未开放,仍可查看以往讨论' : open ? '我们慢慢聊,想到什么都可以说' : '点我聊聊,想到什么都可以说');
const refreshMessage = companion.refreshing ? '正在刷新…'
: companion.refreshStatus === 'error' ? '刷新失败,请重试'
: companion.refreshStatus === 'success' ? '已更新' : '';
return (
<TooltipProvider delayDuration={180} skipDelayDuration={100}>
<section className="teacher-companion no-drag" aria-label="智能体陪伴" data-testid="teacher-companion">
@@ -50,6 +53,13 @@ export function TeacherCompanion({ companion, open, onOpen, onToggle, bubbleRef,
{checking && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" aria-label="智能体正在思考" />}
</button></TeacherIntroduction>}
</nav>
<button type="button" className="consultation-agents-refresh" aria-label="刷新智能体"
title={refreshMessage || '刷新智能体'} disabled={loading || companion.refreshing} aria-busy={companion.refreshing}
onMouseDown={(event) => event.preventDefault()} onClick={() => { setIntroductionId(null); void companion.refresh(); }}>
<RefreshCw className={`h-3.5 w-3.5 shrink-0 ${companion.refreshing ? 'animate-spin motion-reduce:animate-none' : ''}`} aria-hidden="true" />
<span>{companion.refreshing ? '刷新中' : companion.refreshStatus === 'error' ? '刷新失败' : companion.refreshStatus === 'success' ? '已更新' : '刷新'}</span>
</button>
<span className="sr-only" role="status" aria-live="polite">{refreshMessage}</span>
{(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">
+15 -3
View File
@@ -1,6 +1,6 @@
import * as Tooltip from '@radix-ui/react-tooltip';
import { Sparkles } from 'lucide-react';
import type { ReactElement, Ref } from 'react';
import { useRef, type ReactElement, type Ref } from 'react';
import type { TeacherDefinition } from '../../../shared/coding-teacher';
import { TeacherAvatar } from './TeacherAvatar';
@@ -13,11 +13,23 @@ export function TeacherIntroduction({ definition, children, contentRef, open, on
onOpenChange(open: boolean): void;
}) {
const description = definition?.description?.trim();
return <Tooltip.Root open={Boolean(description) && open} onOpenChange={onOpenChange}>
const clicked = useRef(false);
return <Tooltip.Root open={Boolean(description) && open} onOpenChange={(next) => {
if (!next || !clicked.current) onOpenChange(next);
}}>
<Tooltip.Trigger asChild onPointerEnter={(event) => {
// Adjacent entries must switch immediately, even inside the previous
// tooltip's pointer grace area used when moving into its readable card.
if (event.pointerType !== 'touch') onOpenChange(true);
if (event.pointerType === 'touch') return;
if (event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) return;
clicked.current = false;
onOpenChange(true);
}} onClick={() => {
// A delayed Radix hover callback must not reopen the card after selection.
clicked.current = true;
onOpenChange(false);
}} onFocus={() => {
clicked.current = false;
}} onPointerMove={(event) => {
// pointerEnter owns hover opening. Skip Radix's second opening path so
// moving inside an entry after clicking it cannot reopen its introduction.
+5 -2
View File
@@ -73,7 +73,7 @@
/* The teacher speaks from the title bar without taking the student's focus. */
.classroom-composer-view[hidden] { display: none; }
.teacher-companion { position: relative; min-width: 0; max-width: 65%; }
.teacher-companion { position: relative; display: flex; align-items: center; gap: 4px; min-width: 0; max-width: 65%; }
.teacher-introduction { z-index: 200; width: min(304px, calc(100vw - 24px)); max-height: var(--radix-tooltip-content-available-height); padding: 18px; border: 2px solid #ead6af; border-radius: 22px; background: #fff9ed; color: #30465f; box-shadow: 0 5px 0 #ecdcc1, 0 12px 30px #354d6c18; transform-origin: var(--radix-tooltip-content-transform-origin); animation: teacher-introduction-in 150ms ease-out; }
.teacher-introduction-heading { display: flex; align-items: center; gap: 11px; }
.teacher-introduction-avatar { width: 48px; height: 48px; flex-shrink: 0; border: 2px solid #fff; border-radius: 15px; background: #e8f1fb; box-shadow: 0 3px 0 #d6e3ee; }
@@ -85,7 +85,10 @@
.teacher-introduction-arrow { fill: #ead6af; }
@keyframes teacher-introduction-in { from { opacity: 0; } to { opacity: 1; } }
@media (prefers-reduced-motion: reduce) { .teacher-introduction { animation: none; } }
.consultation-agent-tabs { display: flex; align-items: center; gap: 4px; max-width: 100%; overflow-x: auto; scrollbar-width: thin; }
.consultation-agent-tabs { display: flex; align-items: center; gap: 4px; min-width: 0; max-width: 100%; overflow-x: auto; scrollbar-width: thin; }
.consultation-agents-refresh { display: flex; align-items: center; justify-content: center; gap: 5px; flex-shrink: 0; width: 76px; height: 32px; border: 1px solid #dce4d5; border-radius: 8px; color: #526348; background: #f7f9f3; font-size: 12px; white-space: nowrap; cursor: pointer; transition: background 150ms; }
.consultation-agents-refresh:hover:not(:disabled) { background: #eaf0e1; }
.consultation-agents-refresh:disabled { cursor: default; opacity: .6; }
.consultation-agent-tabs .teacher-companion-person { flex-shrink: 0; }
.teacher-companion-person { display: flex; align-items: center; gap: 6px; height: 36px; padding: 0 8px; border-radius: 8px; color: #747d6c; transition: background 150ms; }
.teacher-companion-person:hover, .teacher-companion-person[aria-expanded="true"] { background: #eef1e8; color: #42543a; }
+65 -18
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { teacherApi, teacherTopicsPath } from '@/lib/coding-teacher';
import { teacherApi, teacherTopicsPath, type TeacherCatalogState } from '@/lib/coding-teacher';
import { useAuthStore } from '@/stores/auth';
import { AppError } from '@/lib/error-model';
import {
@@ -11,8 +11,12 @@ import {
} from '../../../shared/coding-teacher';
interface CompanionState {
catalogState?: TeacherCatalogState;
refreshing: boolean;
refreshStatus: 'idle' | 'success' | 'error';
agents: TeacherCatalog['items'];
selectedAgent?: TeacherCatalog['items'][number];
// null keeps an already-open, unassigned editor stable when the first Agent arrives.
selectedAgent?: TeacherCatalog['items'][number] | null;
definition: TeacherDefinition | null;
enabled: boolean;
loading: boolean;
@@ -47,7 +51,7 @@ export function useTeacherCompanion(options: Options) {
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
const scope = `${account}:${options.projectId ?? ''}`;
const storageKey = `makelore-teacher-presence:${scope}`;
const [state, setState] = useState<CompanionState>({ agents: [], definition: null, enabled: false, loading: true, topic: null, seen: [], welcomeDismissed: false, error: '' });
const [state, setState] = useState<CompanionState>({ agents: [], definition: null, enabled: false, loading: true, refreshing: false, refreshStatus: 'idle', topic: null, seen: [], welcomeDismissed: false, error: '' });
const selectionEpoch = useRef(0);
const latest = useRef({ options, state });
latest.current = { options, state };
@@ -55,6 +59,32 @@ export function useTeacherCompanion(options: Options) {
scopeRef.current = scope;
const stateScope = useRef(scope);
const inFlight = useRef(false);
const configLoader = useRef<(() => Promise<{ enabled: boolean }>) | null>(null);
const reloadCatalog = useCallback(async () => { await configLoader.current?.(); }, []);
const refreshFlight = useRef<{ load: NonNullable<typeof configLoader.current>; promise: Promise<void> } | null>(null);
const refresh = useCallback((): Promise<void> => {
const load = configLoader.current;
if (!load) return Promise.resolve();
const refreshingScope = scopeRef.current;
const isCurrent = () => configLoader.current === load && scopeRef.current === refreshingScope;
if (refreshFlight.current?.load === load) return refreshFlight.current.promise;
setState((current) => ({ ...current, refreshing: true, refreshStatus: 'idle' }));
const promise = load().then(() => {
if (isCurrent()) setState((current) => ({ ...current, refreshStatus: 'success' }));
}).catch(() => {
if (isCurrent()) setState((current) => ({ ...current, refreshStatus: 'error' }));
}).finally(() => {
if (isCurrent()) setState((current) => ({ ...current, refreshing: false }));
if (refreshFlight.current?.promise === promise) refreshFlight.current = null;
});
refreshFlight.current = { load, promise };
return promise;
}, []);
useEffect(() => {
if (state.refreshStatus !== 'success') return;
const timer = window.setTimeout(() => setState((current) => ({ ...current, refreshStatus: 'idle' })), 3000);
return () => window.clearTimeout(timer);
}, [state.refreshStatus]);
const noteTopic = useCallback((topic: TeacherTopic) => {
if (scopeRef.current !== scope || topic.projectId !== options.projectId) return;
setState((current) => current.topic?.id === topic.id && current.topic.revision >= topic.revision
@@ -64,7 +94,7 @@ export function useTeacherCompanion(options: Options) {
}, [scope, options.projectId]);
const selectAgent = useCallback((id: string) => {
const current = latest.current.state;
if (id === (current.selectedAgent?.teacher_id ?? current.topic?.definition.config_id ?? current.definition?.config_id)) return;
if (id === (current.selectedAgent?.teacher_id ?? current.topic?.definition.config_id)) return;
const agent = current.agents.find((item) => item.teacher_id === id);
if (!agent) return;
selectionEpoch.current++;
@@ -93,24 +123,38 @@ export function useTeacherCompanion(options: Options) {
const welcomeDismissed = readLocal<boolean>(storageKey + ':welcome-dismissed', false) === true;
selectionEpoch.current++;
const initialSelection = selectionEpoch.current;
setState({ agents: [], definition: null, enabled: false, loading: true, topic: null, seen, welcomeDismissed, error: '' });
setState({ agents: [], definition: null, enabled: false, loading: true, refreshing: false, refreshStatus: 'idle', topic: null, seen, welcomeDismissed, error: '' });
const projectId = options.projectId;
if (!projectId) {
setState((current) => ({ ...current, loading: false }));
return () => { alive = false; };
}
const base = teacherTopicsPath(projectId);
const loadConfig = async () => {
const config = await teacherApi.config();
const catalog = await teacherApi.catalog();
const selectedId = latest.current.state.selectedAgent?.teacher_id;
const selected = catalog.items.find((item) => item.teacher_id === selectedId)
?? (!selectedId ? catalog.items.find((item) => item.is_default) ?? catalog.items[0] : undefined);
const enabled = selected ? true : !selectedId && config.enabled;
if (alive) setState((current) => ({ ...current, agents: catalog.items,
definition: selected?.definition ?? current.selectedAgent?.definition ?? current.topic?.definition ?? config.definition, enabled, loading: false }));
return { enabled };
let configFlight: Promise<{ enabled: boolean }> | null = null;
const loadConfig = () => {
if (configFlight) return configFlight;
configFlight = (async () => {
const [config, catalog] = await Promise.all([teacherApi.config(), teacherApi.catalog()]);
if (!alive || scopeRef.current !== scope) return { enabled: false };
const select = (current: CompanionState) => {
const id = current.selectedAgent?.teacher_id ?? current.topic?.definition.config_id;
return catalog.items.find((item) => item.teacher_id === id)
?? (!id ? catalog.items.find((item) => item.is_default) ?? catalog.items[0] : undefined);
};
const isEnabled = (current: CompanionState) => Boolean(select(current))
|| (!current.selectedAgent && !current.topic?.definition.config_id && config.enabled);
const enabled = isEnabled(latest.current.state);
setState((current) => ({ ...current, catalogState: { config, catalog }, agents: catalog.items,
selectedAgent: current.selectedAgent ? select(current) ?? current.selectedAgent
: (!current.agents.length && !current.topic?.definition.config_id && latest.current.options.teacherOpen)
? null : current.selectedAgent,
definition: select(current)?.definition ?? current.selectedAgent?.definition ?? current.topic?.definition ?? config.definition,
enabled: isEnabled(current), loading: false, error: '' }));
return { enabled };
})().finally(() => { configFlight = null; });
return configFlight;
};
configLoader.current = loadConfig;
void (async () => {
try {
await loadConfig();
@@ -183,6 +227,7 @@ export function useTeacherCompanion(options: Options) {
document.addEventListener('visibilitychange', onVisible);
return () => {
alive = false;
if (configLoader.current === loadConfig) configLoader.current = null;
window.clearInterval(timer);
window.removeEventListener('focus', onVisible);
document.removeEventListener('visibilitychange', onVisible);
@@ -211,12 +256,12 @@ export function useTeacherCompanion(options: Options) {
const last = topic?.requests.at(-1);
const invitation = unreadInvitation({ topic, seen: state.seen });
const visibleState = stateScope.current === scope ? state : { agents: [], selectedAgent: undefined, definition: null, enabled: false, loading: true, topic: null, seen: [], welcomeDismissed: true, error: '' };
const visibleState: CompanionState = stateScope.current === scope ? state : { agents: [], selectedAgent: undefined, definition: null, enabled: false, loading: true, refreshing: false, refreshStatus: 'idle', topic: null, seen: [], welcomeDismissed: true, error: '' };
// This is the published greeting, not a fabricated project assessment.
const selectedDefinition = topic?.definition ?? visibleState.definition;
const selectedAgentId = visibleState.selectedAgent?.teacher_id ?? selectedDefinition?.config_id;
const selectedAgent = visibleState.agents.find((item) => item.teacher_id === selectedAgentId)
?? visibleState.selectedAgent;
const selectedAgent = visibleState.selectedAgent === null ? undefined
: visibleState.agents.find((item) => item.teacher_id === selectedAgentId) ?? visibleState.selectedAgent;
const welcome = topic?.role !== 'friend' && !visibleState.loading && visibleState.enabled && !visibleState.welcomeDismissed
? selectedDefinition?.welcome_message.trim() || null : null;
return {
@@ -224,6 +269,8 @@ export function useTeacherCompanion(options: Options) {
error: last?.intent === 'check-in' && ['failed', 'interrupted'].includes(last.status) ? '智能体这次没连上,可以点头像找智能体聊聊。' : visibleState.error,
definition: selectedDefinition,
selectedAgent,
refresh,
reloadCatalog,
selectAgent,
topic,
invitation,