feat: integrate pinned teacher discussion workspace

This commit is contained in:
鲨鱼辣椒
2026-09-23 19:13:51 +08:00
parent 7951cca700
commit 404cfcde46
21 changed files with 1666 additions and 11 deletions

View File

@@ -0,0 +1,64 @@
// Deterministic responses for layout/interaction tests only; never imported by the app.
import type { TeacherDefinition, TeacherTopic, TeacherSend, TeacherDiscussionAction } from '../../../shared/coding-teacher';
import type { TeacherDiscussionContent } from '../../../shared/teacher-discussion';
const definition: TeacherDefinition = { schema_version: 1, teacher_id: 'coding-teacher', name: '麦洛老师', description: '', avatar_id: 'avatar-01', welcome_message: '', suggested_questions: [], system_prompt: '测试', skills: [], model: { model_id: 'fixture', reasoning_choice: { mode: 'default' } }, limits: { max_input_tokens: 8000, max_output_tokens: 1500 } };
const samples: Record<string, TeacherDiscussionContent> = {
ideas: { kind: 'ideas', title: '我的小狗世界', items: [{ id: 'dog', text: '养一只自己的小狗', state: 'kept' }, { id: 'breed', parentId: 'dog', text: '是一只柯基', state: 'kept' }, { id: 'garden', text: '有一片可以种东西的花园', state: 'kept' }, { id: 'food', parentId: 'garden', text: '种出来的东西可以喂小狗', state: 'suggested' }] },
structure: { kind: 'structure', title: '小狗和花园怎么连起来?', nodes: [{ id: 'world', label: '我的小狗世界' }, { id: 'dog', label: '照顾小狗', parentId: 'world' }, { id: 'breed', label: '一只柯基', parentId: 'dog', relation: '它的样子' }, { id: 'garden', label: '种植花园', parentId: 'world' }, { id: 'food', label: '收获食物,喂给小狗', parentId: 'garden', relation: '收获后' }] },
flow: { kind: 'flow', title: '我回家时,小狗会做什么?', nodes: [{ id: 'home', kind: 'event', label: '我回到家' }, { id: 'awake', kind: 'condition', label: '小狗醒着吗?' }, { id: 'welcome', kind: 'outcome', label: '跑过来欢迎我' }, { id: 'sleep', kind: 'outcome', label: '先睡觉,醒来再过来' }], edges: [{ id: 'one', from: 'home', to: 'awake' }, { id: 'yes', from: 'awake', to: 'welcome', label: '醒着' }, { id: 'no', from: 'awake', to: 'sleep', label: '睡着了' }] },
comparison: { kind: 'comparison', title: '哪一种更像你想要的小狗?', columns: [{ id: 'click', label: '点了才回应' }, { id: 'active', label: '会主动找我' }], rows: [{ id: 'home', label: '刚回到家的时候', cells: [{ columnId: 'click', text: '等我点一下,才跳起来。' }, { columnId: 'active', text: '看见我就跑过来,还带着玩具。' }] }, { id: 'busy', label: '我忙着种东西的时候', cells: [{ columnId: 'click', text: '安静等着,不打扰我。' }, { columnId: 'active', text: '有时来蹭一蹭,可能也会打断我。' }] }] },
};
const scenario = new URLSearchParams(location.search).get('kind') ?? 'ideas';
let current: TeacherTopic = { schemaVersion: 1, revision: 1, id: 'discussion-fixture', accountId: 'fixture', projectId: 'fixture', sourceConversationId: 'project', role: 'teacher', definition, version: 1, createdAt: 'now', updatedAt: 'now', requests: Array.from({ length: 8 }, (_, i) => ({ id: `r${i}`, text: i === 7 ? '我还没想好,我们边聊边想。' : '我希望这个游戏更有意思。', references: [], createdAt: 'now', sourceCursor: { workerGeneration: 0, seq: i }, sourceCapturedAt: 'now', includedSourceMessageIds: [], omittedMessages: 0, status: 'completed', response: i === 7 ? '可以,我们先把已经想到的放在一起。哪里还不确定,就留着继续聊。' : '先从你最在意的一个小地方开始想。', ...(scenario === 'ordinary' && i === 7 ? { suggestedQuestions: ['有什么好玩的想法?'] } : {}) })), ...(samples[scenario] ? { discussion: { id: 'tool', revision: 1, status: 'active', content: structuredClone(samples[scenario]), ...(scenario === 'structure' ? { previousIdeas: structuredClone(samples.ideas) as Extract<TeacherDiscussionContent, { kind: 'ideas' }> } : {}) } } : {}) };
const stream = Object.assign(new EventTarget(), { close() {}, onerror: null, onopen: null });
let timer: ReturnType<typeof setTimeout> | undefined;
const snapshot = () => { current.revision++; stream.dispatchEvent(new MessageEvent('snapshot', { data: JSON.stringify(current) })); };
export const teacherApi = {
config: async () => ({ enabled: true, definition }),
list: async () => ({ items: [{ id: current.id, title: '我的小狗世界' }], lastSelectedTopicId: current.id }),
read: async () => structuredClone(current),
create: async () => structuredClone(current),
events: async () => stream,
updateDiscussion: async (_base: string, _id: string, input: TeacherDiscussionAction) => {
const tool = current.discussion!;
if (input.action === 'pause' || input.action === 'finish') tool.status = input.action === 'pause' ? 'paused' : 'finished';
else tool.status = 'active';
if (input.action === 'back-ideas' && tool.previousIdeas) {
if (tool.content.kind === 'structure') tool.previousStructure = structuredClone(tool.content);
tool.content = structuredClone(tool.previousIdeas);
}
if (tool.content.kind === 'ideas') {
const item = tool.content.items.find(item => item.id === input.itemId);
if (item && input.action === 'keep-idea') item.state = 'kept';
if (item && input.action === 'aside-idea') item.state = 'aside';
if (item && input.action === 'first-idea') tool.content.firstItemId = item.id;
}
tool.revision++;
snapshot();
return structuredClone(current);
},
send: async (_base: string, _id: string, input: TeacherSend) => {
current.requests.push({ id: input.requestId, text: input.text, references: [], createdAt: 'now', status: 'running', sourceCursor: { workerGeneration: 0, seq: 1 }, sourceCapturedAt: 'now', includedSourceMessageIds: [], omittedMessages: 0, response: '', discussionContext: input.discussion });
snapshot();
timer = setTimeout(() => {
const request = current.requests.at(-1)!;
request.status = 'completed';
request.response = '好,已经把你的补充放在上面了。我们可以接着想。';
const tool = current.discussion;
if (tool?.status === 'active' && input.discussion) {
if (input.discussion.transition === 'structure' && tool.content.kind === 'ideas') {
tool.previousIdeas = structuredClone(tool.content);
tool.content = structuredClone(samples.structure);
} else if (tool.content.kind === 'ideas') tool.content.items.push({ id: `new-${tool.revision}`, text: input.text, state: 'kept' });
else if (tool.content.kind === 'structure') tool.content.nodes.push({ id: `new-${tool.revision}`, label: input.text, parentId: 'world' });
else if (tool.content.kind === 'flow') tool.content.nodes.push({ id: `new-${tool.revision}`, label: input.text, kind: 'outcome' });
else tool.content.rows.push({ id: `new-${tool.revision}`, label: '再想想这一点', cells: tool.content.columns.map(col => ({ columnId: col.id, text: '先观察实际玩的时候有什么不同。' })) });
tool.revision++;
}
snapshot();
}, 350);
return structuredClone(current);
},
cancel: async () => { clearTimeout(timer); current.requests.at(-1)!.status = 'cancelled'; snapshot(); return structuredClone(current); },
};
export const teacherTopicsPath = () => '/fixture';

View File

@@ -0,0 +1,12 @@
import { createRoot } from 'react-dom/client';
import { TeacherChatPanel } from '../../../src/pages/Chat/TeacherChatPanel';
import '../../../src/styles/globals.css';
import '../../../src/pages/Chat/classroom-workspace.css';
const width = Number(new URLSearchParams(location.search).get('width')) || 508;
createRoot(document.getElementById('root')!).render(<div className="classroom-workspace flex h-screen flex-col bg-white">
<header className="flex h-10 shrink-0 items-center border-b px-5 text-xs">老师讨论交互测试 · 真实页面组件 / 模拟回复</header>
<div className="flex min-h-0 flex-1 justify-end bg-[#f5f5f1]">
<main className="min-w-0 flex-1 p-8"><h1 className="text-lg">我的小狗世界</h1><p className="mt-4 text-sm text-muted-foreground">作品区域</p></main>
<div className="h-full shrink-0 border-l" style={{ width }}><TeacherChatPanel projectId="fixture" sourceId="source" role="teacher" /></div>
</div>
</div>);

View File

@@ -0,0 +1,70 @@
import { test, expect } from '@playwright/test';
import { createServer, type ViteDevServer } from 'vite';
import { resolve } from 'node:path';
let server: ViteDevServer;
let url: string;
test.use({ channel: process.env.MAKELORE_LAYOUT_BROWSER_CHANNEL, video: 'off' });
test.beforeAll(async () => {
server = await createServer({ configFile: false, cacheDir: 'node_modules/.vite-teacher-discussion', resolve: { alias: { '@': resolve('src') } }, esbuild: { jsx: 'automatic' }, server: { host: '127.0.0.1', port: 0 }, plugins: [{
name: 'isolated-discussion-test', enforce: 'pre',
load(id) {
if (id.endsWith('/src/lib/coding-teacher.ts')) return "export { teacherApi, teacherTopicsPath } from '/tests/e2e/fixtures/teacher-discussion-api.ts';";
if (id.endsWith('/src/stores/auth.ts')) return 'export const useAuthStore = selector => selector({user:{userId:"fixture"}});';
},
configureServer(vite) { vite.middlewares.use((req, res, next) => {
if (!req.url?.startsWith('/?') && req.url !== '/') return next();
res.setHeader('Content-Type', 'text/html');
res.end('<html><head><meta charset="utf-8"></head><body><div id="root"></div><script type="module" src="/tests/e2e/fixtures/teacher-discussion-layout.tsx"></script></body></html>');
}); },
}] });
await server.listen(); url = server.resolvedUrls!.local[0];
});
test.afterAll(async () => { await server?.close(); });
for (const width of [319, 508]) for (const kind of ['ordinary', 'ideas', 'structure', 'flow', 'comparison']) {
test(`${kind} pins the current tool and composer at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width: 1180, height: 800 });
const errors: string[] = []; page.on('pageerror', error => errors.push(error.message));
await page.goto(`${url}?kind=${kind}&width=${width}`);
const input = page.getByRole('textbox', { name: '向老师提问' });
await expect(input).toBeEnabled();
const tool = page.getByTestId('teacher-discussion');
if (kind === 'ordinary') {
await expect(tool).toHaveCount(0);
await input.fill('保留我的草稿');
await page.getByRole('button', { name: '有什么好玩的想法?' }).click();
await expect(page.getByText('好,已经把你的补充放在上面了。我们可以接着想。')).toBeVisible();
await expect(input).toHaveValue('保留我的草稿');
} else {
await expect(tool).toHaveAttribute('data-kind', kind);
const before = await tool.boundingBox();
const composer = await input.boundingBox();
await page.locator('.consultation-messages').hover();
await page.mouse.wheel(0, -1500);
await expect.poll(async () => (await tool.boundingBox())?.y).toBe(before!.y);
expect((await input.boundingBox())?.y).toBe(composer!.y);
expect(await tool.evaluate(el => el.scrollWidth <= el.clientWidth)).toBe(true);
expect(composer!.y + composer!.height).toBeLessThan(800);
await input.fill('它还喜欢和我踢球');
await page.getByRole('button', { name: '提问', exact: true }).click();
await expect(page.getByRole('status')).toContainText('正在梳理');
await expect(page.getByText('好,已经把你的补充放在上面了。我们可以接着想。')).toBeVisible();
await expect(tool).toHaveCount(1);
await expect(tool).toHaveAttribute('data-kind', kind);
if (kind === 'ideas') {
await page.getByRole('button', { name: '把想法理一理' }).click();
await expect(tool).toHaveAttribute('data-kind', 'structure');
await page.getByRole('button', { name: '回去补充想法' }).click();
await expect(tool).toHaveAttribute('data-kind', 'ideas');
await expect(tool.getByText('它还喜欢和我踢球', { exact: true })).toHaveCount(1);
}
await input.fill('先留下下一句');
await page.getByRole('button', { name: '先这些', exact: true }).click();
await expect(tool).toHaveAttribute('data-collapsed', 'true');
await expect(input).toHaveValue('先留下下一句');
await page.getByRole('button', { name: '接着改', exact: true }).click();
await expect(tool).toHaveAttribute('data-collapsed', 'false');
}
await page.screenshot({ path: test.info().outputPath(`${kind}-${width}.png`) });
expect(errors).toEqual([]);
});
}