import { useCallback, useEffect, useRef, useState } from 'react'; import { teacherApi, teacherTopicsPath } 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 { agents: TeacherCatalog['items']; selectedAgent?: TeacherCatalog['items'][number]; 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(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) { 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 ?? ''}`; const storageKey = `makelore-teacher-presence:${scope}`; const [state, setState] = useState({ 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); scopeRef.current = scope; const stateScope = useRef(scope); const inFlight = useRef(false); 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 ? 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, 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); 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; stateScope.current = scope; inFlight.current = false; const storedSeen = readLocal(storageKey + ':seen', []); const seen = Array.isArray(storedSeen) ? storedSeen.filter((id): id is string => typeof id === 'string') : []; const welcomeDismissed = readLocal(storageKey + ':welcome-dismissed', false) === true; 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 })); 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 }; }; void (async () => { try { await loadConfig(); if (!alive) 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(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 = await teacherApi.read(base, currentState.topic.id, false); if (alive && 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; } if (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(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; window.clearInterval(timer); window.removeEventListener('focus', onVisible); document.removeEventListener('visibilitychange', onVisible); }; }, [account, options.projectId, scope, storageKey, noteTopic]); const topic = stateScope.current === scope ? state.topic : null; const topicId = topic?.id; const topicProjectId = topic?.projectId; useEffect(() => { 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 || 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, noteTopic]); 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: '' }; // 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, bubbleVisible: Boolean(invitation || welcome), checking: last?.intent === 'check-in' && ['preparing', 'running'].includes(last.status), dismiss, noteTopic, }; }