feat: 在顶栏并排展示下发智能体并直接切换

This commit is contained in:
brother7 committed 2026-09-24 15:38:50 +08:00
1 parent 39b03a1628
commit a10cf00015
15 files changed
+291 -59

No files matched your search

+41 -10
View File
@@ -6,10 +6,13 @@ import {
TEACHER_CHECK_IN_INTERVAL_MS,
type TeacherCheckInInput,
type TeacherDefinition,
type TeacherCatalog,
type TeacherTopic,
} from '../../../shared/coding-teacher';
interface CompanionState {
agents: TeacherCatalog['items'];
selectedAgent?: TeacherCatalog['items'][number];
definition: TeacherDefinition | null;
enabled: boolean;
loading: boolean;
@@ -44,7 +47,8 @@ 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>({ definition: null, enabled: false, loading: true, topic: null, seen: [], welcomeDismissed: false, error: '' });
const [state, setState] = useState<CompanionState>({ agents: [], definition: null, enabled: false, loading: true, topic: null, seen: [], welcomeDismissed: false, error: '' });
const selectionEpoch = useRef(0);
const latest = useRef({ options, state });
latest.current = { options, state };
const scopeRef = useRef(scope);
@@ -55,8 +59,18 @@ export function useTeacherCompanion(options: Options) {
if (scopeRef.current !== scope || topic.projectId !== options.projectId) return;
setState((current) => current.topic?.id === topic.id && current.topic.revision >= topic.revision
? current
: { ...current, topic, error: '' });
: { ...current, topic, selectedAgent: current.agents.find((item) => item.teacher_id === topic.definition.config_id)
?? (topic.definition.config_id ? { teacher_id: topic.definition.config_id, version: topic.version, definition: topic.definition, is_default: false } : undefined), error: '' });
}, [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;
const agent = current.agents.find((item) => item.teacher_id === id);
if (!agent) return;
selectionEpoch.current++;
setState((value) => ({ ...value, selectedAgent: agent, definition: agent.definition, topic: null,
enabled: true, welcomeDismissed: true, error: '' }));
}, []);
const dismiss = useCallback(() => {
const request = unreadInvitation(latest.current.state);
writeLocal(storageKey + ':welcome-dismissed', true);
@@ -77,7 +91,9 @@ export function useTeacherCompanion(options: Options) {
const storedSeen = readLocal<unknown>(storageKey + ':seen', []);
const seen = Array.isArray(storedSeen) ? storedSeen.filter((id): id is string => typeof id === 'string') : [];
const welcomeDismissed = readLocal<boolean>(storageKey + ':welcome-dismissed', false) === true;
setState({ definition: null, enabled: false, loading: true, topic: null, seen, welcomeDismissed, error: '' });
selectionEpoch.current++;
const initialSelection = selectionEpoch.current;
setState({ agents: [], definition: null, enabled: false, loading: true, topic: null, seen, welcomeDismissed, error: '' });
const projectId = options.projectId;
if (!projectId) {
setState((current) => ({ ...current, loading: false }));
@@ -86,8 +102,14 @@ export function useTeacherCompanion(options: Options) {
const base = teacherTopicsPath(projectId);
const loadConfig = async () => {
const config = await teacherApi.config();
if (alive) setState((current) => ({ ...current, definition: config.definition, enabled: config.enabled, loading: false }));
return 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 };
};
void (async () => {
try {
@@ -95,8 +117,8 @@ export function useTeacherCompanion(options: Options) {
if (!alive) return;
const topics = await teacherApi.list(base);
if (!alive || !topics.lastSelectedTopicId) return;
const topic = await teacherApi.read(base, topics.lastSelectedTopicId);
if (alive && (!latest.current.state.topic || latest.current.state.topic.id === topic.id)) noteTopic(topic);
const topic = await teacherApi.read(base, topics.lastSelectedTopicId, false);
if (alive && initialSelection === selectionEpoch.current && (!latest.current.state.topic || latest.current.state.topic.id === topic.id)) noteTopic(topic);
} catch {
if (alive) setState((current) => ({ ...current, loading: false, error: '智能体暂时没连上,稍后再来看看。' }));
}
@@ -111,6 +133,8 @@ export function useTeacherCompanion(options: Options) {
const { options: current, state: currentState } = latest.current;
if (currentState.topic?.role === 'friend') return;
if (!alive || inFlight.current || document.visibilityState !== 'visible' || currentState.loading) return;
// A newly selected agent has no Main selection until its history loads or the student sends.
if (currentState.selectedAgent && !currentState.topic) 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))) {
inFlight.current = true;
@@ -127,6 +151,7 @@ export function useTeacherCompanion(options: Options) {
lastAttempt = Date.now();
writeLocal(storageKey + ':last-attempt', lastAttempt);
inFlight.current = true;
const checkingSelection = selectionEpoch.current;
try {
const config = await loadConfig();
const dispatch = latest.current.options;
@@ -143,7 +168,7 @@ export function useTeacherCompanion(options: Options) {
writeLocal(storageKey + ':last-attempt', lastAttempt);
}
writeLocal(storageKey + ':pending', null);
if (result.topic) noteTopic(result.topic);
if (result.topic && checkingSelection === selectionEpoch.current) noteTopic(result.topic);
} 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);
@@ -171,12 +196,13 @@ export function useTeacherCompanion(options: Options) {
if (!topicId || !topicProjectId || topic?.role === 'friend') return;
let alive = true;
let stream: EventSource | undefined;
const streamSelection = selectionEpoch.current;
const base = teacherTopicsPath(topicProjectId);
void teacherApi.events(base, topicId).then((source) => {
if (!alive) { source.close(); return; }
stream = source;
source.addEventListener('snapshot', (event) => {
if (!alive) return;
if (!alive || streamSelection !== selectionEpoch.current) return;
try { noteTopic(JSON.parse((event as MessageEvent).data) as TeacherTopic); } catch { /* Wait for the next authoritative snapshot. */ }
});
}).catch(() => { /* The consultation can still be opened and reloaded. */ });
@@ -185,15 +211,20 @@ export function useTeacherCompanion(options: Options) {
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: '' };
const visibleState = stateScope.current === scope ? state : { agents: [], selectedAgent: undefined, definition: null, enabled: false, loading: true, 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 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: selectedDefinition,
selectedAgent,
selectAgent,
topic,
invitation,
welcome,