feat(chat): add manual refresh for delivered agents

This commit is contained in:
鲨鱼辣椒 committed 2026-09-28 13:06:38 +08:00
1 parent 862477f9d4
commit 2b1943dd0f
13 files changed
+517 -59

No files matched your search

+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,