Merge remote main and reconcile agent refresh with ongoing chats
This commit is contained in:
commit
a21a1f077c
24 files changed
+1122
-165
No files matched your search
@@ -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;
|
||||
@@ -48,7 +52,7 @@ export function useTeacherCompanion(options: Options) {
|
||||
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
|
||||
const scope = account;
|
||||
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 [unreadAgentIds, setUnreadAgentIds] = useState<string[]>([]);
|
||||
const selectionEpoch = useRef(0);
|
||||
const latest = useRef({ options, state });
|
||||
@@ -57,6 +61,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.conversation && topic.projectId !== latest.current.options.projectId)) return;
|
||||
const selectedId = latest.current.state.selectedAgent?.teacher_id;
|
||||
@@ -74,7 +104,7 @@ export function useTeacherCompanion(options: Options) {
|
||||
}, [scope]);
|
||||
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++;
|
||||
@@ -105,21 +135,41 @@ export function useTeacherCompanion(options: Options) {
|
||||
const welcomeDismissed = readLocal<boolean>(storageKey + ':welcome-dismissed', false) === true;
|
||||
if (!preserveChat) selectionEpoch.current++;
|
||||
const initialSelection = selectionEpoch.current;
|
||||
if (!preserveChat) setState({ agents: [], definition: null, enabled: false, loading: true, topic: null, seen, welcomeDismissed, error: '' });
|
||||
if (!preserveChat) setState({ agents: [], definition: null, enabled: false, loading: true, refreshing: false, refreshStatus: 'idle', topic: null, seen, welcomeDismissed, error: '' });
|
||||
else setState((current) => ({ ...current, refreshing: false, refreshStatus: 'idle' }));
|
||||
const projectId = options.projectId;
|
||||
const base = projectId ? teacherTopicsPath(projectId) : '';
|
||||
const loadConfig = async () => {
|
||||
const config = await teacherApi.config();
|
||||
const catalog = await teacherApi.catalog();
|
||||
const selectedId = latest.current.state.selectedAgent?.teacher_id ?? readLocal<string | undefined>(storageKey + ':selected-agent', undefined);
|
||||
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,
|
||||
selectedAgent: selected ?? current.selectedAgent,
|
||||
definition: selected?.definition ?? current.selectedAgent?.definition ?? current.topic?.definition ?? config.definition, enabled, loading: false }));
|
||||
return { enabled, selected, selectedId };
|
||||
type LoadedCatalog = { enabled: boolean; selected?: TeacherCatalog['items'][number]; selectedId?: string };
|
||||
let configFlight: Promise<LoadedCatalog> | null = null;
|
||||
const loadConfig = (): Promise<LoadedCatalog> => {
|
||||
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 selection = (current: CompanionState) => {
|
||||
const selectedId = current.selectedAgent?.teacher_id ?? current.topic?.definition.config_id
|
||||
?? readLocal<string | undefined>(storageKey + ':selected-agent', undefined);
|
||||
const selected = catalog.items.find((item) => item.teacher_id === selectedId)
|
||||
?? (!selectedId ? catalog.items.find((item) => item.is_default) ?? catalog.items[0] : undefined);
|
||||
const unassigned = current.selectedAgent === null
|
||||
|| (!current.agents.length && !selectedId && latest.current.options.teacherOpen);
|
||||
return { selectedId, selected, unassigned,
|
||||
enabled: Boolean(selected) || (!selectedId && config.enabled) };
|
||||
};
|
||||
const loaded = selection(latest.current.state);
|
||||
setState((current) => {
|
||||
const next = selection(current);
|
||||
return { ...current, catalogState: { config, catalog }, agents: catalog.items,
|
||||
selectedAgent: next.unassigned ? null : next.selected ?? current.selectedAgent,
|
||||
definition: next.selected?.definition ?? current.selectedAgent?.definition ?? current.topic?.definition ?? config.definition,
|
||||
enabled: next.enabled, loading: false, error: '' };
|
||||
});
|
||||
return { enabled: loaded.enabled, selected: loaded.unassigned ? undefined : loaded.selected,
|
||||
selectedId: loaded.unassigned ? undefined : loaded.selectedId };
|
||||
})().finally(() => { configFlight = null; });
|
||||
return configFlight;
|
||||
};
|
||||
configLoader.current = loadConfig;
|
||||
void (async () => {
|
||||
try {
|
||||
const loaded = await loadConfig();
|
||||
@@ -207,6 +257,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);
|
||||
@@ -258,12 +309,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 = visibleState.selectedAgent?.definition ?? 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 {
|
||||
@@ -272,6 +323,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,
|
||||
|
||||
Reference in new issue
Block a user