feat(coding): keep one ongoing conversation per delivered agent
This commit is contained in:
1 parent
e54f3d234d
commit
7aa81da616
23 files changed
+1205
-160
No files matched your search
@@ -954,7 +954,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}:${activeProject.id}:${teacherCompanion.selectedAgent?.teacher_id ?? 'history'}`}
|
||||
<TeacherChatPanel key={`${account}:${teacherCompanion.selectedAgent?.teacher_id ?? activeProject.id}`}
|
||||
projectId={activeProject.id} projectName={activeProject.name} sourceId={targetConversationId ?? ''}
|
||||
selectedAgent={teacherCompanion.selectedAgent}
|
||||
externalTopic={teacherCompanion.topic}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ArrowUp, ChevronDown, ChevronRight, Loader2, Maximize2, Plus, X } from 'lucide-react';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { teacherApi, teacherTopicsPath, legacyTopicBase } from '@/lib/coding-teacher';
|
||||
@@ -15,8 +15,15 @@ import type { TeacherDiscussionAction } from '../../../shared/coding-teacher';
|
||||
import { TeacherAvatar } from './TeacherAvatar';
|
||||
import { TeacherReply } from './TeacherReply';
|
||||
|
||||
// Preserve loaded pages and the reading anchor while moving between contacts.
|
||||
// Durable messages remain Main-owned; this is only the current window's view.
|
||||
const conversationViews = new Map<string, { topic: TeacherTopic | null; before: string | null; top: number; follow: boolean }>();
|
||||
const messageOrderKey = (request: TeacherTopic['requests'][number]) => request.origin
|
||||
? [request.origin.projectId, request.origin.topicId, request.origin.requestId].join(':') : request.id;
|
||||
|
||||
export function TeacherChatPanel({
|
||||
projectId,
|
||||
projectName,
|
||||
sourceId,
|
||||
onClose,
|
||||
onBringBack,
|
||||
@@ -45,13 +52,21 @@ export function TeacherChatPanel({
|
||||
onComposingChange?(composing: boolean): void;
|
||||
selectedAgent?: TeacherCatalog['items'][number];
|
||||
}) {
|
||||
const base = teacherTopicsPath(projectId);
|
||||
const continuous = Boolean(selectedAgent && !draftRevision);
|
||||
const base = continuous ? '/api/coding/agent-conversations' : 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}:${projectId}:agent:${selectedAgent.teacher_id}` : projectDraftKey : null;
|
||||
const [saved] = useState<{ text?: string; references?: TeacherReference[]; pending?: TeacherSend }>(() => {
|
||||
try { return draftKey ? JSON.parse(localStorage.getItem(draftKey) ?? '{}') : {}; } catch { return {}; }
|
||||
const draftKey = !draftRevision ? selectedAgent ? `makelore-consultation-draft:${account}: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) ?? '{}') : {};
|
||||
} catch { return {}; }
|
||||
});
|
||||
const [referenceScope, setReferenceScope] = useState({ projectId: saved.projectId ?? projectId, sourceId: saved.sourceId ?? sourceId });
|
||||
const referenceScopeRef = useRef(referenceScope);
|
||||
referenceScopeRef.current = referenceScope;
|
||||
const [legacyDraft] = useState<{ text?: string; references?: TeacherReference[] }>(() => {
|
||||
try { return draftKey ? JSON.parse(localStorage.getItem(`makelore-consultation-draft:${account}:${projectId}:friend`) ?? '{}') : {}; } catch { return {}; }
|
||||
});
|
||||
@@ -60,11 +75,17 @@ export function TeacherChatPanel({
|
||||
});
|
||||
const persistDraft = useCallback((text: string, references: TeacherReference[], pending?: TeacherSend | null) => {
|
||||
if (!draftKey) return;
|
||||
try { localStorage.setItem(draftKey, JSON.stringify({ text, references, pending })); } catch { /* Draft remains in the open panel. */ }
|
||||
try { localStorage.setItem(draftKey, JSON.stringify({ text, references, pending, ...referenceScopeRef.current })); } catch { /* Draft remains in the open panel. */ }
|
||||
}, [draftKey]);
|
||||
const label = '智能体';
|
||||
const discussionEnabled = !draftRevision;
|
||||
const [historyOpen, setHistoryOpen] = useState(false);
|
||||
const [before, setBefore] = useState<string | null>(cachedView?.before ?? null);
|
||||
const [loadingOlder, setLoadingOlder] = useState(false);
|
||||
const olderAnchor = useRef<{ height: number; top: number } | null>(null);
|
||||
const followBottom = useRef(cachedView?.follow ?? true);
|
||||
const restoreTop = useRef(cachedView?.top);
|
||||
const scrollPosition = useRef(cachedView?.top ?? 0);
|
||||
const [focus, setFocus] = useState<{ topicId: string; id: string; label: string } | null>(null);
|
||||
const [definition, setDefinition] = useState<TeacherDefinition | null>(null);
|
||||
const externalTopicRef = useRef(externalTopic);
|
||||
@@ -75,9 +96,15 @@ export function TeacherChatPanel({
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const focusedOnce = useRef(false);
|
||||
const [topics, setTopics] = useState<TeacherTopicList>({ items: [], lastSelectedTopicId: null });
|
||||
const [topic, setTopic] = useState<TeacherTopic | null>(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] }
|
||||
: storedTopic, [storedTopic, continuous, projectId]);
|
||||
const legacyFriend = topic?.role === 'friend';
|
||||
const legacyView = Boolean(continuous && topic && !topic.conversation);
|
||||
const viewingLegacy = useRef(false);
|
||||
const topicBase = legacyTopicBase(base, legacyFriend);
|
||||
const endpointId = continuous ? selectedAgent!.teacher_id : topic?.id ?? '';
|
||||
const [text, setText] = useState(saved.text ?? '');
|
||||
const [references, setReferences] = useState<TeacherReference[]>(quote ? [quote] : saved.references ?? []);
|
||||
useEffect(() => { onComposingChange?.(Boolean(text.trim() || references.length)); }, [text, references.length, onComposingChange]);
|
||||
@@ -90,7 +117,7 @@ export function TeacherChatPanel({
|
||||
const [legacyEnabled, setLegacyEnabled] = useState(false);
|
||||
const [teachers, setTeachers] = useState<TeacherCatalog['items']>([]);
|
||||
const [selectedTeacherVersion, setSelectedTeacherVersion] = useState<number>();
|
||||
const topicEnabled = legacyFriend ? false : !topic ? enabled
|
||||
const topicEnabled = legacyFriend || legacyView ? false : !topic ? enabled
|
||||
: topic.definition.config_id
|
||||
? teachers.some((item) => item.teacher_id === topic.definition.config_id)
|
||||
: legacyEnabled;
|
||||
@@ -102,36 +129,54 @@ export function TeacherChatPanel({
|
||||
const topicRef = useRef(topic);
|
||||
topicRef.current = topic;
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const beforeRef = useRef(before);
|
||||
beforeRef.current = before;
|
||||
useEffect(() => () => {
|
||||
if (continuous && draftKey && !viewingLegacy.current) conversationViews.set(draftKey, { topic: topicRef.current,
|
||||
before: beforeRef.current, top: scrollPosition.current, follow: followBottom.current });
|
||||
}, [continuous, draftKey]);
|
||||
const content = topic?.discussion?.content;
|
||||
const activeFocus = focus && focus.topicId === topic?.id && content && topic?.discussion?.status === 'active' && (
|
||||
content.kind === 'ideas' ? content.items.some(item => item.id === focus.id)
|
||||
: content.kind === 'comparison' ? content.rows.some(row => content.columns.some(column => `${row.id}:${column.id}` === focus.id))
|
||||
: content.nodes.some(node => node.id === focus.id)
|
||||
) ? focus : null;
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
const pane = scrollRef.current;
|
||||
if (pane) pane.scrollTop = pane.scrollHeight;
|
||||
}, [topic?.id, topic?.revision]);
|
||||
if (!pane) return;
|
||||
if (restoreTop.current !== undefined) {
|
||||
pane.scrollTop = restoreTop.current; restoreTop.current = undefined;
|
||||
} else if (olderAnchor.current) {
|
||||
pane.scrollTop = olderAnchor.current.top + pane.scrollHeight - olderAnchor.current.height;
|
||||
olderAnchor.current = null;
|
||||
} else if (followBottom.current) pane.scrollTop = pane.scrollHeight;
|
||||
}, [topic?.id, topic?.revision, topic?.requests.length]);
|
||||
const consume = useCallback(
|
||||
(next: TeacherTopic) => {
|
||||
if (pending.current && next.requests.some((request) => request.id === pending.current?.requestId)) {
|
||||
pending.current = null;
|
||||
persistDraft(draftRef.current.text, draftRef.current.references);
|
||||
}
|
||||
setTopic((current) =>
|
||||
current?.id === next.id && current.revision > next.revision ? current : next
|
||||
);
|
||||
setTopic((current) => {
|
||||
const olderSnapshot = current?.id === next.id && current.revision > next.revision;
|
||||
if (olderSnapshot && !continuous) return current;
|
||||
if (!continuous || current?.id !== next.id) return next;
|
||||
const requests = new Map(current.requests.map(request => [request.id, request]));
|
||||
next.requests.forEach(request => { if (!olderSnapshot || !requests.has(request.id)) requests.set(request.id, request); });
|
||||
return { ...(olderSnapshot ? current : next), requests: [...requests.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || messageOrderKey(a).localeCompare(messageOrderKey(b))) };
|
||||
});
|
||||
},
|
||||
[persistDraft]
|
||||
[persistDraft, continuous]
|
||||
);
|
||||
useEffect(() => {
|
||||
if (externalTopic && externalTopic.projectId === projectId
|
||||
if (!viewingLegacy.current && externalTopic && (continuous || externalTopic.projectId === projectId)
|
||||
&& (!selectedAgentId || externalTopic.definition.config_id === selectedAgentId)) {
|
||||
consume(externalTopic);
|
||||
setDefinition(externalTopic.definition);
|
||||
setDefinition(continuous ? selectedAgentRef.current?.definition ?? externalTopic.definition : externalTopic.definition);
|
||||
}
|
||||
}, [externalTopic, projectId, consume, selectedAgentId]);
|
||||
useEffect(() => { if (topic) onTopicChange?.(topic); }, [topic, onTopicChange]);
|
||||
}, [externalTopic, projectId, consume, selectedAgentId, continuous]);
|
||||
useEffect(() => { if (topic && !legacyView) onTopicChange?.(topic); }, [topic, onTopicChange, legacyView]);
|
||||
useEffect(() => { if (continuous && selectedAgent) setDefinition(selectedAgent.definition); }, [continuous, selectedAgent]);
|
||||
useEffect(() => {
|
||||
if (!busy && !focusedOnce.current) {
|
||||
focusedOnce.current = true;
|
||||
@@ -139,8 +184,8 @@ export function TeacherChatPanel({
|
||||
}
|
||||
}, [busy]);
|
||||
useEffect(() => {
|
||||
if (quote) setReferences([quote]);
|
||||
}, [quote]);
|
||||
if (quote) { setReferences([quote]); setReferenceScope({ projectId, sourceId }); }
|
||||
}, [quote, projectId, sourceId]);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setBusy(true);
|
||||
@@ -171,6 +216,11 @@ export function TeacherChatPanel({
|
||||
if (alive) setError(e instanceof Error ? e.message : `${label}配置暂不可用`);
|
||||
}
|
||||
try {
|
||||
if (continuous && selectedAgentId) {
|
||||
const view = await teacherApi.conversation(selectedAgentId);
|
||||
if (alive) { if (view.topic) consume(view.topic); if (!cachedView?.topic) setBefore(view.before); }
|
||||
return;
|
||||
}
|
||||
const listed = await teacherApi.list(base);
|
||||
if (!alive) return;
|
||||
setTopics(listed);
|
||||
@@ -199,14 +249,26 @@ export function TeacherChatPanel({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
generation.current++;
|
||||
};
|
||||
}, [base, draftRevision, label, consume, selectedAgentId]);
|
||||
}, [base, draftRevision, label, consume, selectedAgentId, continuous, cachedView]);
|
||||
const seenPending = useRef<string | undefined>(undefined);
|
||||
const markSeen = useCallback(() => {
|
||||
const current = topicRef.current;
|
||||
const last = current?.requests.at(-1);
|
||||
if (!continuous || legacyView || !selectedAgentId || !current || !last || !followBottom.current
|
||||
|| 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)
|
||||
.finally(() => { seenPending.current = undefined; });
|
||||
}, [continuous, legacyView, selectedAgentId, consume]);
|
||||
useEffect(() => { markSeen(); }, [topic?.revision, markSeen]);
|
||||
useEffect(() => {
|
||||
if (!topic?.id || legacyFriend) return;
|
||||
if (!topic?.id || legacyFriend || legacyView) return;
|
||||
const streamTopicId = topic.id;
|
||||
let closed = false,
|
||||
stream: EventSource | undefined;
|
||||
void teacherApi
|
||||
.events(topicBase, topic.id)
|
||||
.events(topicBase, endpointId)
|
||||
.then((source) => {
|
||||
if (closed) {
|
||||
source.close();
|
||||
@@ -216,13 +278,7 @@ export function TeacherChatPanel({
|
||||
source.addEventListener('snapshot', (event) => {
|
||||
if (closed) return;
|
||||
const next = JSON.parse((event as MessageEvent).data) as TeacherTopic;
|
||||
setTopic((current) =>
|
||||
current?.id === streamTopicId &&
|
||||
next.id === streamTopicId &&
|
||||
current.revision <= next.revision
|
||||
? next
|
||||
: current
|
||||
);
|
||||
if (next.id === streamTopicId) consume(next);
|
||||
});
|
||||
source.onerror = () => {
|
||||
if (!closed) setError(`连接暂时中断,正在恢复${label}回复。`);
|
||||
@@ -238,14 +294,44 @@ export function TeacherChatPanel({
|
||||
closed = true;
|
||||
stream?.close();
|
||||
};
|
||||
}, [topicBase, topic?.id, legacyFriend, consume, label]);
|
||||
}, [topicBase, topic?.id, endpointId, legacyFriend, legacyView, consume, label]);
|
||||
const loadOlder = async () => {
|
||||
if (!before || loadingOlder || !selectedAgentId) return;
|
||||
const epoch = generation.current;
|
||||
setLoadingOlder(true);
|
||||
try {
|
||||
const page = await teacherApi.conversation(selectedAgentId, before);
|
||||
if (epoch !== generation.current) return;
|
||||
const pane = scrollRef.current;
|
||||
if (pane) olderAnchor.current = { height: pane.scrollHeight, top: pane.scrollTop };
|
||||
followBottom.current = false;
|
||||
if (page.topic) consume(page.topic);
|
||||
setBefore(page.before);
|
||||
} catch (error) { if (epoch === generation.current) setError(error instanceof Error ? error.message : '较早消息加载失败,请重试。'); }
|
||||
finally { if (epoch === generation.current) setLoadingOlder(false); }
|
||||
};
|
||||
const loadLegacy = async () => {
|
||||
setHistoryOpen(value => !value);
|
||||
try {
|
||||
setTopics(await teacherApi.legacyHistory(projectId));
|
||||
} catch { setError('旧记录暂时无法读取。'); }
|
||||
};
|
||||
const returnToConversation = async () => {
|
||||
if (!selectedAgentId) return;
|
||||
const view = await teacherApi.conversation(selectedAgentId);
|
||||
viewingLegacy.current = false;
|
||||
setTopic(view.topic); setBefore(view.before); setDefinition(selectedAgentRef.current?.definition ?? null);
|
||||
setHistoryOpen(false);
|
||||
};
|
||||
const choose = async (id: string) => {
|
||||
const version = ++generation.current;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const next = await teacherApi.read(legacyTopicBase(base, topics.items.some(item => item.id === id && item.legacyRole === 'friend')), id);
|
||||
const next = continuous ? await teacherApi.legacyRead(projectId, topics.items.find(item => item.id === id)!)
|
||||
: await teacherApi.read(legacyTopicBase(base, topics.items.some(item => item.id === id && item.legacyRole === 'friend')), id);
|
||||
if (version === generation.current) {
|
||||
if (continuous) viewingLegacy.current = true;
|
||||
consume(next);
|
||||
setDefinition(next.definition);
|
||||
pending.current = null;
|
||||
@@ -284,12 +370,18 @@ export function TeacherChatPanel({
|
||||
const question = action?.text ?? text;
|
||||
const questionReferences = action ? [] : references;
|
||||
if (!question.trim() || busy || !topicEnabled || topicRef.current?.requests.some((request) => ['preparing', 'running'].includes(request.status))) return;
|
||||
if (continuous && questionReferences.length && (referenceScope.projectId !== projectId || referenceScope.sourceId !== sourceId)) {
|
||||
setError('引用来自另一个项目或操作对话,请切回来源,或移除引用后再提问。'); return;
|
||||
}
|
||||
if (continuous && pending.current?.text === question && pending.current.projectId && pending.current.projectId !== projectId) {
|
||||
setError('上次提问仍绑定原项目,请切回原项目确认结果后重试。'); return;
|
||||
}
|
||||
const version = generation.current;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
let current = topicRef.current;
|
||||
try {
|
||||
if (!current) {
|
||||
if (!current && !continuous) {
|
||||
current = await teacherApi.create(
|
||||
base,
|
||||
draftRevision,
|
||||
@@ -301,15 +393,17 @@ export function TeacherChatPanel({
|
||||
setDefinition(current.definition);
|
||||
}
|
||||
const presentation = discussionEnabled && (!action?.intent || action.intent === 'question' || action.intent === 'guided-help') ? 'discussion-v1' as const : undefined;
|
||||
const discussion = presentation && current.discussion?.status === 'active'
|
||||
const discussion = presentation && current?.discussion?.status === 'active'
|
||||
? action?.discussion ?? { toolId: current.discussion.id, revision: current.discussion.revision,
|
||||
...(activeFocus?.topicId === current.id ? { focusId: activeFocus.id } : {}) } : undefined;
|
||||
const previous = pending.current && !current.requests.some((request) => request.id === pending.current?.requestId)
|
||||
const previous = pending.current && !current?.requests.some((request) => request.id === pending.current?.requestId)
|
||||
? pending.current
|
||||
: null;
|
||||
const input =
|
||||
previous &&
|
||||
previous.text === question &&
|
||||
(!continuous || previous.projectId === projectId) &&
|
||||
previous.sourceConversationId === (sourceId || undefined) &&
|
||||
previous.presentation === presentation &&
|
||||
JSON.stringify(previous.discussion) === JSON.stringify(discussion) &&
|
||||
(previous.intent ?? 'question') === (action?.intent ?? 'question') &&
|
||||
@@ -317,13 +411,15 @@ export function TeacherChatPanel({
|
||||
? previous
|
||||
: {
|
||||
requestId: crypto.randomUUID(), text: question, references: questionReferences,
|
||||
...(continuous ? { projectId } : {}),
|
||||
...(presentation ? { presentation } : {}), ...(discussion ? { discussion } : {}),
|
||||
...(action?.intent ? { intent: action.intent } : {}),
|
||||
...(sourceId ? { sourceConversationId: sourceId } : {}),
|
||||
};
|
||||
pending.current = input;
|
||||
persistDraft(text, references, input);
|
||||
const next = await teacherApi.send(topicBase, current.id, input);
|
||||
const next = continuous ? await teacherApi.sendConversation(selectedAgentId!, input)
|
||||
: await teacherApi.send(topicBase, current!.id, input);
|
||||
if (version !== generation.current) return;
|
||||
consume(next);
|
||||
pending.current = null;
|
||||
@@ -334,7 +430,7 @@ export function TeacherChatPanel({
|
||||
setReferences([]);
|
||||
persistDraft('', []);
|
||||
}
|
||||
setTopics(await teacherApi.list(base));
|
||||
if (!continuous) setTopics(await teacherApi.list(base));
|
||||
} catch (e) {
|
||||
if (version === generation.current)
|
||||
setError(e instanceof Error ? e.message : '提问失败,请保留问题后重试');
|
||||
@@ -353,7 +449,8 @@ export function TeacherChatPanel({
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const next = await teacherApi.updateDiscussion(topicBase, current.id, {
|
||||
const next = await teacherApi.updateDiscussion(topicBase, endpointId, {
|
||||
...(continuous ? { projectId } : {}),
|
||||
toolId: current.discussion.id, revision: current.discussion.revision, action, ...(itemId ? { itemId } : {}),
|
||||
});
|
||||
if (version === generation.current) { consume(next); setFocus(null); }
|
||||
@@ -385,11 +482,21 @@ export function TeacherChatPanel({
|
||||
<TeacherAvatar className="consultation-avatar h-9 w-9 rounded-xl" definition={definition} />
|
||||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{definition?.name ?? '智能体'}</h2>
|
||||
<p className="mt-1 text-[11px] text-muted-foreground">{draftRevision ? '运营草稿试聊' : definition?.description}</p></div>
|
||||
<button aria-label={`${label}新话题`} title="新话题" disabled={busy || !enabled} onClick={() => void newTopic()} className="consult-icon"><Plus className="h-4 w-4" /></button>
|
||||
{!continuous && <button aria-label={`${label}新话题`} title="新话题" disabled={busy || !enabled} onClick={() => void newTopic()} className="consult-icon"><Plus className="h-4 w-4" /></button>}
|
||||
{onExpand && <button className="consult-icon" aria-label={expanded ? '恢复咨询栏宽度' : '展开咨询栏'} onClick={onExpand}><Maximize2 className="h-4 w-4" /></button>}
|
||||
{onClose && <button className="consult-icon" aria-label={`关闭${label}`} onClick={onClose}><X className="h-4 w-4" /></button>}
|
||||
</header>
|
||||
{(topics.items.length > 0 || draftRevision) && <div className="px-5 pt-2">
|
||||
{continuous && <div className="flex items-center justify-between gap-2 px-5 pt-2 text-[11px] text-muted-foreground">
|
||||
<span>本轮项目:{projectName || projectId}{sourceId ? ' · 当前操作对话' : ''}</span>
|
||||
<button type="button" onClick={() => void loadLegacy()}>旧记录</button>
|
||||
</div>}
|
||||
{continuous && historyOpen && <div className="space-y-2 px-5 pt-2 text-xs">
|
||||
<p className="text-muted-foreground">升级前的原始记录保留在这里,仅供查看。</p>
|
||||
{topics.items.map(item => <button className="block" key={item.id} onClick={() => void choose(item.id)}>{item.title}(只读)</button>)}
|
||||
{!topics.items.length && <p>没有待查看的旧记录。</p>}
|
||||
</div>}
|
||||
{legacyView && <button className="px-5 pt-2 text-left text-xs underline" onClick={() => void returnToConversation().catch(() => setError('暂时无法返回聊天。'))}>返回与智能体的聊天</button>}
|
||||
{!continuous && (topics.items.length > 0 || draftRevision) && <div className="px-5 pt-2">
|
||||
<button className="text-[11px] text-muted-foreground" onClick={() => setHistoryOpen(!historyOpen)} aria-expanded={historyOpen}>以往讨论 <ChevronDown className="inline h-3 w-3" /></button>
|
||||
{(historyOpen || draftRevision) && <div className="mt-2 flex gap-2">
|
||||
<select aria-label={`${label}话题`} value={topic?.id ?? ''} disabled={busy} onChange={(e) => void choose(e.target.value)} className="min-w-0 flex-1 rounded-lg border bg-background p-2 text-xs">
|
||||
@@ -404,13 +511,20 @@ export function TeacherChatPanel({
|
||||
focusItem(id, question);
|
||||
void send({ text: question, discussion: { toolId: topic.discussion!.id, revision: topic.discussion!.revision, focusId: id } });
|
||||
}} />}
|
||||
<div ref={scrollRef} className="consultation-messages min-h-0 flex-1 overflow-y-auto px-5 py-6">
|
||||
<div ref={scrollRef} className="consultation-messages min-h-0 flex-1 overflow-y-auto px-5 py-6"
|
||||
onScroll={() => { const pane = scrollRef.current; if (!pane) return;
|
||||
scrollPosition.current = pane.scrollTop;
|
||||
followBottom.current = pane.scrollHeight - pane.scrollTop - pane.clientHeight < 80;
|
||||
markSeen();
|
||||
if (continuous && !legacyView && pane.scrollTop < 40) void loadOlder(); }}>
|
||||
{continuous && !legacyView && before && <button type="button" disabled={loadingOlder} className="mb-4 w-full text-xs text-muted-foreground" onClick={() => void loadOlder()}>{loadingOlder ? '正在加载…' : '查看更早消息'}</button>}
|
||||
{!topic?.requests.length && <div className="flex min-h-full flex-col items-center justify-center pb-5 text-center">
|
||||
<TeacherAvatar className="mb-6 h-[68px] w-[68px] rounded-3xl" definition={definition} />
|
||||
<h3 className="text-lg font-medium tracking-tight">{definition?.welcome_message || '开始对话'}</h3>
|
||||
<div className="mt-6 flex w-full max-w-64 flex-col gap-2">{questions.map((question) => <button key={question} onClick={() => changeText(question)} className="consultation-suggestion flex items-center justify-between gap-2 rounded-lg border bg-white px-3 py-3 text-left text-xs">{question}<ChevronRight className="h-3 w-3 shrink-0 opacity-50" /></button>)}</div>
|
||||
</div>}
|
||||
{topic?.requests.map((request) => <div key={request.id} className="mb-7 space-y-4">
|
||||
{topic?.requests.map((request, index) => <div key={request.id} className="mb-7 space-y-4">
|
||||
{continuous && request.projectId && (index === 0 || request.projectId !== topic.requests[index - 1].projectId) && <p className="text-center text-[10px] text-muted-foreground">{request.projectName || '之前的项目'}</p>}
|
||||
{request.intent === 'check-in'
|
||||
? <p className="text-[11px] text-muted-foreground">智能体来看看你的进展</p>
|
||||
: <div className="flex justify-end"><p className="consultation-user max-w-[92%] whitespace-pre-wrap break-words rounded-2xl rounded-br-sm px-4 py-3 text-[13px] leading-7">{request.text}</p></div>}
|
||||
@@ -452,12 +566,13 @@ export function TeacherChatPanel({
|
||||
{request.omittedMessages > 0 && <p className="text-[10px] text-muted-foreground">本轮参考了较近的讨论,省略了 {request.omittedMessages} 条较早内容。</p>}
|
||||
{request.error && <p className="text-xs text-destructive">{request.error}</p>}
|
||||
{onBringBack && request.response && request.intent !== 'suggestions' && request.status === 'completed' && <div className="text-[11px] text-muted-foreground">
|
||||
<button onClick={() => onBringBack(request.response)}>带回主会话草稿</button>
|
||||
<button disabled={continuous && (request.projectId !== projectId || request.sourceConversationId !== sourceId)} onClick={() => onBringBack(request.response)}>
|
||||
{continuous && (request.projectId !== projectId || request.sourceConversationId !== sourceId) ? '请打开来源项目和操作对话后带回' : '带回主会话草稿'}</button>
|
||||
</div>}
|
||||
</div>)}
|
||||
</div>
|
||||
{error && <p role="alert" className="px-5 py-2 text-xs leading-5 text-destructive">{error}</p>}
|
||||
{topic?.unsaved && <div className="px-5 py-2 text-xs text-destructive">回复尚未保存,请复制或重试保存。<button className="ml-2 underline" onClick={() => void teacherApi.save(topicBase, topic.id).then(consume).catch(() => setError('保存失败,请先复制回复。'))}>重试保存</button></div>}
|
||||
{topic?.unsaved && <div className="px-5 py-2 text-xs text-destructive">回复尚未保存,请复制或重试保存。<button className="ml-2 underline" onClick={() => void teacherApi.save(topicBase, endpointId).then(consume).catch(() => setError('保存失败,请先复制回复。'))}>重试保存</button></div>}
|
||||
{!topicEnabled && !error && !busy && <p className="px-5 pb-2 text-xs text-muted-foreground">{legacyFriend ? '这是旧版内置朋友的话题,仅供查看。请选择智能体新建话题。' : `${label}暂未开放,历史仍可查看。`}</p>}
|
||||
<form className="px-4 pb-4 pt-2" onSubmit={(e) => { e.preventDefault(); void send(); }}>
|
||||
{Boolean(unassignedDraft.text?.trim() || unassignedDraft.references?.length) && <details className="mb-2 text-xs text-muted-foreground">
|
||||
@@ -483,7 +598,7 @@ export function TeacherChatPanel({
|
||||
<div className="mt-2 flex items-center justify-between gap-2" data-testid="consultation-composer-actions">
|
||||
{discussionEnabled ? <button type="button" disabled={helpUnavailable} onClick={askForSuggestions} className="consultation-help-prompt flex min-h-9 cursor-pointer items-center gap-1.5 rounded-full px-3 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50">帮我看看<ChevronRight className="h-3 w-3" aria-hidden="true" /></button>
|
||||
: <span />}
|
||||
{running ? <button type="button" className="rounded-lg border px-3 py-2 text-xs" onClick={() => void teacherApi.cancel(topicBase, topic!.id, running.id).then(consume).catch(() => setError('暂时无法停止,请稍后重试。'))}>停止回复</button>
|
||||
{running ? <button type="button" className="rounded-lg border px-3 py-2 text-xs" onClick={() => void teacherApi.cancel(topicBase, endpointId, running.id).then(consume).catch(() => setError('暂时无法停止,请稍后重试。'))}>停止回复</button>
|
||||
: <button type="submit" aria-label="提问" title={busy ? '正在发送…' : '发送'} disabled={busy || !topicEnabled || !text.trim()} className="consultation-send flex h-8 w-8 items-center justify-center rounded-full text-white disabled:opacity-30"><ArrowUp className="h-4 w-4" /></button>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -28,7 +28,7 @@ export function TeacherCompanion({ companion, open, onOpen, bubbleRef }: {
|
||||
aria-controls="coding-consultation-dock" data-agent-id={agent.teacher_id}
|
||||
onMouseDown={(event) => event.preventDefault()} onClick={() => onOpen(agent.teacher_id)}>
|
||||
<span className="teacher-companion-avatar"><TeacherAvatar definition={agent.definition} />
|
||||
{activeId === agent.teacher_id && invitation && <span className="teacher-companion-unread" aria-hidden="true" />}</span>
|
||||
{(companion.unreadAgentIds.includes(agent.teacher_id) || (activeId === agent.teacher_id && invitation)) && <span className="teacher-companion-unread" aria-hidden="true" />}</span>
|
||||
<span className="teacher-companion-name">{agent.definition.name}</span>
|
||||
{activeId === agent.teacher_id && checking && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" aria-label="智能体正在思考" />}
|
||||
</button>)}
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user