fix: isolate delivered agent chats by project
This commit is contained in:
1 parent
a21a1f077c
commit
4b41c23a3a
15 files changed
+518
-165
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { teacherApi, teacherTopicsPath, type TeacherCatalogState } from '@/lib/coding-teacher';
|
||||
import { teacherApi, teacherTopicsPath, teacherConversationsPath, type TeacherCatalogState } from '@/lib/coding-teacher';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { AppError } from '@/lib/error-model';
|
||||
import {
|
||||
@@ -50,7 +50,7 @@ function unreadInvitation(state: Pick<CompanionState, 'topic' | 'seen'>) {
|
||||
|
||||
export function useTeacherCompanion(options: Options) {
|
||||
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
|
||||
const scope = account;
|
||||
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[]>([]);
|
||||
@@ -88,7 +88,7 @@ export function useTeacherCompanion(options: Options) {
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [state.refreshStatus]);
|
||||
const noteTopic = useCallback((topic: TeacherTopic) => {
|
||||
if (scopeRef.current !== scope || (!topic.conversation && topic.projectId !== latest.current.options.projectId)) return;
|
||||
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) {
|
||||
@@ -133,7 +133,7 @@ export function useTeacherCompanion(options: Options) {
|
||||
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++;
|
||||
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' }));
|
||||
@@ -152,7 +152,7 @@ export function useTeacherCompanion(options: Options) {
|
||||
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);
|
||||
|| (!current.loading && !current.agents.length && !selectedId && latest.current.options.teacherOpen);
|
||||
return { selectedId, selected, unassigned,
|
||||
enabled: Boolean(selected) || (!selectedId && config.enabled) };
|
||||
};
|
||||
@@ -175,8 +175,8 @@ export function useTeacherCompanion(options: Options) {
|
||||
const loaded = await loadConfig();
|
||||
if (!alive) return;
|
||||
const agentId = loaded.selected?.teacher_id ?? loaded.selectedId;
|
||||
if (agentId) {
|
||||
const view = await teacherApi.conversation(agentId);
|
||||
if (agentId && projectId) {
|
||||
const view = await teacherApi.conversation(projectId, agentId);
|
||||
if (alive && view.topic && initialSelection === selectionEpoch.current) noteTopic(view.topic);
|
||||
return;
|
||||
}
|
||||
@@ -206,14 +206,14 @@ export function useTeacherCompanion(options: Options) {
|
||||
inFlight.current = true;
|
||||
try {
|
||||
const refreshed = currentState.topic.conversation
|
||||
? (await teacherApi.conversation(currentState.topic.conversation.agentId)).topic
|
||||
? (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 now own one account-wide chat. Project observations
|
||||
// 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. */ }
|
||||
@@ -266,17 +266,19 @@ export function useTeacherCompanion(options: Options) {
|
||||
|
||||
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(agent.teacher_id),
|
||||
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 last && !['preparing', 'running'].includes(last.status)
|
||||
return view.topic?.projectId === projectId && last && !['preparing', 'running'].includes(last.status)
|
||||
&& view.topic?.conversation?.seenThrough !== last.id ? [id] : [];
|
||||
}));
|
||||
};
|
||||
@@ -284,18 +286,18 @@ export function useTeacherCompanion(options: Options) {
|
||||
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]);
|
||||
}, [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 && !conversationAgentId) || topic?.role === 'friend') return;
|
||||
if (!topicId || !topicProjectId || topic?.role === 'friend') return;
|
||||
let alive = true;
|
||||
let stream: EventSource | undefined;
|
||||
const streamSelection = selectionEpoch.current;
|
||||
const base = conversationAgentId ? '/api/coding/agent-conversations' : teacherTopicsPath(topicProjectId!);
|
||||
const base = conversationAgentId ? teacherConversationsPath(topicProjectId) : teacherTopicsPath(topicProjectId);
|
||||
void teacherApi.events(base, conversationAgentId ?? topicId).then((source) => {
|
||||
if (!alive) { source.close(); return; }
|
||||
stream = source;
|
||||
@@ -318,7 +320,7 @@ export function useTeacherCompanion(options: Options) {
|
||||
const welcome = topic?.role !== 'friend' && !visibleState.loading && visibleState.enabled && !visibleState.welcomeDismissed
|
||||
? selectedDefinition?.welcome_message.trim() || null : null;
|
||||
return {
|
||||
unreadAgentIds,
|
||||
unreadAgentIds: stateScope.current === scope ? unreadAgentIds : [],
|
||||
...visibleState,
|
||||
error: last?.intent === 'check-in' && ['failed', 'interrupted'].includes(last.status) ? '智能体这次没连上,可以点头像找智能体聊聊。' : visibleState.error,
|
||||
definition: selectedDefinition,
|
||||
|
||||
Reference in new issue
Block a user