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
@@ -20,6 +20,9 @@ export function teacherTopicsPath(projectId: string) {
|
||||
? '/api/coding/teacher-preview/topics'
|
||||
: `/api/coding/projects/${encodeURIComponent(projectId)}/agent-topics`;
|
||||
}
|
||||
export function teacherConversationsPath(projectId: string) {
|
||||
return `/api/coding/projects/${encodeURIComponent(projectId)}/agent-conversations`;
|
||||
}
|
||||
/** Read old locally-generated friend histories without copying or rebinding them. */
|
||||
export function legacyTopicBase(base: string, legacyFriend: boolean) {
|
||||
return legacyFriend ? base.replace(/agent-topics$/, 'friend-topics') : base;
|
||||
@@ -28,12 +31,12 @@ export const teacherApi = {
|
||||
legacyHistory: (projectId: string) => hostApiFetch<TeacherTopicList>(`/api/coding/projects/${encodeURIComponent(projectId)}/agent-history`),
|
||||
legacyRead: (projectId: string, item: TeacherTopicList['items'][number]) => hostApiFetch<TeacherTopic>(
|
||||
`/api/coding/projects/${encodeURIComponent(projectId)}/agent-history/${encodeURIComponent(item.id)}?source=${encodeURIComponent(item.legacySourceId ?? 'project')}&friend=${item.legacyRole === 'friend'}`),
|
||||
seenConversation: (agentId: string, requestId: string) => hostApiFetch<TeacherTopic>(
|
||||
'/api/coding/agent-conversations/' + encodeURIComponent(agentId) + '/seen', { method: 'POST', body: JSON.stringify({ requestId }) }),
|
||||
conversation: (agentId: string, before?: string) => hostApiFetch<TeacherConversationView>(
|
||||
'/api/coding/agent-conversations/' + encodeURIComponent(agentId) + (before ? '?before=' + encodeURIComponent(before) : '')),
|
||||
sendConversation: (agentId: string, input: TeacherSend) => hostApiFetch<TeacherTopic>(
|
||||
'/api/coding/agent-conversations/' + encodeURIComponent(agentId) + '/messages', { method: 'POST', body: JSON.stringify(input) }),
|
||||
seenConversation: (projectId: string, agentId: string, requestId: string) => hostApiFetch<TeacherTopic>(
|
||||
teacherConversationsPath(projectId) + '/' + encodeURIComponent(agentId) + '/seen', { method: 'POST', body: JSON.stringify({ requestId }) }),
|
||||
conversation: (projectId: string, agentId: string, before?: string) => hostApiFetch<TeacherConversationView>(
|
||||
teacherConversationsPath(projectId) + '/' + encodeURIComponent(agentId) + (before ? '?before=' + encodeURIComponent(before) : '')),
|
||||
sendConversation: (projectId: string, agentId: string, input: TeacherSend) => hostApiFetch<TeacherTopic>(
|
||||
teacherConversationsPath(projectId) + '/' + encodeURIComponent(agentId) + '/messages', { method: 'POST', body: JSON.stringify(input) }),
|
||||
catalog: () => hostApiFetch<TeacherCatalog>('/api/coding/teacher/teachers'),
|
||||
checkIn: (projectId: string, input: TeacherCheckInInput) =>
|
||||
hostApiFetch<TeacherCheckInResult>(`/api/coding/projects/${encodeURIComponent(projectId)}/teacher-check-in`, {
|
||||
|
||||
@@ -969,7 +969,7 @@ export function CodingChatPanel({
|
||||
onPointerMove={(event) => { if (event.currentTarget.hasPointerCapture(event.pointerId)) setConsultationWidth(Math.max(320, Math.min(640, window.innerWidth - event.clientX))); }}
|
||||
onPointerUp={(event) => { if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); }}
|
||||
onKeyDown={(event) => { if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { event.preventDefault(); setConsultationWidth((width) => Math.max(320, Math.min(640, width + (event.key === 'ArrowLeft' ? 20 : -20)))); } }} />
|
||||
<TeacherChatPanel key={`${account}:${teacherCompanion.selectedAgent?.teacher_id ?? activeProject.id}`}
|
||||
<TeacherChatPanel key={`${account}:${activeProject.id}:${teacherCompanion.selectedAgent?.teacher_id ?? 'legacy'}`}
|
||||
projectId={activeProject.id} projectName={activeProject.name} sourceId={targetConversationId ?? ''}
|
||||
selectedAgent={teacherCompanion.selectedAgent}
|
||||
catalogState={teacherCompanion.catalogState}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ArrowUp, ChevronDown, ChevronRight, Loader2 } from 'lucide-react';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { teacherApi, teacherTopicsPath, legacyTopicBase, type TeacherCatalogState } from '@/lib/coding-teacher';
|
||||
import { teacherApi, teacherTopicsPath, teacherConversationsPath, legacyTopicBase, type TeacherCatalogState } from '@/lib/coding-teacher';
|
||||
import type {
|
||||
TeacherDefinition,
|
||||
TeacherCatalog,
|
||||
@@ -21,7 +21,12 @@ const conversationViews = new Map<string, { topic: TeacherTopic | null; before:
|
||||
const messageOrderKey = (request: TeacherTopic['requests'][number]) => request.origin
|
||||
? [request.origin.projectId, request.origin.topicId, request.origin.requestId].join(':') : request.id;
|
||||
|
||||
export function TeacherChatPanel({
|
||||
export function TeacherChatPanel(props: Parameters<typeof ProjectTeacherChatPanel>[0]) {
|
||||
const account = useAuthStore(state => state.user?.userId ?? state.user?.username ?? 'signed-out');
|
||||
return <ProjectTeacherChatPanel key={`${account}:${props.projectId}:${props.selectedAgent?.teacher_id ?? 'legacy'}:${props.draftRevision ?? ''}`} {...props} />;
|
||||
}
|
||||
|
||||
function ProjectTeacherChatPanel({
|
||||
projectId,
|
||||
projectName,
|
||||
sourceId,
|
||||
@@ -51,15 +56,21 @@ export function TeacherChatPanel({
|
||||
reloadCatalog?(): Promise<void>;
|
||||
}) {
|
||||
const continuous = Boolean(selectedAgent && !draftRevision);
|
||||
const base = continuous ? '/api/coding/agent-conversations' : teacherTopicsPath(projectId);
|
||||
const base = continuous ? teacherConversationsPath(projectId) : teacherTopicsPath(projectId);
|
||||
const account = useAuthStore((state) => state.user?.userId ?? state.user?.username ?? 'signed-out');
|
||||
const projectDraftKey = `makelore-consultation-draft:${account}:${projectId}:teacher`;
|
||||
const draftKey = !draftRevision ? selectedAgent ? `makelore-consultation-draft:${account}:agent:${selectedAgent.teacher_id}` : projectDraftKey : null;
|
||||
const draftKey = !draftRevision ? selectedAgent ? `makelore-consultation-draft:${account}:project:${projectId}:agent:${selectedAgent.teacher_id}` : projectDraftKey : null;
|
||||
const [cachedView] = useState(() => continuous && draftKey ? conversationViews.get(draftKey) : undefined);
|
||||
const [saved] = useState<{ text?: string; references?: TeacherReference[]; pending?: TeacherSend; projectId?: string; sourceId?: string }>(() => {
|
||||
try {
|
||||
const legacyKey = selectedAgent ? `makelore-consultation-draft:${account}:${projectId}:agent:${selectedAgent.teacher_id}` : projectDraftKey;
|
||||
return draftKey ? JSON.parse(localStorage.getItem(draftKey) ?? localStorage.getItem(legacyKey) ?? '{}') : {};
|
||||
if (!draftKey) return {};
|
||||
const current = localStorage.getItem(draftKey);
|
||||
if (current) return JSON.parse(current);
|
||||
const legacyKey = selectedAgent ? `makelore-consultation-draft:${account}:agent:${selectedAgent.teacher_id}` : projectDraftKey;
|
||||
const old = JSON.parse(localStorage.getItem(legacyKey) ?? '{}');
|
||||
if ((old.projectId ?? old.pending?.projectId) === projectId) return old;
|
||||
// Pre-single-chat versions already had project drafts; retain them as a fallback.
|
||||
return selectedAgent ? JSON.parse(localStorage.getItem(`makelore-consultation-draft:${account}:${projectId}:agent:${selectedAgent.teacher_id}`) ?? '{}') : {};
|
||||
} catch { return {}; }
|
||||
});
|
||||
const [referenceScope, setReferenceScope] = useState({ projectId: saved.projectId ?? projectId, sourceId: saved.sourceId ?? sourceId });
|
||||
@@ -98,7 +109,7 @@ export function TeacherChatPanel({
|
||||
const [topics, setTopics] = useState<TeacherTopicList>({ items: [], lastSelectedTopicId: null });
|
||||
const [storedTopic, setTopic] = useState<TeacherTopic | null>(cachedView?.topic ?? null);
|
||||
const topic = useMemo(() => storedTopic && continuous ? { ...storedTopic,
|
||||
discussion: storedTopic.projectId === projectId ? storedTopic.discussion : storedTopic.conversation?.discussions[projectId] }
|
||||
discussion: storedTopic.conversation?.discussions[projectId] ?? storedTopic.discussion }
|
||||
: storedTopic, [storedTopic, continuous, projectId]);
|
||||
const legacyFriend = topic?.role === 'friend';
|
||||
const legacyView = Boolean(continuous && topic && !topic.conversation);
|
||||
@@ -165,6 +176,7 @@ export function TeacherChatPanel({
|
||||
}, [topic?.id, topic?.revision, topic?.requests.length]);
|
||||
const consume = useCallback(
|
||||
(next: TeacherTopic) => {
|
||||
if (next.projectId !== projectId) return;
|
||||
if (pending.current && next.requests.some((request) => request.id === pending.current?.requestId)) {
|
||||
pending.current = null;
|
||||
persistDraft(draftRef.current.text, draftRef.current.references);
|
||||
@@ -178,10 +190,10 @@ export function TeacherChatPanel({
|
||||
return { ...(olderSnapshot ? current : next), requests: [...requests.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || messageOrderKey(a).localeCompare(messageOrderKey(b))) };
|
||||
});
|
||||
},
|
||||
[persistDraft, continuous]
|
||||
[persistDraft, continuous, projectId]
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!viewingLegacy.current && externalTopic && (continuous || externalTopic.projectId === projectId)
|
||||
if (!viewingLegacy.current && externalTopic && externalTopic.projectId === projectId
|
||||
&& (!selectedAgentId || externalTopic.definition.config_id === selectedAgentId)) {
|
||||
consume(externalTopic);
|
||||
setDefinition(continuous ? selectedAgentRef.current?.definition ?? externalTopic.definition : externalTopic.definition);
|
||||
@@ -235,7 +247,7 @@ export function TeacherChatPanel({
|
||||
}
|
||||
try {
|
||||
if (continuous && selectedAgentId) {
|
||||
const view = await teacherApi.conversation(selectedAgentId);
|
||||
const view = await teacherApi.conversation(projectId, selectedAgentId);
|
||||
if (alive) { if (view.topic) consume(view.topic); if (!cachedView?.topic) setBefore(view.before); }
|
||||
return;
|
||||
}
|
||||
@@ -245,7 +257,7 @@ export function TeacherChatPanel({
|
||||
const previous = listed.items.find((item) => item.id === listed.lastSelectedTopicId
|
||||
&& (!selectedAgentId || item.teacherId === selectedAgentId))
|
||||
?? (selectedAgentId ? listed.items.find((item) => item.teacherId === selectedAgentId) : undefined);
|
||||
if (externalTopicRef.current && (!selectedAgentId || externalTopicRef.current.definition.config_id === selectedAgentId)) {
|
||||
if (externalTopicRef.current?.projectId === projectId && (!selectedAgentId || externalTopicRef.current.definition.config_id === selectedAgentId)) {
|
||||
consume(externalTopicRef.current);
|
||||
setDefinition(externalTopicRef.current.definition);
|
||||
} else if (previous) {
|
||||
@@ -267,7 +279,7 @@ export function TeacherChatPanel({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
generation.current++;
|
||||
};
|
||||
}, [base, draftRevision, label, consume, selectedAgentId, continuous, cachedView, reloadCatalog]);
|
||||
}, [base, projectId, draftRevision, label, consume, selectedAgentId, continuous, cachedView, reloadCatalog]);
|
||||
const seenPending = useRef<string | undefined>(undefined);
|
||||
const markSeen = useCallback(() => {
|
||||
const current = topicRef.current;
|
||||
@@ -276,9 +288,9 @@ export function TeacherChatPanel({
|
||||
|| document.visibilityState === 'hidden' || ['preparing', 'running'].includes(last.status)
|
||||
|| current.conversation?.seenThrough === last.id || seenPending.current === last.id) return;
|
||||
seenPending.current = last.id;
|
||||
void teacherApi.seenConversation(selectedAgentId, last.id).then(consume).catch(() => undefined)
|
||||
void teacherApi.seenConversation(projectId, selectedAgentId, last.id).then(consume).catch(() => undefined)
|
||||
.finally(() => { seenPending.current = undefined; });
|
||||
}, [continuous, legacyView, selectedAgentId, consume]);
|
||||
}, [continuous, legacyView, projectId, selectedAgentId, consume]);
|
||||
useEffect(() => { markSeen(); }, [topic?.revision, markSeen]);
|
||||
useEffect(() => {
|
||||
if (!topic?.id || legacyFriend || legacyView) return;
|
||||
@@ -318,7 +330,7 @@ export function TeacherChatPanel({
|
||||
const epoch = generation.current;
|
||||
setLoadingOlder(true);
|
||||
try {
|
||||
const page = await teacherApi.conversation(selectedAgentId, before);
|
||||
const page = await teacherApi.conversation(projectId, selectedAgentId, before);
|
||||
if (epoch !== generation.current) return;
|
||||
const pane = scrollRef.current;
|
||||
if (pane) olderAnchor.current = { height: pane.scrollHeight, top: pane.scrollTop };
|
||||
@@ -336,7 +348,7 @@ export function TeacherChatPanel({
|
||||
};
|
||||
const returnToConversation = async () => {
|
||||
if (!selectedAgentId) return;
|
||||
const view = await teacherApi.conversation(selectedAgentId);
|
||||
const view = await teacherApi.conversation(projectId, selectedAgentId);
|
||||
viewingLegacy.current = false;
|
||||
setTopic(view.topic); setBefore(view.before); setDefinition(selectedAgentRef.current?.definition ?? null);
|
||||
setHistoryOpen(false);
|
||||
@@ -436,7 +448,7 @@ export function TeacherChatPanel({
|
||||
};
|
||||
pending.current = input;
|
||||
persistDraft(text, references, input);
|
||||
const next = continuous ? await teacherApi.sendConversation(selectedAgentId!, input)
|
||||
const next = continuous ? await teacherApi.sendConversation(projectId, selectedAgentId!, input)
|
||||
: await teacherApi.send(topicBase, current!.id, input);
|
||||
if (version !== generation.current) return;
|
||||
consume(next);
|
||||
|
||||
@@ -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