Skip to content

AI-native design editor. Open-source Figma alternative.

test(chat): extract browser harness

Danila Poyarkovc3a560d2b901
diff --git a/tests/e2e/chat/panel.spec.ts b/tests/e2e/chat/panel.spec.ts
index 180390524..828c63046 100644
--- a/tests/e2e/chat/panel.spec.ts
+++ b/tests/e2e/chat/panel.spec.ts
@@ -1,168 +1,40 @@
import { expect, test, type Page } from '@playwright/test'
-import { CanvasHelper } from '#tests/helpers/canvas'
+import {
+ apiKeyInput as getAPIKeyInput,
+ chatInput as getChatInput,
+ chatTab as getChatTab,
+ designTab as getDesignTab,
+ openChatTestApp,
+ USE_REAL_LLM
+} from '#tests/helpers/chat/app'
-const USE_REAL_LLM = process.env.TEST_REAL_LLM === '1'
-const OPENROUTER_KEY = process.env.OPENROUTER_API_KEY ?? ''
+test.describe.configure({ mode: 'serial' })
let page: Page
-let canvas: CanvasHelper
-
-test.describe.configure({ mode: 'serial' })
test.beforeAll(async ({ browser }) => {
- page = await browser.newPage()
- await page.goto('/')
- await page.evaluate(async () => {
- const themeModulePath = '/src/app/shell/theme.ts'
- const themeModule = await import(themeModulePath)
- themeModule.useAppTheme().setTheme('dark')
- })
- await page.waitForFunction(() => document.documentElement.dataset.theme === 'dark')
- canvas = new CanvasHelper(page)
- await canvas.waitForInit()
-
- if (!USE_REAL_LLM) {
- await injectMockTransport(page)
- }
+ ;({ page } = await openChatTestApp(browser))
})
test.afterAll(async () => {
await page.close()
})
-async function injectMockTransport(page: Page) {
- await page.evaluate(() => {
- const setChatTransport = window.openPencil?.setChatTransport
- if (!setChatTransport) throw new Error('Transport override not available')
-
- let msgCounter = 0
-
- setChatTransport(() => ({
- async sendMessages({
- messages
- }: {
- messages: Array<{ role: string; parts: Array<{ type: string; text?: string }> }>
- }) {
- const lastUser = [...messages].reverse().find((m) => m.role === 'user')
- const text = lastUser?.parts?.find((p) => p.type === 'text')?.text ?? ''
- const appOrigin = window.location.origin
- const msgId = `mock-msg-${++msgCounter}`
- const lowerText = text.toLowerCase()
- document.documentElement.dataset.lastChatRequest = text
- const wantsTool = lowerText.includes('frame') || lowerText.includes('rectangle')
- const wantsCode = lowerText.includes('code block')
- const wantsUnsafeMarkdown = lowerText.includes('unsafe markdown')
- const wantsMultipleParts = lowerText.includes('multiple parts')
- const wantsReasoning = lowerText.includes('reasoning')
-
- if (lowerText.includes('missing agent')) {
- throw new Error(
- '"claude-agent-acp" is not installed. Install it with: npm i -g @agentclientprotocol/claude-agent-acp'
- )
- }
-
- return new ReadableStream({
- start(controller) {
- controller.enqueue({ type: 'start', messageId: msgId })
-
- if (wantsTool) {
- const toolCallId = `call-${msgId}`
- controller.enqueue({
- type: 'tool-input-start',
- toolCallId,
- toolName: 'create_shape'
- })
- controller.enqueue({
- type: 'tool-input-delta',
- toolCallId,
- inputTextDelta:
- '{"type":"FRAME","x":100,"y":100,"width":200,"height":150,"name":"Card"}'
- })
- controller.enqueue({
- type: 'tool-input-available',
- toolCallId,
- toolName: 'create_shape',
- input: { type: 'FRAME', x: 100, y: 100, width: 200, height: 150, name: 'Card' }
- })
- controller.enqueue({
- type: 'tool-output-available',
- toolCallId,
- toolName: 'create_shape',
- output: {
- id: '0:99',
- type: 'FRAME',
- x: 100,
- y: 100,
- width: 200,
- height: 150,
- name: 'Card'
- }
- })
- }
-
- if (wantsReasoning) {
- controller.enqueue({ type: 'reasoning-start', id: 'reasoning-1' })
- controller.enqueue({
- type: 'reasoning-delta',
- id: 'reasoning-1',
- delta: 'Inspecting the referenced layout.'
- })
- controller.enqueue({ type: 'reasoning-end', id: 'reasoning-1' })
- }
-
- if (wantsMultipleParts) {
- controller.enqueue({ type: 'text-start', id: 'text-a' })
- controller.enqueue({ type: 'text-delta', id: 'text-a', delta: 'First' })
- controller.enqueue({ type: 'text-end', id: 'text-a' })
- controller.enqueue({ type: 'text-start', id: 'text-b' })
- controller.enqueue({ type: 'text-delta', id: 'text-b', delta: 'Second' })
- controller.enqueue({ type: 'text-end', id: 'text-b' })
- controller.enqueue({ type: 'finish', finishReason: 'stop' })
- controller.close()
- return
- }
-
- let words: string[]
- if (wantsTool) words = ['Created', 'a', 'frame', 'called', '"Card".']
- else if (wantsUnsafeMarkdown) {
- words = [
- `[unsafe](javascript:alert(1)) ![embedded](data:image/svg+xml,<svg onload=alert(1)></svg>) ![approved](${appOrigin}/assets/approved.png) ![unapproved](https://example.com/unapproved.png) ![insecure](http://example.com/insecure.png) [safe](https://openpencil.dev)`
- ]
- } else if (wantsCode) words = ['```typescript\nconst greeting = "Hello"\n```']
- else words = `I'll help you with: "${text}". Here's a mock response.`.split(' ')
-
- controller.enqueue({ type: 'text-start', id: 'text-1' })
- for (const word of words) {
- controller.enqueue({ type: 'text-delta', id: 'text-1', delta: word + ' ' })
- }
- controller.enqueue({ type: 'text-end', id: 'text-1' })
- controller.enqueue({ type: 'finish', finishReason: 'stop' })
- controller.close()
- }
- })
- },
- async reconnectToStream() {
- return null
- }
- }))
- })
-}
-
function chatTab() {
- return page.getByRole('tab', { name: 'AI' })
+ return getChatTab(page)
}
function designTab() {
- return page.getByRole('tab', { name: 'Design' })
+ return getDesignTab(page)
}
function chatInput() {
- return page.getByRole('textbox', { name: 'Describe a change' })
+ return getChatInput(page)
}
function apiKeyInput() {
- return page.getByTestId('provider-settings-api-key')
+ return getAPIKeyInput(page)
}
test('⌘J switches to AI tab', async () => {
@@ -184,7 +56,7 @@ test('clicking AI tab directs provider setup to unified settings', async () => {
})
test('saving API key in unified settings shows chat interface', async () => {
- const key = USE_REAL_LLM ? OPENROUTER_KEY : 'sk-or-test-key-12345'
+ const key = USE_REAL_LLM ? (process.env.OPENROUTER_API_KEY ?? '') : 'sk-or-test-key-12345'
await page.getByTestId('provider-setup-open-settings').click()
await expect(page.getByTestId('app-settings-dialog')).toBeVisible()
await expect(page.getByTestId('settings-remember-credentials')).toHaveAttribute(
diff --git a/tests/helpers/chat/app.ts b/tests/helpers/chat/app.ts
new file mode 100644
index 000000000..07403c99e
--- /dev/null
+++ b/tests/helpers/chat/app.ts
@@ -0,0 +1,59 @@
+import type { Browser, Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+import { injectMockChatTransport } from '#tests/helpers/chat/transport'
+
+const USE_REAL_LLM = process.env.TEST_REAL_LLM === '1'
+const OPENROUTER_KEY = process.env.OPENROUTER_API_KEY ?? ''
+
+export interface ChatTestApp {
+ page: Page
+ canvas: CanvasHelper
+}
+
+export async function openChatTestApp(browser: Browser): Promise<ChatTestApp> {
+ const page = await browser.newPage()
+ await page.goto('/')
+ await page.evaluate(async () => {
+ const themeModulePath = '/src/app/shell/theme.ts'
+ const themeModule = await import(themeModulePath)
+ themeModule.useAppTheme().setTheme('dark')
+ })
+ await page.waitForFunction(() => document.documentElement.dataset.theme === 'dark')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ if (!USE_REAL_LLM) await injectMockChatTransport(page)
+ return { page, canvas }
+}
+
+export function chatInput(page: Page) {
+ return page.getByRole('textbox', { name: 'Describe a change' })
+}
+
+export function chatTab(page: Page) {
+ return page.getByRole('tab', { name: 'AI' })
+}
+
+export function designTab(page: Page) {
+ return page.getByRole('tab', { name: 'Design' })
+}
+
+export function apiKeyInput(page: Page) {
+ return page.getByTestId('provider-settings-api-key')
+}
+
+export async function configureChat(page: Page): Promise<void> {
+ const key = USE_REAL_LLM ? OPENROUTER_KEY : 'sk-or-test-key-12345'
+ await chatTab(page).click()
+ await page.getByTestId('provider-setup-open-settings').click()
+ await page.locator('[data-model-id]').first().click()
+ await page.getByTestId('settings-model-provider').click()
+ await page.getByRole('option', { name: 'OpenRouter' }).click()
+ await page.getByLabel('Name').fill('Claude Sonnet')
+ await apiKeyInput(page).fill(key)
+ await page.getByRole('button', { name: 'Save model' }).click()
+ await page.getByTestId('app-settings-done').click()
+ await chatInput(page).waitFor()
+}
+
+export { USE_REAL_LLM }
diff --git a/tests/helpers/chat/transport.ts b/tests/helpers/chat/transport.ts
new file mode 100644
index 000000000..c1b1fcdcc
--- /dev/null
+++ b/tests/helpers/chat/transport.ts
@@ -0,0 +1,106 @@
+import type { Page } from '@playwright/test'
+
+export async function injectMockChatTransport(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const setChatTransport = window.openPencil?.setChatTransport
+ if (!setChatTransport) throw new Error('Transport override not available')
+ let messageCounter = 0
+
+ setChatTransport(() => ({
+ async sendMessages({
+ messages
+ }: {
+ messages: Array<{ role: string; parts: Array<{ type: string; text?: string }> }>
+ }) {
+ const lastUser = [...messages].reverse().find((message) => message.role === 'user')
+ const text = lastUser?.parts?.find((part) => part.type === 'text')?.text ?? ''
+ const messageId = `mock-msg-${++messageCounter}`
+ const normalized = text.toLowerCase()
+ document.documentElement.dataset.lastChatRequest = text
+ const tool = normalized.includes('frame') || normalized.includes('rectangle')
+ const code = normalized.includes('code block')
+ const unsafeMarkdown = normalized.includes('unsafe markdown')
+ const multipleParts = normalized.includes('multiple parts')
+ const reasoning = normalized.includes('reasoning')
+
+ if (normalized.includes('missing agent')) {
+ throw new Error('Mock agent unavailable')
+ }
+
+ return new ReadableStream({
+ start(controller) {
+ controller.enqueue({ type: 'start', messageId })
+ if (tool) enqueueToolCall(controller, messageId)
+ if (reasoning) enqueueReasoning(controller)
+ if (multipleParts) {
+ enqueueMultipleTextParts(controller)
+ return
+ }
+ let response = `I'll help you with: "${text}". Here's a mock response.`
+ if (tool) response = 'Created a frame called "Card".'
+ else if (unsafeMarkdown) {
+ response = `[unsafe](javascript:alert(1)) ![embedded](data:image/svg+xml,<svg onload=alert(1)></svg>) ![approved](${window.location.origin}/assets/approved.png) ![unapproved](https://example.com/unapproved.png) ![insecure](http://example.com/insecure.png) [safe](https://openpencil.dev)`
+ } else if (code) response = '```typescript\nconst greeting = "Hello"\n```'
+ enqueueText(controller, response)
+ }
+ })
+ },
+ async reconnectToStream() {
+ return null
+ }
+ }))
+
+ function enqueueText(controller: ReadableStreamDefaultController, text: string): void {
+ controller.enqueue({ type: 'text-start', id: 'text-1' })
+ controller.enqueue({ type: 'text-delta', id: 'text-1', delta: text })
+ controller.enqueue({ type: 'text-end', id: 'text-1' })
+ controller.enqueue({ type: 'finish', finishReason: 'stop' })
+ controller.close()
+ }
+
+ function enqueueReasoning(controller: ReadableStreamDefaultController): void {
+ controller.enqueue({ type: 'reasoning-start', id: 'reasoning-1' })
+ controller.enqueue({
+ type: 'reasoning-delta',
+ id: 'reasoning-1',
+ delta: 'Inspecting the referenced layout.'
+ })
+ controller.enqueue({ type: 'reasoning-end', id: 'reasoning-1' })
+ }
+
+ function enqueueMultipleTextParts(controller: ReadableStreamDefaultController): void {
+ for (const [id, delta] of [
+ ['text-a', 'First'],
+ ['text-b', 'Second']
+ ]) {
+ controller.enqueue({ type: 'text-start', id })
+ controller.enqueue({ type: 'text-delta', id, delta })
+ controller.enqueue({ type: 'text-end', id })
+ }
+ controller.enqueue({ type: 'finish', finishReason: 'stop' })
+ controller.close()
+ }
+
+ function enqueueToolCall(controller: ReadableStreamDefaultController, messageId: string): void {
+ const toolCallId = `call-${messageId}`
+ controller.enqueue({ type: 'tool-input-start', toolCallId, toolName: 'create_shape' })
+ controller.enqueue({
+ type: 'tool-input-delta',
+ toolCallId,
+ inputTextDelta: '{"type":"FRAME","x":100,"y":100,"width":200,"height":150,"name":"Card"}'
+ })
+ controller.enqueue({
+ type: 'tool-input-available',
+ toolCallId,
+ toolName: 'create_shape',
+ input: { type: 'FRAME', x: 100, y: 100, width: 200, height: 150, name: 'Card' }
+ })
+ controller.enqueue({
+ type: 'tool-output-available',
+ toolCallId,
+ toolName: 'create_shape',
+ output: { id: '0:99', type: 'FRAME', name: 'Card' }
+ })
+ }
+ })
+}