fix: isolate delivered agent chats by project

This commit is contained in:
2026-09-28 16:21:14 +08:00
parent a21a1f077c
commit 4b41c23a3a
15 changed files with 518 additions and 165 deletions

View File

@@ -20,6 +20,7 @@ const api = vi.hoisted(() => ({
}));
vi.mock('@/lib/coding-teacher', () => ({
teacherApi: api,
teacherConversationsPath: (project: string) => '/api/coding/projects/' + project + '/agent-conversations',
teacherTopicsPath: (p: string) => p === 'preview' ? 'preview/sample' : p + '/agent-topics',
legacyTopicBase: (base: string, legacy: boolean) => legacy ? base.replace('agent-topics', 'friend-topics') : base,
}));
@@ -696,7 +697,7 @@ describe('merged cloud teacher classroom', () => {
const selected = { ...topic('selected'), sourceConversationId: 'project', role: 'teacher' as const, definition: cloudDefinition, version: 9 };
api.conversation.mockResolvedValue({ topic: null, before: null });
api.create.mockResolvedValue(selected);
api.sendConversation.mockImplementation(async (_agent, input: TeacherSend) => ({ ...selected, revision: 2,
api.sendConversation.mockImplementation(async (_project, _agent, input: TeacherSend) => ({ ...selected, revision: 2,
conversation: {agentId: 'algorithm', segmentTurns: 1, discussions: {}, seenThrough: input.requestId},
requests: [request({ id: input.requestId, text: input.text, response: '先看看玩家会做什么。' })] }));
render(<TeacherChatPanel projectId="p" sourceId="c" selectedAgent={{ teacher_id: 'algorithm', version: 9, definition: cloudDefinition, is_default: false }} />);
@@ -709,7 +710,7 @@ describe('merged cloud teacher classroom', () => {
fireEvent.click(screen.getByRole('button', { name: '提问', exact: true }));
await screen.findByText('先看看玩家会做什么。');
expect(api.create).not.toHaveBeenCalled();
expect(api.sendConversation).toHaveBeenCalledWith('algorithm', expect.objectContaining({ projectId: 'p', sourceConversationId: 'c', presentation: 'discussion-v1' }));
expect(api.sendConversation).toHaveBeenCalledWith('p', 'algorithm', expect.objectContaining({ projectId: 'p', sourceConversationId: 'c', presentation: 'discussion-v1' }));
expect(screen.getByRole('complementary', { name: '算法智能体咨询' })).toBeVisible();
});

View File

@@ -7,7 +7,8 @@ import { TeacherChatPanel } from '@/pages/Chat/TeacherChatPanel';
import { TEACHER_CHECK_IN_INTERVAL_MS, type TeacherCatalog, type TeacherDefinition, type TeacherTopic } from '../../shared/coding-teacher';
const api = vi.hoisted(() => ({ catalog: vi.fn(), config: vi.fn(), list: vi.fn(), read: vi.fn(), create: vi.fn(), send: vi.fn(), events: vi.fn(), checkIn: vi.fn(), conversation: vi.fn(), sendConversation: vi.fn(), seenConversation: vi.fn() }));
vi.mock('@/lib/coding-teacher', () => ({ teacherApi: api, legacyTopicBase: (base: string) => base, teacherTopicsPath: (project: string) => project }));
vi.mock('@/lib/coding-teacher', () => ({ teacherApi: api, legacyTopicBase: (base: string) => base, teacherTopicsPath: (project: string) => project,
teacherConversationsPath: (project: string) => '/api/coding/projects/' + project + '/agent-conversations' }));
vi.mock('@/stores/auth', () => ({ useAuthStore: (selector: (state: unknown) => unknown) => selector({ user: { userId: 'kid' } }) }));
const definition: TeacherDefinition = {
schema_version: 1, teacher_id: 'coding-teacher', name: '运营配置的智能体', description: '', avatar_id: 'avatar-06', welcome_message: '', suggested_questions: [], system_prompt: '指导', skills: [],
@@ -89,7 +90,7 @@ describe('manual agent refresh', () => {
await act(async () => fireEvent.click(screen.getByRole('button', { name: '提问', exact: true })));
expect(api.create).not.toHaveBeenCalled();
expect(api.send).not.toHaveBeenCalled();
expect(api.sendConversation).toHaveBeenCalledWith(original.teacher_id, expect.objectContaining({ projectId: 'project', sourceConversationId: 'source', text: '我正在写的问题' }));
expect(api.sendConversation).toHaveBeenCalledWith('project', original.teacher_id, expect.objectContaining({ projectId: 'project', sourceConversationId: 'source', text: '我正在写的问题' }));
});
it('preserves the ongoing chat, old turn version and draft across refresh and later removal', async () => {
@@ -100,7 +101,7 @@ describe('manual agent refresh', () => {
requests: [{ ...checkInTopic().requests[0], teacherVersion: 1 }],
conversation: { agentId: original.teacher_id, segmentTurns: 1, discussions: {}, seenThrough: 'check-1' } };
api.catalog.mockResolvedValue({ items: [original] });
api.conversation.mockImplementation(async (id) => ({ topic: id === original.teacher_id ? history : null, before: null }));
api.conversation.mockImplementation(async (project, id) => ({ topic: project === 'project' && id === original.teacher_id ? history : null, before: null }));
const view = await mount();
await act(async () => fireEvent.click(screen.getByRole('button', { name: '智能体', exact: true })));
const input = screen.getByLabelText('向智能体提问');
@@ -122,16 +123,19 @@ describe('manual agent refresh', () => {
expect(screen.queryByRole('button', { name: '智能体新话题' })).not.toBeInTheDocument();
expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
await act(async () => view.rerender(<Harness projectId="other" />));
expect(screen.getByLabelText('向智能体提问')).toBe(input);
expect(input).toHaveValue('接着刚才说');
expect(screen.getByLabelText('向智能体提问')).toHaveValue('');
expect(screen.queryByText(history.requests[0].response)).toBeNull();
await act(async () => view.rerender(<Harness projectId="project" />));
const restoredInput = screen.getByLabelText('向智能体提问');
expect(restoredInput).toHaveValue('接着刚才说');
api.sendConversation.mockResolvedValue(history);
await act(async () => fireEvent.click(screen.getByRole('button', { name: '提问', exact: true })));
expect(api.sendConversation).toHaveBeenCalledWith(original.teacher_id, expect.objectContaining({ text: '接着刚才说', projectId: 'other' }));
fireEvent.change(input, { target: { value: '停用时保留的问题' } });
expect(api.sendConversation).toHaveBeenCalledWith('project', original.teacher_id, expect.objectContaining({ text: '接着刚才说', projectId: 'project' }));
fireEvent.change(restoredInput, { target: { value: '停用时保留的问题' } });
api.catalog.mockResolvedValue({ items: [added] });
await act(async () => fireEvent.click(screen.getByRole('button', { name: '刷新智能体' })));
expect(screen.getByRole('button', { name: '与方法伙伴聊天' })).toHaveAttribute('aria-pressed', 'true');
expect(input).toHaveValue('停用时保留的问题');
expect(restoredInput).toHaveValue('停用时保留的问题');
expect(screen.getByRole('button', { name: '提问', exact: true })).toBeDisabled();
expect(within(screen.getByTestId('teacher-chat-panel')).getByText(history.requests[0].response)).toBeVisible();
expect(api.create).not.toHaveBeenCalled();
@@ -220,23 +224,23 @@ describe('teacher presence and periodic guidance', () => {
it('restores the last selected disabled agent as read-only history after a restart', async () => {
const saved = { ...checkInTopic(), definition: {...definition, config_id: 'disabled', name: '已停用的老师'},
conversation: {agentId: 'disabled', segmentTurns: 1, discussions: {}, seenThrough: 'check-1'} };
localStorage.setItem('makelore-teacher-presence:kid:selected-agent', JSON.stringify('disabled'));
localStorage.setItem('makelore-teacher-presence:kid:project:selected-agent', JSON.stringify('disabled'));
api.conversation.mockResolvedValue({topic: saved, before: null});
api.seenConversation.mockResolvedValue(saved);
await mount();
expect(api.conversation).toHaveBeenCalledWith('disabled');
expect(api.conversation).toHaveBeenCalledWith('project', 'disabled');
await act(async () => fireEvent.click(screen.getByRole('button', {name: '智能体', exact: true})));
expect(screen.getByRole('complementary', {name: '已停用的老师咨询'})).toBeVisible();
expect(screen.getByRole('button', {name: '提问', exact: true})).toBeDisabled();
expect(api.sendConversation).not.toHaveBeenCalled();
});
it('tracks unread replies per agent without creating invitation bubbles or losing the selected chat on a project switch', async () => {
it('tracks unread replies and selected agents separately for each project', async () => {
const agents = ['a', 'b'].map(id => ({teacher_id: id, version: 1, is_default: id === 'a', definition: {...definition, config_id: id, name: id}}));
const chats = agents.map(agent => ({...checkInTopic(), id: agent.teacher_id + '-chat', definition: agent.definition,
conversation: {agentId: agent.teacher_id, segmentTurns: 1, discussions: {}}}));
api.catalog.mockResolvedValue({items: agents});
api.conversation.mockImplementation(async id => ({topic: chats.find(chat => chat.definition.config_id === id), before: null}));
api.seenConversation.mockImplementation(async (id, requestId) => {
api.conversation.mockImplementation(async (project, id) => ({topic: project === 'project' ? chats.find(chat => chat.definition.config_id === id) : null, before: null}));
api.seenConversation.mockImplementation(async (_project, id, requestId) => {
const chat = chats.find(chat => chat.definition.config_id === id)!;
return {...chat, revision: 3, conversation: {...chat.conversation, seenThrough: requestId}};
});
@@ -244,9 +248,12 @@ describe('teacher presence and periodic guidance', () => {
expect(view.container.querySelectorAll('.teacher-companion-unread')).toHaveLength(2);
expect(screen.queryByTestId('teacher-invitation')).not.toBeInTheDocument();
await act(async () => fireEvent.click(screen.getByRole('button', {name: '与b聊天'})));
expect(api.seenConversation).toHaveBeenCalledWith('b', 'check-1');
expect(api.seenConversation).toHaveBeenCalledWith('project', 'b', 'check-1');
expect(screen.getByRole('button', {name: '与b聊天'}).querySelector('.teacher-companion-unread')).toBeNull();
await act(async () => view.rerender(<Harness projectId="other" />));
expect(screen.getByRole('button', {name: '与a聊天'})).toHaveAttribute('aria-pressed', 'true');
expect(view.container.querySelectorAll('.teacher-companion-unread')).toHaveLength(0);
await act(async () => view.rerender(<Harness projectId="project" />));
expect(screen.getByRole('button', {name: '与b聊天'})).toHaveAttribute('aria-pressed', 'true');
expect(api.create).not.toHaveBeenCalled();
});
@@ -372,7 +379,7 @@ describe('teacher presence and periodic guidance', () => {
expect(api.checkIn).not.toHaveBeenCalled();
await act(async () => fireEvent.click(screen.getByRole('button', { name: '提问', exact: true })));
expect(api.create).not.toHaveBeenCalled();
expect(api.sendConversation).toHaveBeenCalledWith('experience', expect.objectContaining({projectId: 'project', text: '体验的草稿'}));
expect(api.sendConversation).toHaveBeenCalledWith('project', 'experience', expect.objectContaining({projectId: 'project', text: '体验的草稿'}));
});
it('restores each selected agent conversation and uses its stable identity when sending', async () => {
@@ -385,19 +392,19 @@ describe('teacher presence and periodic guidance', () => {
{ id: oldB.id, teacherId: b.teacher_id, title: '体验历史' },
{ id: oldA.id, teacherId: a.teacher_id, title: '方法历史' },
], lastSelectedTopicId: oldB.id });
api.conversation.mockImplementation(async id => ({topic: id === 'method' ? oldA : oldB, before: null}));
api.conversation.mockImplementation(async (_project, id) => ({topic: id === 'method' ? oldA : oldB, before: null}));
api.sendConversation.mockResolvedValue({ ...oldA, revision: 3 });
await mount();
await act(async () => fireEvent.click(screen.getByRole('button', { name: '与方法老师聊天' })));
expect(api.conversation).toHaveBeenCalledWith('method');
expect(api.conversation).toHaveBeenCalledWith('project', 'method');
expect(screen.getByRole('complementary', { name: '方法老师咨询' })).toBeVisible();
fireEvent.change(screen.getByLabelText('向智能体提问'), { target: { value: '继续原来的讨论' } });
await act(async () => fireEvent.click(screen.getByRole('button', { name: '提问', exact: true })));
expect(api.sendConversation.mock.calls[0][0]).toBe('method');
expect(api.sendConversation.mock.calls[0][1]).toBe('method');
expect(api.create).not.toHaveBeenCalled();
await act(async () => fireEvent.click(screen.getByRole('button', { name: '与体验朋友聊天' })));
expect(screen.getByRole('complementary', { name: '体验朋友咨询' })).toBeVisible();
expect(api.conversation).toHaveBeenCalledWith('experience');
expect(api.conversation).toHaveBeenCalledWith('project', 'experience');
});
it('ignores a late initial history read after the student selects a different agent', async () => {
@@ -408,13 +415,13 @@ describe('teacher presence and periodic guidance', () => {
api.list.mockResolvedValue({ items: [{ id: old.id, teacherId: 'a' }], lastSelectedTopicId: old.id });
let resolve!: (view: {topic: TeacherTopic; before: null}) => void;
const pending = new Promise<{topic: TeacherTopic; before: null}>((done) => { resolve = done; });
api.conversation.mockImplementation(id => id === 'a' ? pending : Promise.resolve({topic: null, before: null}));
api.conversation.mockImplementation((_project, id) => id === 'a' ? pending : Promise.resolve({topic: null, before: null}));
await mount();
await act(async () => fireEvent.click(screen.getByRole('button', { name: '与体验朋友聊天' })));
await act(async () => resolve({topic: old, before: null}));
expect(screen.getByRole('complementary', { name: '体验朋友咨询' })).toBeVisible();
expect(screen.getByRole('button', { name: '与体验朋友聊天' })).toHaveAttribute('aria-pressed', 'true');
expect(api.conversation).toHaveBeenCalledWith('a');
expect(api.conversation).toHaveBeenCalledWith('project', 'a');
expect(api.send).not.toHaveBeenCalled();
});
@@ -441,7 +448,7 @@ describe('teacher presence and periodic guidance', () => {
expect(screen.queryByTestId('teacher-invitation')).not.toBeInTheDocument();
});
it('shows the published greeting immediately without a model request and remembers dismissal across projects', async () => {
it('shows the published greeting without a model request and remembers dismissal in its project', async () => {
api.config.mockResolvedValue({ enabled: true, definition: { ...definition, welcome_message: '有什么编程问题想一起讨论?' } });
const view = await mount();
expect(screen.getByTestId('teacher-invitation')).toHaveAttribute('data-bubble-kind', 'welcome');
@@ -453,6 +460,8 @@ describe('teacher presence and periodic guidance', () => {
const next = await mount();
expect(screen.queryByTestId('teacher-invitation')).not.toBeInTheDocument();
await act(async () => next.rerender(<Harness projectId="other" />));
expect(screen.getByTestId('teacher-invitation')).toBeVisible();
await act(async () => next.rerender(<Harness projectId="project" />));
expect(screen.queryByTestId('teacher-invitation')).not.toBeInTheDocument();
});

View File

@@ -7,6 +7,7 @@ const api = vi.hoisted(() => ({ catalog: vi.fn(), config: vi.fn(), conversation:
list: vi.fn(), read: vi.fn(), legacyHistory: vi.fn(), legacyRead: vi.fn(), create: vi.fn(), send: vi.fn(), events: vi.fn(), updateDiscussion: vi.fn(), cancel: vi.fn(), seenConversation: vi.fn() }));
const identity = vi.hoisted(() => ({ id: 0 }));
vi.mock('@/lib/coding-teacher', () => ({ teacherApi: api, legacyTopicBase: (base: string) => base,
teacherConversationsPath: (project: string) => '/api/coding/projects/' + project + '/agent-conversations',
teacherTopicsPath: (project: string) => '/legacy/' + project }));
vi.mock('@/stores/auth', () => ({ useAuthStore: (selector: (state: unknown) => unknown) => selector({ user: { userId: 'kid-' + identity.id } }) }));
const definition: TeacherDefinition = { schema_version: 1, config_id: 'agent-a', teacher_id: 'teacher',
@@ -29,11 +30,11 @@ beforeEach(() => {
vi.resetAllMocks(); identity.id++; localStorage.clear(); stream = new EventTarget();
api.config.mockResolvedValue({ enabled: true, definition });
api.catalog.mockResolvedValue({ items: [agent] });
api.conversation.mockResolvedValue({ topic: topic(), before: null });
api.conversation.mockImplementation(async projectId => ({ topic: projectId === 'project-a' ? topic() : null, before: null }));
api.list.mockResolvedValue({ items: [], lastSelectedTopicId: null });
api.events.mockResolvedValue(Object.assign(stream, { close: vi.fn() }));
api.seenConversation.mockImplementation(async (_agent, requestId) => ({ ...topic(), conversation: { ...topic().conversation!, seenThrough: requestId } }));
api.sendConversation.mockImplementation(async (_agent, input) => ({ ...topic(), revision: 2,
api.seenConversation.mockImplementation(async (projectId, _agent, requestId) => ({ ...topic(), projectId, conversation: { ...topic().conversation!, seenThrough: requestId } }));
api.sendConversation.mockImplementation(async (projectId, _agent, input) => ({ ...topic(), projectId, revision: 2,
requests: [...topic().requests, { ...request(input.requestId, input.text), projectId: input.projectId, sourceConversationId: input.sourceConversationId }] }));
});
afterEach(cleanup);
@@ -41,23 +42,53 @@ const props = { projectId: 'project-a', projectName: '天气', sourceId: 'source
async function mount() { let view!: ReturnType<typeof render>; await act(async () => { view = render(<TeacherChatPanel {...props} />); }); return view; }
describe('continuous agent panel', () => {
it('opens one chat without topic controls or creating a topic, and preserves it across project switches', async () => {
it('ignores a previous project fetch and external snapshot after a project switch', async () => {
let resolve!: (value: { topic: TeacherTopic; before: null }) => void;
const delayed = new Promise<{ topic: TeacherTopic; before: null }>(done => { resolve = done; });
api.conversation.mockImplementation(project => project === 'project-a' ? delayed : Promise.resolve({ topic: null, before: null }));
const view = await mount();
await act(async () => view.rerender(<TeacherChatPanel {...props} projectId="project-b" externalTopic={topic()} />));
await act(async () => resolve({ topic: topic(), before: null }));
expect(screen.queryByText('旧的问题')).toBeNull();
expect(api.seenConversation).not.toHaveBeenCalled();
expect(screen.getByRole('textbox')).toHaveValue('');
});
it('adopts an old global draft only in its recorded project and preserves the original', async () => {
const key = `makelore-consultation-draft:kid-${identity.id}:agent:agent-a`;
const original = JSON.stringify({ text: '旧全局草稿', projectId: 'project-a', sourceId: 'source-a' });
localStorage.setItem(key, original);
const olderProjectKey = `makelore-consultation-draft:kid-${identity.id}:project-a:agent:agent-a`;
localStorage.setItem(olderProjectKey, JSON.stringify({ text: '升级前更旧的草稿' }));
const view = await mount();
expect(screen.getByRole('textbox')).toHaveValue('旧全局草稿');
await act(async () => view.rerender(<TeacherChatPanel {...props} projectId="project-b" />));
expect(screen.getByRole('textbox')).toHaveValue('');
expect(localStorage.getItem(key)).toBe(original);
expect(localStorage.getItem(olderProjectKey)).toContain('升级前更旧的草稿');
await act(async () => view.rerender(<TeacherChatPanel {...props} />));
expect(screen.getByRole('textbox')).toHaveValue('旧全局草稿');
});
it('keeps one chat per project and restores its own history and draft when switching back', async () => {
const view = await mount();
expect(screen.queryByRole('button', { name: '智能体新话题' })).toBeNull();
expect(screen.queryByRole('combobox')).toBeNull();
expect(api.create).not.toHaveBeenCalled();
expect(screen.getByText('旧的问题')).toBeInTheDocument();
fireEvent.change(screen.getByRole('textbox'), { target: { value: '跨项目草稿' } });
view.rerender(<TeacherChatPanel {...props} projectId="project-b" projectName="游戏" sourceId="source-b" />);
expect(screen.getByRole('textbox')).toHaveValue('跨项目草稿');
expect(screen.getByText('旧的问题')).toBeInTheDocument();
expect(screen.getByText('本轮项目:游戏 · 当前操作对话')).toBeInTheDocument();
fireEvent.change(screen.getByRole('textbox'), { target: { value: '天气项目草稿' } });
await act(async () => view.rerender(<TeacherChatPanel {...props} projectId="project-b" projectName="游戏" sourceId="source-b" />));
expect(screen.getByRole('textbox')).toHaveValue('');
expect(screen.queryByText('旧的问题')).toBeNull();
fireEvent.change(screen.getByRole('textbox'), { target: { value: '游戏问题' } });
fireEvent.click(screen.getByRole('button', { name: '提问' }));
await waitFor(() => expect(api.sendConversation).toHaveBeenCalledWith('agent-a', expect.objectContaining({
projectId: 'project-b', sourceConversationId: 'source-b', text: '跨项目草稿' })));
await waitFor(() => expect(api.sendConversation).toHaveBeenCalledWith('project-b', 'agent-a', expect.objectContaining({
projectId: 'project-b', sourceConversationId: 'source-b', text: '游戏问题' })));
await act(async () => view.rerender(<TeacherChatPanel {...props} />));
expect(screen.getByRole('textbox')).toHaveValue('天气项目草稿');
expect(screen.getByText('旧的问题')).toBeInTheDocument();
expect(screen.queryByText('游戏问题')).toBeNull();
});
it('merges older pages and streamed current turns without replacing earlier messages', async () => {
api.conversation.mockImplementation(async (_id, before) => ({ topic: before ? topic([request('0', '更早的问题')]) : topic(), before: before ? null : '1' }));
api.conversation.mockImplementation(async (_project, _id, before) => ({ topic: before ? topic([request('0', '更早的问题')]) : topic(), before: before ? null : '1' }));
await mount();
fireEvent.click(screen.getByText('查看更早消息'));
await screen.findByText('更早的问题');
@@ -68,12 +99,12 @@ describe('continuous agent panel', () => {
expect(screen.getByText('旧的问题')).toBeInTheDocument();
expect(screen.getByText('新的问题')).toBeInTheDocument();
});
it('rejects stale references and prevents carrying an old project reply into the new Pi draft', async () => {
it('rejects stale references and prevents carrying an old Pi reply into another Pi draft', async () => {
const bring = vi.fn();
let view!: ReturnType<typeof render>;
await act(async () => { view = render(<TeacherChatPanel {...props} quote={{ kind: 'code', text: '旧项目代码' }} onBringBack={bring} />); });
fireEvent.change(screen.getByRole('textbox'), { target: { value: '看看' } });
view.rerender(<TeacherChatPanel {...props} projectId="project-b" sourceId="source-b" onBringBack={bring} />);
view.rerender(<TeacherChatPanel {...props} sourceId="source-b" onBringBack={bring} />);
fireEvent.click(screen.getByRole('button', { name: '提问' }));
expect(api.sendConversation).not.toHaveBeenCalled();
expect(screen.getByRole('alert')).toHaveTextContent('引用来自另一个项目');
@@ -91,7 +122,7 @@ describe('continuous agent panel', () => {
it('merges a delayed older page without overwriting a newer streamed answer', async () => {
let resolve!: (value: {topic: TeacherTopic; before: null}) => void;
const page = new Promise<{topic: TeacherTopic; before: null}>(done => { resolve = done; });
api.conversation.mockImplementation((_id, before) => before ? page : Promise.resolve({ topic: topic(), before: '1' }));
api.conversation.mockImplementation((_project, _id, before) => before ? page : Promise.resolve({ topic: topic(), before: '1' }));
await mount();
fireEvent.click(screen.getByText('查看更早消息'));
await act(async () => stream.dispatchEvent(new MessageEvent('snapshot', {data: JSON.stringify({

View File

@@ -36,13 +36,82 @@ function turn(index: number): TeacherRequest {
omittedMessages: 0, status: 'completed', response: '回答 ' + index };
}
describe('continuous conversation persistence', () => {
it('splits mixed global history by recorded project, preserving originals, seen positions and legacy identities', async () => {
const dir = await root(), global = path.join(dir, 'global');
const project = { id: randomUUID(), path: path.join(dir, 'project'), name: '天气' };
const other = randomUUID(), oldId = randomUUID();
const legacyTurn = turn(0);
const imported = { ...legacyTurn, id: randomUUID(), projectId: project.id,
origin: { projectId: project.id, topicId: oldId, requestId: legacyTurn.id } };
const turns = [imported, ...Array.from({ length: 110 }, (_, i) => ({
...turn(i + 1), projectId: i % 2 ? other : project.id, runtimeThreadId: 'mixed-cloud-thread',
})), turn(112)]; // This old turn has no proven project and must remain only in the original archive.
const metadata = { schemaVersion: 1, revision: 4, accountId: 'account', id: randomUUID(),
projectId: other, sourceConversationId: 'project', definition, version: 1,
createdAt: 'now', updatedAt: 'now', conversation: { agentId: 'agent-a', segmentTurns: 0, discussions: {},
seenThrough: turns[42].id } };
const manifest = { topic: metadata, turns: turns.map(({ id, createdAt }) => ({ id, createdAt, messages: [] })) };
await atomicWriteJson(path.join(global, 'conversation.json'), manifest);
for (const request of turns) await atomicWriteJson(path.join(global, 'turns', request.id + '.json'), request);
const orphan = { ...turn(113), projectId: other, status: 'running' };
await atomicWriteJson(path.join(global, 'turns', orphan.id + '.json'), orphan);
const original = await readFile(path.join(global, 'conversation.json'), 'utf8');
const originalTurn = await readFile(path.join(global, 'turns', orphan.id + '.json'), 'utf8');
const target = path.join(dir, 'a');
const a = new TeacherConversationStore(target, 'account', 'agent-a', project.id);
await a.importGlobal(global);
const b = new TeacherConversationStore(path.join(dir, 'b'), 'account', 'agent-a', other);
await b.importGlobal(global);
expect((await a.read()).id).not.toBe((await b.read()).id);
expect((await a.history()).messages).toHaveLength(56 * 2);
expect((await b.history()).messages).toHaveLength(55 * 2); // Interrupted turns stay visible but are not model context.
expect((await a.page()).requests.every(request => request.projectId === project.id)).toBe(true);
expect((await a.read()).conversation?.seenThrough).toBe(turns[41].id);
expect((await b.read()).conversation?.seenThrough).toBe(turns[42].id);
expect((await b.findRequest(orphan.id))?.status).toBe('interrupted');
expect((await a.findRequest(turns[1].id))?.origin?.topicId).toBe(metadata.id);
expect((await a.findRequest(turns[1].id))?.cloudRequestId).toBe(turns[1].id);
const legacy = new TeacherTopicStore(path.join(project.path, '.makelore', 'teacher-conversations', 'account', 'project'));
await legacy.save({ ...metadata, id: oldId, projectId: project.id, conversation: undefined, requests: [legacyTurn] });
await a.importProject(project);
const resumed = new TeacherConversationStore(target, 'account', 'agent-a', project.id);
await resumed.importGlobal(global); await resumed.importProject(project);
expect((await resumed.history()).messages).toHaveLength(56 * 2);
expect(await readFile(path.join(global, 'conversation.json'), 'utf8')).toBe(original);
expect(await readFile(path.join(global, 'turns', orphan.id + '.json'), 'utf8')).toBe(originalTurn);
const foreign = new TeacherConversationStore(path.join(dir, 'foreign'), 'other-account', 'agent-a', project.id);
await foreign.importGlobal(global);
expect(await foreign.exists()).toBe(false);
});
it('resumes a partial global split after an index write failure without duplicate messages', async () => {
const dir = await root(), old = path.join(dir, 'global'), dest = path.join(dir, 'project');
const request = { ...turn(1), projectId: 'project-a' };
await atomicWriteJson(path.join(old, 'conversation.json'), { topic: {
accountId: 'account', id: randomUUID(), definition, version: 1,
conversation: { agentId: 'agent-a', discussions: {} },
}, turns: [{ id: request.id, createdAt: request.createdAt, messages: [] }] });
await atomicWriteJson(path.join(old, 'turns', request.id + '.json'), request);
const store = new TeacherConversationStore(dest, 'account', 'agent-a', 'project-a');
await store.ensure(definition, 1);
const write = atomic.atomicWriteJson;
let fail = true;
vi.spyOn(atomic, 'atomicWriteJson').mockImplementation(async (file, value) => {
if (fail && file === path.join(dest, 'conversation.json')) { fail = false; throw new Error('disk unavailable'); }
return write(file, value);
});
await expect(store.importGlobal(old)).rejects.toThrow('disk unavailable');
await store.importGlobal(old);
expect((await store.read()).requests.map(turn => turn.id)).toEqual([request.id]);
await new TeacherConversationStore(dest, 'account', 'agent-a', 'project-a').importGlobal(old);
expect((await store.history()).messages).toHaveLength(2);
});
it('pages thousands of turns, restores the latest page and preserves repeated questions', async () => {
const dir = await root();
const store = new TeacherConversationStore(dir, 'account', 'agent-a');
const store = new TeacherConversationStore(dir, 'account', 'agent-a', 'project-a');
const topic = await store.ensure(definition, 1);
topic.requests = Array.from({ length: 1001 }, (_, i) => turn(i));
await store.save(topic);
const resumed = new TeacherConversationStore(dir, 'account', 'agent-a');
const resumed = new TeacherConversationStore(dir, 'account', 'agent-a', 'project-a');
expect((await resumed.read()).requests).toHaveLength(50);
const latest = await resumed.page();
expect(latest.requests.at(-1)?.response).toBe('回答 1000');
@@ -59,15 +128,15 @@ describe('continuous conversation persistence', () => {
expect((await tools.executeResult('read_conversation', JSON.stringify({message_id: `teacher:${topic.requests.at(-1)!.id}:assistant`}), signal)).status).toBe('error');
await resumed.markSeen(latest.requests.at(-1)!.id);
await resumed.markSeen(older.requests[0].id);
expect((await new TeacherConversationStore(dir, 'account', 'agent-a').read()).conversation?.seenThrough).toBe(latest.requests.at(-1)!.id);
expect((await new TeacherConversationStore(dir, 'account', 'agent-a', 'project-a').read()).conversation?.seenThrough).toBe(latest.requests.at(-1)!.id);
});
it('recovers a turn written before its index and marks only unfinished work interrupted', async () => {
const dir = await root();
const store = new TeacherConversationStore(dir, 'account', 'agent-a');
const store = new TeacherConversationStore(dir, 'account', 'agent-a', 'project-a');
await store.ensure(definition, 1);
const pending = { ...turn(1), status: 'running' as const };
await atomicWriteJson(path.join(dir, 'turns', pending.id + '.json'), pending);
const resumed = new TeacherConversationStore(dir, 'account', 'agent-a');
const resumed = new TeacherConversationStore(dir, 'account', 'agent-a', 'project-a');
expect((await resumed.read()).requests[0]).toMatchObject({ id: pending.id, status: 'interrupted' });
expect((await resumed.page()).requests).toHaveLength(1);
});
@@ -80,14 +149,14 @@ describe('continuous conversation persistence', () => {
await oldStore.save(old);
const file = path.join(oldStore.directory, old.id + '.json'), before = await readFile(file, 'utf8');
const target = path.join(dir, 'new');
const store = new TeacherConversationStore(target, 'account', 'agent-a');
const store = new TeacherConversationStore(target, 'account', 'agent-a', project.id);
await store.importProject(project);
const resumed = new TeacherConversationStore(target, 'account', 'agent-a');
const resumed = new TeacherConversationStore(target, 'account', 'agent-a', project.id);
await resumed.importProject(project);
expect((await resumed.read()).requests).toHaveLength(2);
expect((await resumed.read()).requests[0].origin?.topicId).toBe(old.id);
expect(await readFile(file, 'utf8')).toBe(before);
const other = new TeacherConversationStore(path.join(dir, 'other'), 'another-account', 'agent-a');
const other = new TeacherConversationStore(path.join(dir, 'other'), 'another-account', 'agent-a', project.id);
await other.importProject(project);
expect(await other.exists()).toBe(false);
});
@@ -97,7 +166,7 @@ describe('continuous conversation persistence', () => {
const old: TeacherTopic = { schemaVersion: 1, revision: 1, accountId: 'account', id: randomUUID(),
projectId: project.id, sourceConversationId: 'project', definition, version: 1, createdAt: 'now', updatedAt: 'now', requests: [turn(1)] };
await oldStore.save(old);
const store = new TeacherConversationStore(path.join(dir, 'chat'), 'account', 'agent-a');
const store = new TeacherConversationStore(path.join(dir, 'chat'), 'account', 'agent-a', project.id);
await store.ensure(definition, 1);
const write = atomic.atomicWriteJson;
let fail = true;
@@ -123,7 +192,9 @@ it('serves paged account chats and compact SSE, preserves legacy source records
{codingProducts: {teacher: f.service}} as HostApiContext); });
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const address = server.address(); if (!address || typeof address === 'string') throw new Error('no address');
const origin = 'http://127.0.0.1:' + address.port, base = origin + '/api/coding/agent-conversations/agent-a';
const origin = 'http://127.0.0.1:' + address.port;
const base = origin + '/api/coding/projects/' + f.a.project.id + '/agent-conversations/agent-a';
const otherBase = origin + '/api/coding/projects/' + f.b.project.id + '/agent-conversations/agent-a';
const post = (url: string, input: unknown) => fetch(url, {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(input)});
try {
const page = await (await fetch(base)).json();
@@ -135,15 +206,20 @@ it('serves paged account chats and compact SSE, preserves legacy source records
expect((await post(archive, {})).status).toBe(405);
expect(f.run).not.toHaveBeenCalled();
const input = {projectId: f.b.project.id, sourceConversationId: f.bSource.id, requestId: randomUUID(), text: '继续'};
expect((await post(base + '/messages', input)).status).toBe(202);
expect((await post(base + '/messages', input)).status).toBe(202);
await f.settled(); expect(f.run).toHaveBeenCalledTimes(1);
const reader = (await fetch(base + '/events')).body!.getReader();
expect((await (await fetch(otherBase)).json()).topic).toBeNull();
expect((await post(base + '/messages', input)).status).toBe(422);
expect((await post(otherBase + '/messages', input)).status).toBe(202);
expect((await post(otherBase + '/messages', input)).status).toBe(202);
await f.settled(f.b); expect(f.run).toHaveBeenCalledTimes(1);
const reader = (await fetch(otherBase + '/events')).body!.getReader();
const chunk = new TextDecoder().decode((await reader.read()).value);
const snapshot = JSON.parse(chunk.split('data: ')[1].split('\n')[0]);
expect(snapshot.requests).toHaveLength(1); expect(snapshot.requests[0].id).toBe(input.requestId);
await reader.cancel();
expect((await (await post(base + '/seen', {requestId: input.requestId})).json()).conversation.seenThrough).toBe(input.requestId);
expect((await (await post(otherBase + '/seen', {requestId: input.requestId})).json()).conversation.seenThrough).toBe(input.requestId);
expect((await (await post(base + '/seen', {requestId: input.requestId})).json()).conversation.seenThrough).toBeUndefined();
expect((await (await fetch(base)).json()).topic.requests).toHaveLength(50);
expect((await post(otherBase + '/discussion', {projectId: f.a.project.id, action: 'archive'})).status).toBe(422);
expect((await fetch(base + '?before=missing')).status).toBe(400);
} finally { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); }
});
@@ -160,7 +236,7 @@ async function fixture() {
let wait = false, version = 1, enabled = true, accountId = 'account';
const run = vi.fn(async (messages, _signal: AbortSignal, onText: (text: string) => void) => {
onText('已查看');
if (wait) await new Promise<void>(resolve => { release = resolve; });
if (wait) { wait = false; await new Promise<void>(resolve => { release = resolve; }); }
return { inputTokens: 10, outputTokens: 5 };
});
const prepareCloud = vi.fn((_account, _topic, _id, _access) => ({ inputLimit: 8000, run }));
@@ -175,17 +251,47 @@ async function fixture() {
const send = (project = a, session = aSource, requestId = randomUUID()) => service.sendConversation('agent-a', {
projectId: project.project.id, sourceConversationId: session.id, requestId, text: '帮我看看',
});
const settled = async () => {
await vi.waitFor(async () => expect((await service.conversation('agent-a')).topic?.requests.at(-1)?.status).toBe('completed'));
return (await service.conversation('agent-a')).topic!;
const settled = async (project = a) => {
await vi.waitFor(async () => expect((await service.conversation(project.project.id, 'agent-a')).topic?.requests.at(-1)?.status).toBe('completed'));
return (await service.conversation(project.project.id, 'agent-a')).topic!;
};
return { service, a, b, aSource, aOther, bSource, prepareCloud, run, send, settled,
return { dir, service, a, b, aSource, aOther, bSource, prepareCloud, run, send, settled,
wait: () => { wait = true; }, release: () => { wait = false; release?.(); },
version: (v: number) => { version = v; }, enabled: (v: boolean) => { enabled = v; },
account: (id: string) => { accountId = id; } };
}
describe('one account-agent conversation', () => {
it('keeps one visible chat across projects and versions while freezing each execution scope', async () => {
describe('one account-project-agent conversation', () => {
it('starts a clean cloud segment after splitting mixed history and supplies only the selected project messages', async () => {
const f = await fixture(), global = path.join(f.dir, 'agent-conversations', 'account', 'agent-a');
const turns = [
{ ...turn(1), projectId: f.a.project.id, sourceConversationId: f.aSource.id, runtimeThreadId: 'old-mixed-thread', teacherVersion: 1, text: '天气专属历史' },
{ ...turn(2), projectId: f.b.project.id, sourceConversationId: f.bSource.id, runtimeThreadId: 'old-mixed-thread', teacherVersion: 1, text: '游戏专属历史' },
];
await atomicWriteJson(path.join(global, 'conversation.json'), { topic: {
id: randomUUID(), accountId: 'account', definition, version: 1, projectId: f.b.project.id,
conversation: { agentId: 'agent-a', runtimeThreadId: 'old-mixed-thread', discussions: {} },
}, turns: turns.map(({ id, createdAt }) => ({ id, createdAt, messages: [] })) });
for (const turn of turns) await atomicWriteJson(path.join(global, 'turns', turn.id + '.json'), turn);
await f.send(); const current = await f.settled();
expect(current.requests).toHaveLength(2);
expect(current.requests.at(-1)?.runtimeThreadId).not.toBe('old-mixed-thread');
const messages = JSON.stringify(f.run.mock.calls[0][0]);
expect(messages).toContain('天气专属历史');
expect(messages).not.toContain('游戏专属历史');
});
it('isolates the same agent between projects and restores each project chat', async () => {
const f = await fixture();
const a = await f.send(); await f.settled();
const b = await f.send(f.b, f.bSource); await f.settled(f.b);
expect(b.id).not.toBe(a.id);
expect(b.requests).toHaveLength(1);
expect(JSON.stringify(f.run.mock.calls[1][0])).not.toContain('weather');
const back = await f.send(); await f.settled();
expect(back.id).toBe(a.id);
expect(back.requests).toHaveLength(2);
expect(back.requests.every(request => request.projectId === f.a.project.id)).toBe(true);
});
it('keeps one visible chat per project across versions while freezing each execution scope', async () => {
const f = await fixture();
await f.send(); const first = await f.settled();
await f.send(); const same = await f.settled();
@@ -193,18 +299,18 @@ describe('one account-agent conversation', () => {
expect(same.requests[1].runtimeThreadId).toBe(first.requests[0].runtimeThreadId);
// The same cloud checkpoint already owns the previous exchange.
expect(f.run.mock.calls[1][0].filter((m: { content: string }) => m.content.includes('已查看'))).toHaveLength(0);
await f.send(f.b, f.bSource); const second = await f.settled();
expect(second.id).toBe(first.id);
expect(second.requests[2].runtimeThreadId).not.toBe(first.requests[0].runtimeThreadId);
await f.send(f.b, f.bSource); const second = await f.settled(f.b);
expect(second.id).not.toBe(first.id);
expect(second.requests[0].runtimeThreadId).not.toBe(first.requests[0].runtimeThreadId);
expect(f.prepareCloud.mock.calls[2][3].projectPath).toBe(f.b.project.path);
expect(JSON.stringify(f.run.mock.calls[2][0])).toContain('weather');
f.version(2); await f.send(f.b, f.bSource); const updated = await f.settled();
expect(updated.id).toBe(first.id);
expect(updated.requests.map(request => request.teacherVersion)).toEqual([1, 1, 1, 2]);
expect(updated.requests[3].runtimeThreadId).not.toBe(updated.requests[2].runtimeThreadId);
expect(JSON.stringify(f.run.mock.calls[2][0])).not.toContain('weather');
f.version(2); await f.send(f.b, f.bSource); const updated = await f.settled(f.b);
expect(updated.id).toBe(second.id);
expect(updated.requests.map(request => request.teacherVersion)).toEqual([1, 2]);
expect(updated.requests[1].runtimeThreadId).not.toBe(updated.requests[0].runtimeThreadId);
f.enabled(false);
await expect(f.send()).rejects.toMatchObject({ code: 'teacher_disabled' });
expect((await f.service.conversation('agent-a')).topic?.requests).toHaveLength(4);
expect((await f.service.conversation(f.a.project.id, 'agent-a')).topic?.requests).toHaveLength(2);
});
it('deduplicates concurrent submissions, rejects a second active turn and rotates on Pi source change', async () => {
const f = await fixture(); f.wait();
@@ -212,13 +318,19 @@ describe('one account-agent conversation', () => {
const [a, b] = await Promise.all([f.send(f.a, f.aSource, requestId), f.send(f.a, f.aSource, requestId)]);
expect(a.id).toBe(b.id);
expect(f.run).toHaveBeenCalledTimes(1);
await expect(f.send(f.b, f.bSource)).rejects.toMatchObject({ code: 'teacher_topic_busy' });
await expect(f.send()).rejects.toMatchObject({ code: 'teacher_topic_busy' });
const other = await f.send(f.b, f.bSource); await f.settled(f.b);
expect((await f.service.conversation(f.a.project.id, 'agent-a')).topic?.requests[0].status).toBe('running');
const otherScope = { projectId: f.b.project.id, sourceId: 'project', agentId: 'agent-a' };
await f.service.cancel(otherScope, other.id, requestId);
expect(f.run.mock.calls[0][1].aborted).toBe(false);
await expect(f.service.read(otherScope, a.id)).rejects.toMatchObject({ code: 'teacher_topic_not_found' });
expect(f.prepareCloud.mock.calls[0][3].projectPath).toBe(f.a.project.path);
f.release(); await f.settled();
await f.send(f.a, f.aOther); const next = await f.settled();
expect(next.requests[1].runtimeThreadId).not.toBe(next.requests[0].runtimeThreadId);
f.account('other');
expect((await f.service.conversation('agent-a')).topic).toBe(null);
expect((await f.service.conversation(f.a.project.id, 'agent-a')).topic).toBe(null);
await f.send(); expect((await f.settled()).id).not.toBe(a.id);
});
});