feat: add creative welcome and external works square links

This commit is contained in:
鲨鱼辣椒
2026-09-29 15:37:37 +08:00
parent 4199cadd1e
commit f8a7880da3
18 changed files with 428 additions and 41 deletions

View File

@@ -0,0 +1,90 @@
import { test, expect } from '@playwright/test';
import { createServer, type ViteDevServer } from 'vite';
import { resolve } from 'node:path';
let server: ViteDevServer;
let baseUrl: string;
test.use({ headless: true, channel: process.env.MAKELORE_LAYOUT_BROWSER_CHANNEL, video: 'off' });
test.beforeAll(async () => {
server = await createServer({
configFile: false, cacheDir: 'node_modules/.vite-community-layout',
resolve: { alias: { '@': resolve('src') } }, esbuild: { jsx: 'automatic' },
server: { host: '127.0.0.1', port: 0 },
plugins: [{
name: 'isolated-community', enforce: 'pre',
load(id) {
if (id.endsWith('/src/lib/host-events.ts')) return 'export function subscribeHostEvent() { return () => {}; }';
if (id.endsWith('/src/lib/host-api.ts')) return `
export async function createHostEventSource() { return { close() {}, addEventListener() {} }; }
export async function ensureHostApiToken() { return 'fixture'; }
export function getHostApiBase() { return ''; }
export function reportDesktopActivity() {}
export function setDesktopBackgroundLease() {}
export async function hostApiFetch() { return {}; }
`;
},
configureServer(vite) {
vite.middlewares.use((req, res, next) => {
if (req.url !== '/' && !req.url?.startsWith('/?')) 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/community-welcome.tsx"></script></body></html>');
});
},
}],
});
await server.listen();
baseUrl = server.resolvedUrls!.local[0];
});
test.afterAll(async () => { await server?.close(); });
test.beforeEach(async ({ page }) => {
page.on('pageerror', error => { throw error; });
await page.addInitScript(() => {
const scope = window as typeof window & { __communityCalls: unknown[][] };
scope.__communityCalls = [];
Object.defineProperty(window, 'electron', { value: { ipcRenderer: {
invoke: async (...args: unknown[]) => { scope.__communityCalls.push(args); return undefined; },
} } });
});
});
for (const width of [375, 768, 1280, 1470]) {
test(`welcome, composer and community link clear teacher introductions at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 850 });
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.goto(baseUrl + '?teachers');
const heading = page.getByTestId('coding-start-heading');
const teachers = page.getByTestId('teacher-welcomes');
await expect(teachers.locator('.teacher-welcome-card')).toHaveCount(2);
await expect.poll(async () => {
const a = await heading.boundingBox(), b = await teachers.boundingBox();
return !!a && !!b && (a.x + a.width <= b.x || a.y >= b.y + b.height);
}).toBe(true);
await expect(page.locator('.coding-start-mark')).toHaveCSS('animation-name', 'none');
await page.getByTestId('community-invitation').scrollIntoViewIfNeeded();
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width);
await expect(page.getByRole('button', { name: '去作品广场逛逛' })).toBeVisible();
await teachers.getByRole('button', { name: '先自己试试' }).click();
await heading.scrollIntoViewIfNeeded();
await page.screenshot({ path: test.info().outputPath(`community-welcome-${width}.png`) });
});
}
test('the community link opens only on click and leaves the draft mounted', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 850 });
const communityRequests: string[] = [];
page.on('request', request => { if (request.url().includes('square.nianxx.cn')) communityRequests.push(request.url()); });
await page.goto(baseUrl);
const composer = page.getByRole('textbox');
await composer.fill('我想做一个自己的小镇');
await composer.evaluate(node => node.setAttribute('data-mounted', 'same'));
await page.getByRole('button', { name: '去作品广场逛逛' }).click();
expect(await page.evaluate(() => (window as typeof window & { __communityCalls: unknown[][] }).__communityCalls))
.toContainEqual(['shell:openExternal', 'https://square.nianxx.cn/#explore']);
expect(communityRequests).toEqual([]);
await expect(page.locator('iframe')).toHaveCount(0);
await expect(composer).toHaveValue('我想做一个自己的小镇');
await expect(composer).toHaveAttribute('data-mounted', 'same');
await page.getByRole('button', { name: '发送', exact: true }).click();
await expect(page.getByTestId('community-invitation')).toHaveCount(0);
await expect(composer).toHaveAttribute('data-mounted', 'same');
});

View File

@@ -0,0 +1,51 @@
import { useState, type ComponentProps } from 'react';
import { createRoot } from 'react-dom/client';
import { CodingChatBody } from '../../../src/pages/Chat/CodingChatBody';
import { CodingStartHeading } from '../../../src/pages/Chat/CodingStartHeading';
import { CodingComposer } from '../../../src/pages/Chat/CodingComposer';
import { TeacherCompanion } from '../../../src/pages/Chat/TeacherCompanion';
import { CommunityInvitation } from '../../../src/components/community/CommunityInvitation';
import '../../../src/styles/globals.css';
import '../../../src/pages/Chat/classroom-workspace.css';
export function Layout() {
const [bubble, setBubble] = useState<HTMLDivElement | null>(null);
const [draft, setDraft] = useState('');
const [sent, setSent] = useState(false);
const [dismissed, setDismissed] = useState<string[]>([]);
const agents = ['架构工程师-陈宗琦', '产品工程师-Alice'].map((name, index) => ({
teacher_id: String(index), version: 1, is_default: index === 0,
definition: { config_id: String(index), name, avatar_id: 'avatar-06',
description: index === 0 ? '有什么编程问题想一起讨论?' : '陪你把天马行空的点子,变成能玩、能用、眼睛一亮的小作品。' },
}));
const companion = {
agents, selectedAgent: agents[0], definition: agents[0].definition, enabled: true,
unreadAgentIds: [], invitation: null, welcome: null, loading: false, error: null, checking: false,
refreshing: false, refreshStatus: 'idle', refresh: async () => {}, reloadCatalog: async () => {}, dismiss: () => {},
welcomes: new URLSearchParams(location.search).has('teachers') ? agents.flatMap((agent, index) => dismissed.includes(agent.teacher_id)
? [] : [{ agentId: agent.teacher_id, definition: agent.definition, text: agent.definition.description, tone: index }]) : [],
dismissWelcome: (id: string) => setDismissed(values => [...values, id]),
dismissWelcomes: () => setDismissed(['0', '1']),
} as ComponentProps<typeof TeacherCompanion>['companion'];
return <div className="classroom-workspace flex h-screen flex-col bg-white">
<header className="relative z-50 flex h-12 shrink-0 items-center justify-end border-b px-3" data-testid="coding-conversation-header">
<span className="mr-auto min-w-0 truncate text-xs">测试项目 › 新对话</span>
<TeacherCompanion companion={companion} open={false} onOpen={() => {}} onToggle={() => {}} bubbleRef={setBubble} />
</header>
<main className="classroom-main flex min-h-0 min-w-0 flex-1 flex-col">
<div className="classroom-tabs" role="tablist"><button role="tab" aria-selected="true">操作对话</button><button role="tab">作品</button></div>
<CodingChatBody welcome={!sent} hidden={false} bubble={bubble}>
<div className="classroom-chat-view min-h-0 flex-1">{!sent ? <CodingStartHeading /> : <p>第一条消息已发送(测试)</p>}</div>
<div className="classroom-composer-view shrink-0">
<CodingComposer value={draft} editable canSend={Boolean(draft)} preparing={false} recovering={false}
runStatus="idle" mode="prompt" queue={{ items: [] }} error={null} recoverableError={false}
attachments={[]} submitting={false} placeholder="说说你的想法,接下来想做什么?" onChange={setDraft}
onModeChange={() => {}} onSubmit={() => { setSent(true); setDraft(''); }} onRecover={() => {}}
onAddFiles={() => {}} onRemoveAttachment={() => {}} />
</div>
{!sent && <CommunityInvitation />}
</CodingChatBody>
</main>
</div>;
}
createRoot(document.getElementById('root')!).render(<Layout />);

View File

@@ -1121,10 +1121,25 @@ test('first PI Conversation is editable under 500 ms and submits before runtime
buffer: largePng,
});
await composer.fill('Build the first PI scene');
await electronApp.evaluate(({ shell }) => {
const scope = globalThis as typeof globalThis & { __communityOpened?: string[] };
scope.__communityOpened = [];
shell.openExternal = async url => { scope.__communityOpened!.push(url); };
});
await page.getByRole('button', { name: '作品广场', exact: true }).click();
await page.getByRole('button', { name: '去作品广场逛逛' }).click();
await expect.poll(() => electronApp.evaluate(() => (
(globalThis as typeof globalThis & { __communityOpened?: string[] }).__communityOpened
))).toEqual(['https://square.nianxx.cn/#explore', 'https://square.nianxx.cn/#explore']);
await expect(composer).toHaveValue('Build the first PI scene');
await expect(page.getByText('large.png', { exact: true })).toBeVisible();
await expect(page.getByRole('dialog')).toHaveCount(0);
expect((await readState(electronApp)).captured.filter(item => item.path.endsWith('/prompt') && item.method === 'POST')).toHaveLength(0);
await expect(page.getByRole('button', { name: '发送' })).toBeEnabled();
await page.getByTestId('coding-message-composer').evaluate(
(form: HTMLFormElement) => form.requestSubmit(),
);
await expect(page.getByTestId('community-invitation')).toHaveCount(0);
await expect.poll(async () => {
const state = await readState(electronApp);
@@ -1869,7 +1884,7 @@ test('project consultations preserve student drafts and switch between work and
await expect(page.getByRole('button', { name: '与朋友聊天' })).toHaveAttribute('aria-pressed', 'true');
await expect(page.locator('#coding-consultation-dock')).toHaveCSS('width', '508px');
await expect(teacher.locator('form .consultation-hint')).toBeVisible();
await expect(teacher.locator('form .consultation-hint')).toHaveText('不知道问什么,你先帮我看看👀');
await expect(teacher.locator('form .consultation-hint')).toHaveText('帮我整体看🧠');
await expect(teacher.getByText('把你的困惑说出来就好')).toHaveCount(0);
await expect(teacher.getByText('当前项目',{exact:true})).toHaveCount(0);
await expect(teacher.getByRole('button',{name:'解释当前代码',exact:true})).toBeVisible();
@@ -1924,7 +1939,7 @@ test('project consultations preserve student drafts and switch between work and
expect(request.body).not.toHaveProperty('discussion');
}
await expect(teacher).toHaveAccessibleName('朋友咨询');
expect(consultationRequests[0].body).toMatchObject({intent:'suggestions',text:'不知道问什么,你先帮我看看👀'});
expect(consultationRequests[0].body).toMatchObject({intent:'suggestions',text:'帮我整体看🧠'});
expect(consultationRequests[1].body).toMatchObject({text:'怎样观察别人玩游戏?'});
expect(consultationRequests[1].body?.intent).toBeUndefined();
await page.screenshot({path:test.info().outputPath('project-teacher-side-chat.png')});

View File

@@ -29,7 +29,7 @@ test('retry stickers stay readable and preserve drafts in a 319px consultation',
const panel = page.getByTestId('teacher-chat-panel');
const retry = panel.locator('.consultation-retry');
await expect(retry).toBeEnabled();
await expect(retry).toHaveText('不知道问什么,你先帮我看看👀');
await expect(retry).toHaveText('帮我整体看🧠');
expect(await retry.evaluate(el => el.scrollWidth <= el.clientWidth)).toBe(true);
const [panelBounds, retryBounds] = await Promise.all([panel.boundingBox(), retry.boundingBox()]);
expect(retryBounds!.x).toBeGreaterThanOrEqual(panelBounds!.x);
@@ -41,7 +41,7 @@ test('retry stickers stay readable and preserve drafts in a 319px consultation',
await expect(page.getByText('我们可以先从一个小地方开始。')).toBeVisible();
await expect(input).toHaveValue('我还有一点自己的想法');
expect(await page.evaluate(() => (window as unknown as { __teacherReplyInputs: unknown[] }).__teacherReplyInputs)).toEqual([
{ requestId: expect.any(String), text: '不知道问什么,你先帮我看看👀', intent: 'suggestions', references: [], projectId: 'fixture', sourceConversationId: 'source' },
{ requestId: expect.any(String), text: '帮我整体看🧠', intent: 'suggestions', references: [], projectId: 'fixture', sourceConversationId: 'source' },
]);
}
});
@@ -89,7 +89,7 @@ for (const width of [319, 508]) {
const send = page.getByRole('button', { name: '提问', exact: true });
const sent = () => page.evaluate(() => (window as unknown as { __teacherReplyInputs: unknown[] }).__teacherReplyInputs);
await expect(hint).toBeEnabled();
await expect(hint).toHaveText('不知道问什么,你先帮我看看👀');
await expect(hint).toHaveText('帮我整体看🧠');
expect(await hint.evaluate(el => el.scrollWidth <= el.clientWidth && el.scrollHeight <= el.clientHeight)).toBe(true);
await expect(hint).toHaveCSS('background-color', 'rgb(255, 242, 201)');
const initialSend = (await send.boundingBox())!;
@@ -110,9 +110,9 @@ for (const width of [319, 508]) {
expect(await sent()).toEqual([]);
await hint.click();
await expect(page.getByText('我们可以先从一个小地方开始。')).toBeVisible();
expect(await sent()).toEqual([{ requestId: expect.any(String), text: '不知道问什么,你先帮我看看👀', intent: 'suggestions', references: [], projectId: 'fixture', sourceConversationId: 'source' }]);
expect(await sent()).toEqual([{ requestId: expect.any(String), text: '帮我整体看🧠', intent: 'suggestions', references: [], projectId: 'fixture', sourceConversationId: 'source' }]);
await expect(page.getByRole('button', { name: '我也说不清,你带我看看', exact: true })).toHaveCount(0);
await expect(page.locator('.consultation-messages').getByRole('button', { name: '不知道问什么,你先帮我看看👀', exact: true })).toHaveCount(0);
await expect(page.locator('.consultation-messages').getByRole('button', { name: '帮我整体看🧠', exact: true })).toHaveCount(0);
const card = page.getByRole('button', { name: '可以从哪个小地方开始?' });
await expect(card).toBeVisible();
await input.fill('留着我自己的草稿');