feat(coding): keep one ongoing conversation per delivered agent

This commit is contained in:
brother7 committed 2026-09-28 14:19:02 +08:00
1 parent e54f3d234d
commit 7aa81da616
23 files changed
+1205 -160

No files matched your search

+71 -23
View File
@@ -39,15 +39,17 @@ function writeLocal(key: string, value: unknown) {
}
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 ?? ''}`;
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 [unreadAgentIds, setUnreadAgentIds] = useState<string[]>([]);
const selectionEpoch = useRef(0);
const latest = useRef({ options, state });
latest.current = { options, state };
@@ -56,21 +58,30 @@ export function useTeacherCompanion(options: Options) {
const stateScope = useRef(scope);
const inFlight = useRef(false);
const noteTopic = useCallback((topic: TeacherTopic) => {
if (scopeRef.current !== scope || topic.projectId !== options.projectId) return;
if (scopeRef.current !== scope || (!topic.conversation && 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, options.projectId]);
}, [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;
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);
@@ -86,35 +97,40 @@ export function useTeacherCompanion(options: Options) {
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;
selectionEpoch.current++;
if (!preserveChat) selectionEpoch.current++;
const initialSelection = selectionEpoch.current;
setState({ agents: [], definition: null, enabled: false, loading: true, topic: null, seen, welcomeDismissed, error: '' });
if (!preserveChat) 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 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;
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 };
return { enabled, selected, selectedId };
};
void (async () => {
try {
await loadConfig();
const loaded = await loadConfig();
if (!alive) return;
const agentId = loaded.selected?.teacher_id ?? loaded.selectedId;
if (agentId) {
const view = await teacherApi.conversation(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);
@@ -139,13 +155,21 @@ export function useTeacherCompanion(options: Options) {
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);
const refreshed = currentState.topic.conversation
? (await teacherApi.conversation(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;
}
if (current.sourceBusy || current.sourceArchived || !current.sourceId || (current.teacherOpen && current.teacherComposing)) return;
// Delivered agents now own one account-wide chat. 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();
@@ -187,18 +211,41 @@ export function useTeacherCompanion(options: Options) {
window.removeEventListener('focus', onVisible);
document.removeEventListener('visibilitychange', onVisible);
};
}, [account, options.projectId, scope, storageKey, noteTopic]);
}, [account, scope, storageKey, noteTopic, options.projectId]);
useEffect(() => {
let alive = true;
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(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 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, 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;
if (!topicId || (!topicProjectId && !conversationAgentId) || 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) => {
const base = conversationAgentId ? '/api/coding/agent-conversations' : teacherTopicsPath(topicProjectId!);
void teacherApi.events(base, conversationAgentId ?? topicId).then((source) => {
if (!alive) { source.close(); return; }
stream = source;
source.addEventListener('snapshot', (event) => {
@@ -207,19 +254,20 @@ export function useTeacherCompanion(options: Options) {
});
}).catch(() => { /* The consultation can still be opened and reloaded. */ });
return () => { alive = false; stream?.close(); };
}, [topicId, topicProjectId, topic?.role, noteTopic]);
}, [topicId, topicProjectId, topic?.role, conversationAgentId, 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 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 welcome = topic?.role !== 'friend' && !visibleState.loading && visibleState.enabled && !visibleState.welcomeDismissed
? selectedDefinition?.welcome_message.trim() || null : null;
return {
unreadAgentIds,
...visibleState,
error: last?.intent === 'check-in' && ['failed', 'interrupted'].includes(last.status) ? '智能体这次没连上,可以点头像找智能体聊聊。' : visibleState.error,
definition: selectedDefinition,