feat: integrate pixel teacher presence and resilient classroom preview
This commit is contained in:
1 parent
12d800ec51
commit
7951cca700
60 files changed
+3313
-180
No files matched your search
@@ -0,0 +1,203 @@
|
||||
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 TeacherTopic,
|
||||
} from '../../../shared/coding-teacher';
|
||||
|
||||
interface CompanionState {
|
||||
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'>) {
|
||||
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<CompanionState>({ definition: null, enabled: false, loading: true, topic: null, seen: [], welcomeDismissed: false, error: '' });
|
||||
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, error: '' });
|
||||
}, [scope, options.projectId]);
|
||||
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<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: '' });
|
||||
const projectId = options.projectId;
|
||||
if (!projectId) {
|
||||
setState((current) => ({ ...current, loading: false }));
|
||||
return () => { alive = false; };
|
||||
}
|
||||
const base = teacherTopicsPath(projectId, '', 'teacher');
|
||||
const loadConfig = async () => {
|
||||
const config = await teacherApi.config('teacher');
|
||||
if (alive) setState((current) => ({ ...current, definition: config.definition, enabled: config.enabled, loading: false }));
|
||||
return config;
|
||||
};
|
||||
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);
|
||||
if (alive && (!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 (!alive || inFlight.current || document.visibilityState !== 'visible' || currentState.loading) 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;
|
||||
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) 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) return;
|
||||
let alive = true;
|
||||
let stream: EventSource | undefined;
|
||||
const base = teacherTopicsPath(topicProjectId, '', 'teacher');
|
||||
void teacherApi.events(base, topicId).then((source) => {
|
||||
if (!alive) { source.close(); return; }
|
||||
stream = source;
|
||||
source.addEventListener('snapshot', (event) => {
|
||||
if (!alive) 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, noteTopic]);
|
||||
|
||||
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: '' };
|
||||
// This is the published greeting, not a fabricated project assessment.
|
||||
const welcome = !visibleState.loading && visibleState.enabled && !visibleState.welcomeDismissed
|
||||
? visibleState.definition?.welcome_message.trim() || null : null;
|
||||
return {
|
||||
...visibleState,
|
||||
error: last?.intent === 'check-in' && ['failed', 'interrupted'].includes(last.status) ? '老师这次没连上,可以点头像找老师聊聊。' : visibleState.error,
|
||||
definition: topic?.definition ?? visibleState.definition,
|
||||
topic,
|
||||
invitation,
|
||||
welcome,
|
||||
bubbleVisible: Boolean(invitation || welcome),
|
||||
checking: last?.intent === 'check-in' && ['preparing', 'running'].includes(last.status),
|
||||
dismiss,
|
||||
noteTopic,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user