Files
makelore/src/pages/Chat/use-teacher-companion.ts
T

340 lines
19 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from 'react';
import { teacherApi, teacherTopicsPath, teacherConversationsPath, type TeacherCatalogState } from '@/lib/coding-teacher';
import { useAuthStore } from '@/stores/auth';
import { AppError } from '@/lib/error-model';
import {
TEACHER_CHECK_IN_INTERVAL_MS,
type TeacherCheckInInput,
type TeacherDefinition,
type TeacherCatalog,
type TeacherTopic,
} from '../../../shared/coding-teacher';
interface CompanionState {
catalogState?: TeacherCatalogState;
refreshing: boolean;
refreshStatus: 'idle' | 'success' | 'error';
agents: TeacherCatalog['items'];
// 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;
topic: TeacherTopic | null;
seen: string[];
welcomeDismissed: boolean;
error: string;
}
interface Options {
projectId: string | null;
sourceId: string | null;
sourceBusy: boolean;
sourceArchived: boolean;
teacherOpen: boolean;
teacherComposing?: boolean;
}
// Only presentation receipts/request identities live here. Main owns the conversation.
function readLocal<T>(key: string, fallback: T): T {
try { return JSON.parse(localStorage.getItem(key) ?? 'null') ?? fallback; } catch { return fallback; }
}
function writeLocal(key: string, value: unknown) {
try { localStorage.setItem(key, JSON.stringify(value)); } catch { /* In-memory state remains usable. */ }
}
function unreadInvitation(state: Pick<CompanionState, 'topic' | 'seen'>) {
if (state.topic?.conversation) return null;
return state.topic?.requests.slice().reverse().find((request) => request.intent === 'check-in'
&& request.status === 'completed' && request.response && !state.seen.includes(request.id)) ?? null;
}
export function useTeacherCompanion(options: Options) {
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
const scope = account + ':' + (options.projectId ?? 'no-project');
const storageKey = `makelore-teacher-presence:${scope}`;
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 });
latest.current = { options, state };
const scopeRef = useRef(scope);
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 !== latest.current.options.projectId) return;
const selectedId = latest.current.state.selectedAgent?.teacher_id;
if (selectedId && topic.definition.config_id !== selectedId) return;
if (topic.conversation) {
const agentId = topic.conversation.agentId;
const last = topic.requests.at(-1);
const unread = last && !['preparing', 'running'].includes(last.status) && topic.conversation.seenThrough !== last.id;
setUnreadAgentIds(ids => [...ids.filter(id => id !== agentId), ...(unread ? [agentId] : [])]);
}
setState((current) => current.topic?.id === topic.id && current.topic.revision >= topic.revision
? current
: { ...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]);
const selectAgent = useCallback((id: string) => {
const current = latest.current.state;
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++;
writeLocal(storageKey + ':selected-agent', id);
setState((value) => ({ ...value, selectedAgent: agent, definition: agent.definition, topic: null,
enabled: true, welcomeDismissed: true, error: '' }));
}, [storageKey]);
const dismiss = useCallback(() => {
const request = unreadInvitation(latest.current.state);
writeLocal(storageKey + ':welcome-dismissed', true);
setState((current) => {
const through = request ? current.topic?.requests.findIndex((item) => item.id === request.id) ?? -1 : -1;
const acknowledged = current.topic?.requests.slice(0, through + 1)
.filter((item) => item.intent === 'check-in' && item.status === 'completed').map((item) => item.id) ?? [];
const seen = [...new Set([...current.seen, ...acknowledged])].slice(-100);
writeLocal(storageKey + ':seen', seen);
return { ...current, seen, welcomeDismissed: true };
});
}, [storageKey]);
useEffect(() => {
let alive = true;
const preserveChat = stateScope.current === scope && Boolean(latest.current.state.selectedAgent);
stateScope.current = scope;
inFlight.current = false;
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;
if (!preserveChat) { selectionEpoch.current++; setUnreadAgentIds([]); }
const initialSelection = selectionEpoch.current;
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) : '';
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.loading && !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();
if (!alive) return;
const agentId = loaded.selected?.teacher_id ?? loaded.selectedId;
if (agentId && projectId) {
const view = await teacherApi.conversation(projectId, agentId);
if (alive && view.topic && initialSelection === selectionEpoch.current) noteTopic(view.topic);
return;
}
if (!projectId) return;
const topics = await teacherApi.list(base);
if (!alive || !topics.lastSelectedTopicId) return;
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: '智能体暂时没连上,稍后再来看看。' }));
}
})();
// Keep the deadline across Renderer reloads/project switches, but allow a
// newly visited project its full interval before the first paid request.
const storedAttempt = readLocal<unknown>(storageKey + ':last-attempt', null);
let lastAttempt = typeof storedAttempt === 'number' && Number.isFinite(storedAttempt)
&& storedAttempt >= 0 && storedAttempt <= Date.now() ? storedAttempt : Date.now();
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 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;
try {
const refreshed = currentState.topic.conversation
? (await teacherApi.conversation(currentState.topic.projectId, currentState.topic.conversation.agentId)).topic
: await teacherApi.read(base, currentState.topic.id, false);
if (alive && refreshed && latest.current.state.topic?.id === currentState.topic.id) noteTopic(refreshed);
} catch { /* The next visible tick retries this read without dispatching a model. */ }
finally { if (alive) inFlight.current = false; }
return;
}
// Delivered agents own one chat per project. Project observations
// have their own Main scheduler; this legacy timer must not create topics.
if (currentState.selectedAgent || currentState.agents.length) {
try { await loadConfig(); } catch { /* Keep last known delivered contacts. */ }
return;
}
if (!projectId || current.sourceBusy || current.sourceArchived || !current.sourceId || (current.teacherOpen && current.teacherComposing)) return;
if (Date.now() - lastAttempt < TEACHER_CHECK_IN_INTERVAL_MS) return;
if (unreadInvitation(currentState)) return;
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;
if (!alive || !config.enabled || document.visibilityState !== 'visible' || dispatch.sourceBusy || dispatch.sourceArchived || !dispatch.sourceId || (dispatch.teacherOpen && dispatch.teacherComposing)) return;
const saved = readLocal<TeacherCheckInInput | null>(storageKey + ':pending', null);
const input = saved?.requestId && saved.sourceConversationId === dispatch.sourceId
? saved
: { requestId: crypto.randomUUID(), sourceConversationId: dispatch.sourceId };
writeLocal(storageKey + ':pending', input);
const result = await teacherApi.checkIn(projectId, input);
if (!alive) return;
if (result.skipped === 'busy') {
lastAttempt = Date.now() - TEACHER_CHECK_IN_INTERVAL_MS;
writeLocal(storageKey + ':last-attempt', lastAttempt);
}
writeLocal(storageKey + ':pending', null);
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);
setState((value) => ({ ...value, error: '智能体这次没连上,可以点头像找智能体聊聊。' }));
} finally {
if (alive) inFlight.current = false;
}
};
const timer = window.setInterval(() => { void check(); }, 15_000);
const onVisible = () => { void check(); };
window.addEventListener('focus', onVisible);
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);
};
}, [account, scope, storageKey, noteTopic, options.projectId]);
useEffect(() => {
let alive = true;
const projectId = options.projectId;
if (!projectId) return;
const refresh = async () => {
if (document.visibilityState === 'hidden') return;
const views = await Promise.allSettled(state.agents.map(async agent => ({
id: agent.teacher_id, view: await teacherApi.conversation(projectId, agent.teacher_id),
})));
if (!alive) return;
setUnreadAgentIds(views.flatMap(result => {
if (result.status !== 'fulfilled') return [];
const { id, view } = result.value;
const last = view.topic?.requests.at(-1);
return view.topic?.projectId === projectId && last && !['preparing', 'running'].includes(last.status)
&& view.topic?.conversation?.seenThrough !== last.id ? [id] : [];
}));
};
void refresh();
const timer = window.setInterval(() => void refresh(), 15_000);
window.addEventListener('focus', refresh);
return () => { alive = false; window.clearInterval(timer); window.removeEventListener('focus', refresh); };
}, [account, options.projectId, state.agents]);
const topic = stateScope.current === scope ? state.topic : null;
const topicId = topic?.id;
const topicProjectId = topic?.projectId;
const conversationAgentId = topic?.conversation?.agentId;
useEffect(() => {
if (!topicId || !topicProjectId || topic?.role === 'friend') return;
let alive = true;
let stream: EventSource | undefined;
const streamSelection = selectionEpoch.current;
const base = conversationAgentId ? teacherConversationsPath(topicProjectId) : teacherTopicsPath(topicProjectId);
void teacherApi.events(base, conversationAgentId ?? topicId).then((source) => {
if (!alive) { source.close(); return; }
stream = source;
source.addEventListener('snapshot', (event) => {
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. */ });
return () => { alive = false; stream?.close(); };
}, [topicId, topicProjectId, topic?.role, conversationAgentId, noteTopic]);
const last = topic?.requests.at(-1);
const invitation = unreadInvitation({ topic, seen: state.seen });
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.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 {
unreadAgentIds: stateScope.current === scope ? unreadAgentIds : [],
...visibleState,
error: last?.intent === 'check-in' && ['failed', 'interrupted'].includes(last.status) ? '智能体这次没连上,可以点头像找智能体聊聊。' : visibleState.error,
definition: selectedDefinition,
selectedAgent,
refresh,
reloadCatalog,
selectAgent,
topic,
invitation,
welcome,
bubbleVisible: Boolean(invitation || welcome),
checking: last?.intent === 'check-in' && ['preparing', 'running'].includes(last.status),
dismiss,
noteTopic,
};
}