snapshot of https://github.com/toeverything/AFFiNE.git (canary, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Build & Test / Analyze (javascript, affine) (push) Failing after 4s
Build & Test / Analyze (typescript, affine) (push) Failing after 3s
Build & Test / Rust test filter (push) Failing after 4s
Build & Test / Check yarn binary (push) Failing after 3s
Build & Test / E2E BlockSuite Test (3) (push) Failing after 3s
Build & Test / Analyze (javascript, blocksuite) (push) Failing after 3s
Build & Test / Analyze (typescript, blocksuite) (push) Failing after 3s
Build & Test / Mobile native build filter (push) Failing after 3s
Build & Test / E2E BlockSuite Test (1) (push) Failing after 4s
Build & Test / E2E BlockSuite Test (2) (push) Failing after 4s
Build & Test / E2E Mobile Test (1) (push) Failing after 3s
Build & Test / Unit Test (1) (push) Has been skipped
Build & Test / Unit Test (2) (push) Has been skipped
Build & Test / Unit Test (3) (push) Has been skipped
Build & Test / Unit Test (4) (push) Has been skipped
Build & Test / Unit Test (5) (push) Has been skipped
Build & Test / Native Unit Test (push) Has been skipped
Build & Test / E2E BlockSuite Test (4) (push) Failing after 3s
Build & Test / E2E BlockSuite Test (5) (push) Failing after 3s
Build & Test / E2E BlockSuite Cross Browser Test (push) Failing after 3s
Build & Test / E2E Mobile Test (2) (push) Failing after 3s
Build & Test / Build AFFiNE native (x86_64-unknown-linux-gnu) (push) Failing after 3s
Build & Test / Build Server native (push) Failing after 3s
Build & Test / Check Git Status (push) Has been skipped
Build & Test / Server Test (0, 4) (push) Has been skipped
Build & Test / Server Test (1, 4) (push) Has been skipped
Build & Test / Server Test (2, 4) (push) Has been skipped
Build & Test / Server Test (3, 4) (push) Has been skipped
Build & Test / Server Test with Elasticsearch (push) Has been skipped
Build & Test / Build @affine/electron renderer (push) Failing after 3s
Build & Test / Copilot test filter (push) Failing after 4s
Build & Test / Lint Rust (push) Has been skipped
Build & Test / Server Test with Embedded Search (push) Has been skipped
Build & Test / Server Test with Manticore Search (push) Has been skipped
Build & Test / Server E2E Test (push) Has been skipped
Build & Test / Cloud Desktop E2E Test (push) Has been skipped
Build & Test / Cloud E2E Test 1/2 (push) Has been skipped
Build & Test / Cloud E2E Test 2/2 (push) Has been skipped
Build & Test / Build Android app (push) Has been skipped
Build & Test / Test Android app (push) Has been skipped
Build & Test / Run native tests (push) Has been skipped
Build & Test / Server Copilot Api Test (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (1, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (2, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (3, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (4, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (5, 5) (push) Has been skipped
Release / Canary Gate (push) Has been skipped
Build & Test / Build AFFiNE native (aarch64-apple-darwin) (push) Has been cancelled
Build & Test / Lint (push) Has been cancelled
Build & Test / Typecheck (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-apple-darwin) (push) Has been cancelled
Build & Test / Desktop Test (ubuntu-latest, linux, x64, x86_64-unknown-linux-gnu, true) (push) Has been cancelled
Build & Test / Desktop Test (windows-latest, windows, x64, x86_64-pc-windows-msvc, true) (push) Has been cancelled
Build & Test / E2E Test (1) (push) Has been cancelled
Build & Test / E2E Test (2) (push) Has been cancelled
Build & Test / E2E Test (3) (push) Has been cancelled
Build & Test / E2E Test (4) (push) Has been cancelled
Build & Test / E2E Test (5) (push) Has been cancelled
Build & Test / Build AFFiNE native (aarch64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, arm64, aarch64-apple-darwin, true) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, x64, x86_64-apple-darwin, false) (push) Has been cancelled
Build & Test / 3, 2, 1 Launch (push) Has been cancelled
Build & Test / Build iOS app (push) Has been cancelled
Copilot Test Automatically / Setup Test (push) Failing after 1s
Release / Prepare (push) Failing after 2s
Release / Release Cloud (push) Has been skipped
Release / Release Desktop (push) Has been skipped
Release / Release Docker Image (push) Has been skipped
Release / Release Mobile (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-16 04:01:20 +05:00
commit 702cc698a7
9990 changed files with 1073618 additions and 0 deletions

View File

@@ -0,0 +1,393 @@
// oxlint-disable unicorn/prefer-dom-node-dataset
import type { Page } from '@playwright/test';
import { expect } from '@playwright/test';
type ChatStatus = 'loading' | 'success' | 'error' | 'idle' | 'transmitting';
type ChatUserMessage = {
role: 'user';
content: string;
};
type ChatAssistantMessage = {
role: 'assistant';
status: ChatStatus;
title: string;
content: string;
};
type ChatActionMessage = {
role: 'action';
title: string;
content: string;
};
type ChatMessage = ChatUserMessage | ChatAssistantMessage | ChatActionMessage;
export class ChatPanelUtils {
public static async openChatPanel(page: Page) {
if (await page.getByTestId('sidebar-tab-chat').isHidden()) {
await page.getByTestId('right-sidebar-toggle').click({
delay: 200,
});
await page.waitForTimeout(500); // wait the sidebar stable
}
await page.getByTestId('sidebar-tab-chat').click();
await expect(page.getByTestId('sidebar-tab-content-chat')).toBeVisible();
}
public static async closeChatPanel(page: Page) {
await page.getByTestId('right-sidebar-close').click({
delay: 200,
});
await expect(page.getByTestId('sidebar-tab-content-chat')).toBeHidden();
}
public static async typeChat(page: Page, content: string) {
await page.getByTestId('chat-panel-input').focus();
await page.keyboard.type(content);
}
public static async typeChatSequentially(page: Page, content: string) {
const input = await page.locator('chat-panel-input textarea').nth(0);
await input.pressSequentially(content, {
delay: 50,
});
}
public static async makeChat(page: Page, content: string) {
await this.typeChat(page, content);
await page.keyboard.press('Enter');
}
public static async clearChat(page: Page) {
await page.getByTestId('chat-panel-clear').click();
await page.getByTestId('confirm-modal-confirm').click();
await page.waitForTimeout(500);
}
public static async collectHistory(page: Page) {
const selectors =
':is(chat-message-user,chat-message-assistant,chat-message-action,[data-testid="chat-message-user"],[data-testid="chat-message-assistant"],[data-testid="chat-message-action"])';
const messages = page.locator(selectors);
const count = await messages.count();
if (!count) return [] as ChatMessage[];
const history: ChatMessage[] = [];
for (let i = 0; i < count; i++) {
const message = messages.nth(i);
const testId = await message.getAttribute('data-testid');
const tag = await message.evaluate(el => el.tagName.toLowerCase());
const isAssistant =
testId === 'chat-message-assistant' || tag === 'chat-message-assistant';
const isAction =
testId === 'chat-message-action' || tag === 'chat-message-action';
const isUser =
testId === 'chat-message-user' || tag === 'chat-message-user';
if (!isAssistant && !isAction && !isUser) continue;
const titleNode = message.locator('.user-info').first();
const title =
(await titleNode.count()) > 0 ? await titleNode.innerText() : '';
if (isUser) {
const pureText = message.getByTestId('chat-content-pure-text').first();
const content =
(await pureText.count()) > 0
? await pureText.innerText()
: ((await message.innerText()) ?? '');
history.push({ role: 'user', content });
continue;
}
const richText = message.locator('chat-content-rich-text editor-host');
const richContent =
(await richText.count()) > 0
? (await richText.allInnerTexts()).join(' ')
: '';
const content = richContent || ((await message.innerText()) ?? '').trim();
if (isAssistant) {
const inferredStatus = (await message
.getByTestId('ai-loading')
.isVisible()
.catch(() => false))
? 'transmitting'
: content
? 'success'
: 'idle';
history.push({
role: 'assistant',
status: ((await message.getAttribute('data-status')) ??
inferredStatus) as ChatStatus,
title,
content,
});
continue;
}
history.push({ role: 'action', title, content });
}
return history;
}
private static expectHistory(
history: ChatMessage[],
expected: (
| Partial<ChatUserMessage>
| Partial<ChatAssistantMessage>
| Partial<ChatActionMessage>
)[]
) {
expect(history).toHaveLength(expected.length);
const assistantStage = {
loading: 1,
transmitting: 1,
success: 2,
} as const;
history.forEach((message, index) => {
const expectedMessage = expected[index];
if (
message.role === 'assistant' &&
expectedMessage?.role === 'assistant' &&
expectedMessage.status
) {
const expectedStatus = expectedMessage.status;
if (
expectedStatus in assistantStage &&
message.status in assistantStage
) {
expect(
assistantStage[message.status as keyof typeof assistantStage]
).toBeGreaterThanOrEqual(
assistantStage[expectedStatus as keyof typeof assistantStage]
);
const { status: _status, ...expectedRest } = expectedMessage;
expect(message).toMatchObject(expectedRest);
return;
}
}
expect(message).toMatchObject(expectedMessage);
});
}
public static async expectToHaveHistory(
page: Page,
expected: (
| Partial<ChatUserMessage>
| Partial<ChatAssistantMessage>
| Partial<ChatActionMessage>
)[]
) {
const history = await this.collectHistory(page);
this.expectHistory(history, expected);
}
public static async waitForHistory(
page: Page,
expected: (
| Partial<ChatUserMessage>
| Partial<ChatAssistantMessage>
| Partial<ChatActionMessage>
)[],
timeout = 2 * 60000
) {
await expect(async () => {
const history = await this.collectHistory(page);
this.expectHistory(history, expected);
}).toPass({ timeout });
}
public static async getLatestAssistantMessage(page: Page) {
const message = page.getByTestId('chat-message-assistant').last();
const actions = await message.getByTestId('chat-actions');
const actionList = await message.getByTestId('chat-action-list');
return {
message,
content: (
await message
.locator('chat-content-rich-text editor-host')
.allInnerTexts()
).join(' '),
actions: {
copy: async () => actions.getByTestId('action-copy-button').click(),
retry: async () => actions.getByTestId('action-retry-button').click(),
insert: async () => actionList.getByTestId('action-insert').click(),
saveAsBlock: async () =>
actionList.getByTestId('action-save-as-block').click(),
saveAsDoc: async () =>
actionList.getByTestId('action-save-as-doc').click(),
addAsNote: async () =>
actionList.getByTestId('action-add-to-edgeless-as-note').click(),
},
};
}
public static async getLatestAIActionMessage(page: Page) {
const message = page.getByTestId('chat-message-action').last();
const actionName = await message.getByTestId('action-name');
await actionName.click();
const answer = await message.getByTestId('answer-prompt');
const prompt = await message.getByTestId('chat-message-action-prompt');
return {
message,
answer,
prompt,
actionName,
};
}
public static async chatWithDoc(page: Page, docName: string) {
const withButton = page.getByTestId('chat-panel-with-button');
await withButton.hover();
await withButton.click({ delay: 200 });
const withMenu = page.getByTestId('ai-add-popover');
await withMenu.waitFor({ state: 'visible' });
await withMenu.getByText(docName).click();
await page.getByTestId('chat-panel-chips').getByText(docName);
}
public static async chatWithAttachments(
page: Page,
attachments: { name: string; mimeType: string; buffer: Buffer }[],
text: string
) {
await page.evaluate(() => {
delete window.showOpenFilePicker;
});
for (const attachment of attachments) {
const fileChooserPromise = page.waitForEvent('filechooser');
const withButton = page.getByTestId('chat-panel-with-button');
await withButton.hover();
await withButton.click({ delay: 200 });
const withMenu = page.getByTestId('ai-add-popover');
await withMenu.waitFor({ state: 'visible' });
await withMenu.getByTestId('ai-chat-with-files').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(attachment);
await expect(async () => {
const states = await page
.getByTestId('chat-panel-chip')
.evaluateAll(elements => elements.map(el => el.dataset.state));
expect(states.every(state => state === 'finished')).toBe(true);
}).toPass({ timeout: 20000 });
}
await expect(async () => {
const states = await page
.getByTestId('chat-panel-chip')
.evaluateAll(elements => elements.map(el => el.dataset.state));
expect(states).toHaveLength(attachments.length);
expect(states.every(state => state === 'finished')).toBe(true);
}).toPass({ timeout: 20000 });
await this.makeChat(page, text);
}
public static async uploadImages(
page: Page,
images: { name: string; mimeType: string; buffer: Buffer }[]
) {
await page.evaluate(() => {
delete window.showOpenFilePicker;
});
const fileChooserPromise = page.waitForEvent('filechooser');
const withButton = page.getByTestId('chat-panel-with-button');
await withButton.hover();
await withButton.click({ delay: 200 });
const withMenu = page.getByTestId('ai-add-popover');
await withMenu.waitFor({ state: 'visible' });
await withMenu.getByTestId('ai-chat-with-images').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(images);
}
public static async chatWithImages(
page: Page,
images: { name: string; mimeType: string; buffer: Buffer }[],
text: string
) {
await this.uploadImages(page, images);
await page.waitForSelector('ai-chat-input .image-container');
await this.makeChat(page, text);
}
public static async chatWithTags(page: Page, tags: string[]) {
for (const tag of tags) {
const withButton = page.getByTestId('chat-panel-with-button');
await withButton.hover();
await withButton.click({ delay: 200 });
const withMenu = page.getByTestId('ai-add-popover');
await withMenu.waitFor({ state: 'visible' });
await withMenu.getByTestId('ai-chat-with-tags').click();
await withMenu.getByText(tag).click();
await page.getByTestId('chat-panel-chips').getByText(tag);
await this.waitForEmbeddingProgress(page);
await withMenu.waitFor({
state: 'hidden',
});
}
}
public static async chatWithCollections(page: Page, collections: string[]) {
for (const collection of collections) {
const withButton = page.getByTestId('chat-panel-with-button');
await withButton.hover();
await withButton.click({ delay: 200 });
const withMenu = page.getByTestId('ai-add-popover');
await withMenu.waitFor({ state: 'visible' });
await withMenu.getByTestId('ai-chat-with-collections').click();
await withMenu.getByText(collection).click();
await page.getByTestId('chat-panel-chips').getByText(collection);
await this.waitForEmbeddingProgress(page);
await withMenu.waitFor({
state: 'hidden',
});
}
}
public static async waitForEmbeddingProgress(page: Page) {
try {
await page.getByTestId('chat-panel-embedding-progress').waitFor({
state: 'visible',
});
await page.getByTestId('chat-panel-embedding-progress').waitFor({
state: 'hidden',
});
} catch {
// do nothing
}
}
public static async openChatInputPreference(page: Page) {
const trigger = page.getByTestId('chat-input-preference-trigger');
await trigger.click();
await page.getByTestId('chat-input-preference').waitFor({
state: 'visible',
});
}
public static async enableReasoning(page: Page) {
await this.openChatInputPreference(page);
const reasoning = page.getByTestId('chat-reasoning');
if ((await reasoning.getAttribute('data-active')) === 'false') {
await reasoning.click();
}
}
public static async disableReasoning(page: Page) {
await this.openChatInputPreference(page);
const reasoning = page.getByTestId('chat-reasoning');
if ((await reasoning.getAttribute('data-active')) === 'true') {
await reasoning.click();
}
}
}

View File

@@ -0,0 +1,771 @@
import {
createEdgelessNoteBlock,
setEdgelessTool,
} from '@affine-test/kit/utils/editor';
import {
pressEscape,
selectAllByKeyboard,
} from '@affine-test/kit/utils/keyboard';
import {
clickNewPageButton,
getBlockSuiteEditorTitle,
} from '@affine-test/kit/utils/page-logic';
import type { EdgelessRootBlockComponent } from '@blocksuite/affine/blocks/root';
import type {
MindmapElementModel,
ShapeElementModel,
} from '@blocksuite/affine-model';
import type { GfxModel } from '@blocksuite/std/gfx';
import { type Page } from '@playwright/test';
export class EditorUtils {
public static async waitForCurrentDocSynced(page: Page) {
await page.evaluate(async () => {
const [, , workspaceId, docId] = location.pathname.split('/');
const workspace = (
window as typeof window & {
currentWorkspace?: {
engine: {
doc: {
waitForSynced(docId: string, abort: AbortSignal): Promise<void>;
};
};
};
}
).currentWorkspace;
if (!workspaceId || !docId || !workspace) {
throw new Error('Current document is unavailable');
}
const abort = AbortSignal.timeout(60_000);
await Promise.all([
workspace.engine.doc.waitForSynced(docId, abort),
workspace.engine.doc.waitForSynced('db$docProperties', abort),
]);
const response = await fetch(
`/api/workspaces/${workspaceId}/docs/${docId}`
);
if (!response.ok) {
throw new Error('Current document could not be persisted');
}
});
}
public static async focusToEditor(page: Page) {
const title = getBlockSuiteEditorTitle(page);
await title.focus();
await page.keyboard.press('Enter');
}
public static async getEditorContent(page: Page, trim = true) {
let content = '';
let retry = 3;
while (!content && retry > 0) {
const lines = await page.$$('page-editor .inline-editor');
const contents = await Promise.all(lines.map(el => el.innerText()));
content = contents
.map(c => {
const invisibleFiltered = c.replace(/[\u200B-\u200D\uFEFF]/g, '');
if (trim) {
return invisibleFiltered.trim();
}
return invisibleFiltered;
})
.filter(c => !!c)
.join('\n');
if (!content) {
await page.waitForTimeout(500);
retry -= 1;
}
}
return content;
}
public static async getNoteContent(page: Page) {
const edgelessNode = await page.waitForSelector(
'affine-edgeless-note .edgeless-note-page-content'
);
return (await edgelessNode.innerText())
.replace(/[\u200B-\u200D\uFEFF]/g, '')
.trim();
}
public static async switchToEdgelessMode(page: Page) {
const editor = await page.waitForSelector('page-editor');
await page.getByTestId('switch-edgeless-mode-button').click();
await editor.waitForElementState('hidden');
await page.waitForSelector('edgeless-editor');
}
public static async switchToPageMode(page: Page) {
await page.getByTestId('switch-page-mode-button').click();
await page.waitForSelector('page-editor');
}
public static async isPageMode(page: Page) {
return await page.waitForSelector('page-editor');
}
public static async isEdgelessMode(page: Page) {
return await page.waitForSelector('edgeless-editor');
}
public static async getDocTitle(page: Page) {
return page.getByTestId('title-edit-button').innerText();
}
public static async waitForAiAnswer(page: Page, timeout = 2 * 60000) {
const answer = page.getByTestId('ai-penel-answer').last();
await answer.waitFor({ state: 'visible', timeout });
return answer;
}
private static createAction(
page: Page,
action: () => Promise<void>,
options?: { responseTimeoutMs?: number }
) {
return async () => {
const responseTimeoutMs = options?.responseTimeoutMs ?? 60000;
await action();
await this.waitForAiAnswer(page, responseTimeoutMs);
await page.getByTestId('ai-generating').waitFor({
state: 'hidden',
timeout: responseTimeoutMs,
});
const responses = new Set<string>();
const answer = await this.waitForAiAnswer(page);
const responsesMenu = answer.getByTestId('answer-responses');
await responsesMenu.waitFor({
state: 'visible',
timeout: responseTimeoutMs,
});
await responsesMenu.scrollIntoViewIfNeeded({
timeout: responseTimeoutMs,
});
await responsesMenu
.getByTestId('answer-insert-below-loading')
.waitFor({ state: 'hidden', timeout: responseTimeoutMs });
if (await responsesMenu.getByTestId('answer-insert-below').isVisible()) {
responses.add('insert-below');
}
if (await responsesMenu.getByTestId('answer-insert-above').isVisible()) {
responses.add('insert-above');
}
if (await responsesMenu.getByTestId('answer-replace').isVisible()) {
responses.add('replace-selection');
}
if (
await responsesMenu.getByTestId('answer-use-as-caption').isVisible()
) {
responses.add('use-as-caption');
}
if (
await responsesMenu.getByTestId('answer-create-new-note').isVisible()
) {
responses.add('create-new-note');
}
return {
answer: await this.waitForAiAnswer(page),
responses,
};
};
}
public static async createEdgelessText(page: Page, text: string) {
await setEdgelessTool(page, 'text');
await page.mouse.click(400, 400);
await page.locator('affine-edgeless-text').waitFor({ state: 'visible' });
await page.waitForTimeout(100);
const texts = text.split('\n');
for (const [index, line] of texts.entries()) {
await page.keyboard.insertText(line);
if (index !== texts.length - 1) {
await page.keyboard.press('Enter');
}
}
}
public static async createEdgelessNote(page: Page, text: string) {
await createEdgelessNoteBlock(page, [500, 300]);
const texts = text.split('\n');
for (const [index, line] of texts.entries()) {
await page.keyboard.insertText(line);
if (index !== texts.length - 1) {
await page.keyboard.press('Enter');
}
}
}
public static async createMindmap(page: Page) {
await page.keyboard.press('m');
await page.mouse.click(400, 400);
const id = await page.evaluate(() => {
const edgelessBlock = document.querySelector(
'affine-edgeless-root'
) as EdgelessRootBlockComponent;
if (!edgelessBlock) {
throw new Error('edgeless block not found');
}
const mindmaps = edgelessBlock.gfx.gfxElements.filter(
(el: GfxModel) => 'type' in el && el.type === 'mindmap'
);
return mindmaps[mindmaps.length - 1].id;
});
return id;
}
public static async createShape(page: Page, text: string) {
// Create shape
await page.keyboard.press('s');
await page.mouse.click(400, 400);
const id = await page.evaluate(() => {
const edgelessBlock = document.querySelector(
'affine-edgeless-root'
) as EdgelessRootBlockComponent;
if (!edgelessBlock) {
throw new Error('edgeless block not found');
}
const shapes = edgelessBlock.gfx.gfxElements.filter(
(el: GfxModel) => 'type' in el && el.type === 'shape'
);
return shapes[shapes.length - 1].id;
});
// Insert text inside shape
await page.mouse.dblclick(450, 450);
await page.keyboard.insertText(text);
// Prevent the shape from being dragged
await page.mouse.click(500, 500);
return id;
}
public static async getMindMapNode(
page: Page,
mindmapId: string,
path: number[]
) {
return page.evaluate(
({ mindmapId, path }) => {
const edgelessBlock = document.querySelector(
'affine-edgeless-root'
) as EdgelessRootBlockComponent;
if (!edgelessBlock) {
throw new Error('edgeless block not found');
}
const mindmap = edgelessBlock.gfx.getElementById(
mindmapId
) as MindmapElementModel;
if (!mindmap) {
throw new Error(`Mindmap not found: ${mindmapId}`);
}
const node = mindmap.getNodeByPath(path);
if (!node) {
throw new Error(`Mindmap node not found at: ${path}`);
}
const rect = edgelessBlock.gfx.viewport.toViewBound(
node.element.elementBound
);
return {
path: mindmap.getPath(node),
id: node.id,
text: (node.element as ShapeElementModel).text?.toString() ?? '',
rect: {
x: rect.x,
y: rect.y,
w: rect.w,
h: rect.h,
},
};
},
{
mindmapId,
path,
}
);
}
public static async clearAllCollections(page: Page) {
while (true) {
const collection = await page
.getByTestId('navigation-panel-collections')
.locator('[data-testid^="navigation-panel-collection-"]')
.first();
if (!(await collection.isVisible())) {
break;
}
const collectionContent = await collection.locator('div').first();
await collectionContent.hover();
const more = await collectionContent.getByTestId(
'navigation-panel-tree-node-operation-button'
);
await more.click();
await page.getByTestId('collection-delete-button').click();
}
await page.waitForTimeout(100);
}
public static async clearAllTags(page: Page) {
while (true) {
const tag = await page
.getByTestId('navigation-panel-tags')
.locator('[data-testid^="navigation-panel-tag-"]')
.first();
if (!(await tag.isVisible())) {
break;
}
const tagContent = await tag.locator('div').first();
await tagContent.hover();
const more = await tagContent.getByTestId(
'navigation-panel-tree-node-operation-button'
);
await more.click();
await page.getByTestId('tag-delete-button').click();
}
await page.waitForTimeout(100);
}
public static async createDoc(page: Page, title: string, docContent: string) {
await clickNewPageButton(page);
await page.keyboard.insertText(title);
await this.focusToEditor(page);
const texts = docContent.split('\n');
for (const [index, line] of texts.entries()) {
await page.keyboard.insertText(line);
if (index !== texts.length - 1) {
await page.keyboard.press('Enter');
}
}
}
public static async createCollectionAndDoc(
page: Page,
collectionName: string,
docContent: string
) {
// Create collection
await page
.getByTestId('navigation-panel-bar-add-collection-button')
.click();
const input = await page.getByTestId('prompt-modal-input');
await input.focus();
await input.pressSequentially(collectionName);
await page.getByTestId('prompt-modal-confirm').click();
const collections = await page.getByTestId('collapsible-section-content');
const collection = await collections
.getByText(collectionName)
.locator('..');
// Create doc
await collection.hover();
await collection.getByTestId('collection-add-doc-button').click();
await page.getByTestId('confirm-modal-confirm').click();
await this.focusToEditor(page);
const texts = docContent.split('\n');
for (const [index, line] of texts.entries()) {
await page.keyboard.insertText(line);
if (index !== texts.length - 1) {
await page.keyboard.press('Enter');
}
}
await this.waitForCurrentDocSynced(page);
}
public static async createTagAndDoc(
page: Page,
tagName: string,
docContent: string
) {
// Create tag
const tags = await page.getByTestId('navigation-panel-tags');
await tags.hover();
await tags.getByTestId('navigation-panel-bar-add-tag-button').click();
const input = await page.getByTestId('rename-modal-input');
await input.focus();
await input.pressSequentially(tagName);
await input.press('Enter');
const tag = await tags.getByText(tagName).locator('..');
// Create doc
await tag.hover();
await tag.getByTestId('tag-add-doc-button').click();
await this.focusToEditor(page);
const texts = docContent.split('\n');
for (const [index, line] of texts.entries()) {
await page.keyboard.insertText(line);
if (index !== texts.length - 1) {
await page.keyboard.press('Enter');
}
}
// sleep 1 sec to wait the doc sync
await page.waitForTimeout(1000);
}
public static async selectElementInEdgeless(page: Page, elements: string[]) {
await page.evaluate(
({ elements }) => {
const edgelessBlock = document.querySelector(
'affine-edgeless-root'
) as EdgelessRootBlockComponent;
if (!edgelessBlock) {
throw new Error('edgeless block not found');
}
edgelessBlock.gfx.selection.set({
elements,
});
},
{ elements }
);
}
public static async removeAll(page: Page) {
await selectAllByKeyboard(page);
await page.keyboard.press('Delete');
}
public static async askAIWithEdgeless(
page: Page,
createBlock: () => Promise<void>,
afterSelected?: () => Promise<void>
) {
await this.switchToEdgelessMode(page);
await this.removeAll(page);
await createBlock();
await pressEscape(page, 5);
await selectAllByKeyboard(page);
await afterSelected?.();
await page.getByTestId('ask-ai-button').click();
return {
aiImageFilter: this.createAction(page, () =>
page.getByTestId('action-ai-image-filter').click()
),
brainstorm: this.createAction(page, () =>
page.getByTestId('action-brainstorm').click()
),
brainstormMindMap: this.createAction(page, () =>
page.getByTestId('action-brainstorm-mindmap').click()
),
changeTone: (
tone: 'professional' | 'informal' | 'friendly' | 'critical' | 'humorous'
) =>
this.createAction(page, async () => {
await page.getByTestId('action-change-tone').hover();
await page.getByTestId(`action-change-tone-${tone}`).click();
})(),
checkCodeError: this.createAction(page, () =>
page.getByTestId('action-check-code-error').click()
),
continueWithAi: () => page.getByTestId('action-continue-with-ai').click(),
continueWriting: this.createAction(page, () =>
page.getByTestId('action-continue-writing').click()
),
createHeadings: this.createAction(page, () =>
page.getByTestId('action-create-headings').click()
),
explainSelection: this.createAction(page, () =>
page.getByTestId('action-explain-selection').click()
),
findActions: this.createAction(page, () =>
page.getByTestId('action-find-actions').click()
),
fixGrammar: this.createAction(page, () =>
page.getByTestId('action-fix-grammar').click()
),
fixSpelling: this.createAction(page, () =>
page.getByTestId('action-fix-spelling').click()
),
generateCaption: this.createAction(page, () =>
page.getByTestId('action-generate-caption').click()
),
generateHeadings: this.createAction(page, () =>
page.getByTestId('action-generate-headings').click()
),
generateImage: this.createAction(page, () =>
page.getByTestId('action-generate-image').click()
),
generateOutline: this.createAction(page, () =>
page.getByTestId('action-generate-outline').click()
),
generatePresentation: this.createAction(
page,
() => page.getByTestId('action-generate-presentation').click(),
{ responseTimeoutMs: 120000 }
),
imageProcessing: this.createAction(page, () =>
page.getByTestId('action-image-processing').click()
),
improveGrammar: this.createAction(page, () =>
page.getByTestId('action-improve-grammar').click()
),
improveWriting: this.createAction(page, () =>
page.getByTestId('action-improve-writing').click()
),
makeItLonger: this.createAction(page, () =>
page.getByTestId('action-make-it-longer').click()
),
makeItReal: this.createAction(page, () =>
page.getByTestId('action-make-it-real').click()
),
makeItShorter: this.createAction(page, () =>
page.getByTestId('action-make-it-shorter').click()
),
summarize: this.createAction(page, () =>
page.getByTestId('action-summarize').click()
),
translate: (language: string) =>
this.createAction(page, async () => {
await page.getByTestId('action-translate').hover();
await page.getByTestId(`action-translate-${language}`).click();
})(),
writeArticle: this.createAction(page, () =>
page.getByTestId('action-write-article').click()
),
writeBlogPost: this.createAction(page, () =>
page.getByTestId('action-write-blog-post').click()
),
writePoem: this.createAction(page, () =>
page.getByTestId('action-write-poem').click()
),
writeTwitterPost: this.createAction(page, () =>
page.getByTestId('action-write-twitter-post').click()
),
regenerateMindMap: this.createAction(page, () =>
page.getByTestId('action-regenerate-mindmap').click()
),
expandMindMapNode: async () =>
page.getByTestId('action-expand-mindmap-node').click(),
} as const;
}
public static async askAIWithCode(
page: Page,
code: string,
language: string
) {
await this.focusToEditor(page);
await page.keyboard.insertText(`\`\`\`${language}`);
await page.keyboard.press('Enter');
await page.keyboard.insertText(code);
await page.locator('affine-code').blur();
await page.locator('affine-code').hover();
await page.getByTestId('ask-ai-button').click();
return {
explainCode: this.createAction(page, () =>
page.getByTestId('action-explain-code').click()
),
checkCodeError: this.createAction(page, () =>
page.getByTestId('action-check-code-error').click()
),
};
}
public static async askAIWithImage(
page: Page,
image: { name: string; mimeType: string; buffer: Buffer }
) {
await page.evaluate(() => {
delete window.showOpenFilePicker;
});
const fileChooserPromise = page.waitForEvent('filechooser');
await this.focusToEditor(page);
await page.keyboard.press('/');
await page.keyboard.insertText('image');
await page.locator('affine-slash-menu').getByTestId('Image').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(image);
await page.locator('affine-page-image').click();
await page.getByTestId('ask-ai-button').click();
return {
explainImage: this.createAction(page, () =>
page.getByTestId('action-explain-image').click()
),
generateImage: this.createAction(
page,
async () => {
await page.getByTestId('action-generate-image').click();
const input = page.locator(
'affine-ai-panel-widget .ai-panel-container textarea'
);
await input.waitFor({ state: 'visible' });
await input.fill('generate an image');
await page.getByTestId('ai-panel-input-send').waitFor({
state: 'visible',
});
await page.getByTestId('ai-panel-input-send').click();
},
{ responseTimeoutMs: 4 * 60000 }
),
generateCaption: this.createAction(page, () =>
page.getByTestId('action-generate-caption').click()
),
imageProcessing: (type: string) =>
this.createAction(
page,
async () => {
await page.getByTestId('action-image-processing').hover();
await page.getByTestId(`action-image-processing-${type}`).click();
},
{ responseTimeoutMs: 4 * 60000 }
)(),
imageFilter: (style: string) =>
this.createAction(
page,
async () => {
await page.getByTestId('action-ai-image-filter').hover();
await page.getByTestId(`action-image-filter-${style}`).click();
},
{ responseTimeoutMs: 4 * 60000 }
)(),
};
}
public static async showAIMenu(page: Page) {
const askAI = await page.locator('page-editor editor-toolbar ask-ai-icon');
await askAI.waitFor({
state: 'attached',
timeout: 5000,
});
await askAI.click();
return {
aiImageFilter: this.createAction(page, () =>
page.getByTestId('action-ai-image-filter').click()
),
brainstorm: this.createAction(page, () =>
page.getByTestId('action-brainstorm').click()
),
brainstormMindMap: this.createAction(page, () =>
page.getByTestId('action-brainstorm-mindmap').click()
),
changeTone: (
tone: 'professional' | 'informal' | 'friendly' | 'critical' | 'humorous'
) =>
this.createAction(page, async () => {
await page.getByTestId('action-change-tone').hover();
await page.getByTestId(`action-change-tone-${tone}`).click();
})(),
checkCodeError: this.createAction(page, () =>
page.getByTestId('action-check-code-error').click()
),
continueWithAi: () => page.getByTestId('action-continue-with-ai').click(),
continueWriting: this.createAction(page, () =>
page.getByTestId('action-continue-writing').click()
),
createHeadings: this.createAction(page, () =>
page.getByTestId('action-create-headings').click()
),
explainSelection: this.createAction(page, () =>
page.getByTestId('action-explain-selection').click()
),
findActions: this.createAction(page, () =>
page.getByTestId('action-find-actions').click()
),
fixGrammar: this.createAction(page, () =>
page.getByTestId('action-fix-grammar').click()
),
fixSpelling: this.createAction(page, () =>
page.getByTestId('action-fix-spelling').click()
),
generateCaption: this.createAction(page, () =>
page.getByTestId('action-generate-caption').click()
),
generateHeadings: this.createAction(page, () =>
page.getByTestId('action-generate-headings').click()
),
generateImage: this.createAction(page, () =>
page.getByTestId('action-generate-image').click()
),
generateOutline: this.createAction(page, () =>
page.getByTestId('action-generate-outline').click()
),
generatePresentation: this.createAction(
page,
() => page.getByTestId('action-generate-presentation').click(),
{ responseTimeoutMs: 120000 }
),
imageProcessing: this.createAction(page, () =>
page.getByTestId('action-image-processing').click()
),
improveGrammar: this.createAction(page, () =>
page.getByTestId('action-improve-grammar').click()
),
improveWriting: this.createAction(page, () =>
page.getByTestId('action-improve-writing').click()
),
makeItLonger: this.createAction(page, () =>
page.getByTestId('action-make-it-longer').click()
),
makeItReal: this.createAction(page, () =>
page.getByTestId('action-make-it-real').click()
),
makeItShorter: this.createAction(page, () =>
page.getByTestId('action-make-it-shorter').click()
),
summarize: this.createAction(page, () =>
page.getByTestId('action-summarize').click()
),
translate: (language: string) =>
this.createAction(page, async () => {
await page.getByTestId('action-translate').hover();
await page.getByTestId(`action-translate-${language}`).click();
})(),
writeArticle: this.createAction(page, () =>
page.getByTestId('action-write-article').click()
),
writeBlogPost: this.createAction(page, () =>
page.getByTestId('action-write-blog-post').click()
),
writePoem: this.createAction(page, () =>
page.getByTestId('action-write-poem').click()
),
writeTwitterPost: this.createAction(page, () =>
page.getByTestId('action-write-twitter-post').click()
),
} as const;
}
public static async askAIWithText(page: Page, text: string) {
await this.focusToEditor(page);
const texts = text.split('\n');
for (const [index, line] of texts.entries()) {
await page.keyboard.insertText(line);
if (index !== texts.length - 1) {
await page.keyboard.press('Enter');
}
}
await page.keyboard.press('ControlOrMeta+A');
await page.keyboard.press('ControlOrMeta+A');
await page.keyboard.press('ControlOrMeta+A');
return await this.showAIMenu(page);
}
public static async whatAreYourThoughts(page: Page, text: string) {
const textarea = page.locator(
'affine-ai-panel-widget .ai-panel-container textarea'
);
await textarea.fill(text);
return textarea;
}
}

View File

@@ -0,0 +1,280 @@
import { expect, type Page } from '@playwright/test';
const WORKSPACE_EMBEDDING_SWITCH_TEST_ID = 'workspace-embedding-setting-switch';
export class SettingsPanelUtils {
public static async openSettingsPanel(page: Page) {
if (await page.getByTestId('workspace-setting:embedding').isHidden()) {
await page
.getByTestId('slider-bar-workspace-setting-button')
.waitFor({ state: 'visible' });
await page.getByTestId('slider-bar-workspace-setting-button').click();
await page.getByTestId('workspace-setting:embedding').click();
await page.getByTestId('workspace-embedding-setting-header').waitFor({
state: 'visible',
});
}
}
public static async closeSettingsPanel(page: Page) {
if (
await page.getByTestId('workspace-embedding-setting-wrapper').isVisible()
) {
await page.keyboard.press('Escape');
await page.getByTestId('workspace-embedding-setting-wrapper').waitFor({
state: 'hidden',
});
}
}
public static async isWorkspaceEmbeddingEnabled(page: Page) {
const input = await page
.getByTestId(WORKSPACE_EMBEDDING_SWITCH_TEST_ID)
.locator('input');
return (await input.getAttribute('value')) === 'on';
}
public static async waitForWorkspaceEmbeddingSwitchToBe(
page: Page,
enabled: boolean
) {
const input = await page
.getByTestId(WORKSPACE_EMBEDDING_SWITCH_TEST_ID)
.locator('input');
await expect(input).toHaveAttribute('value', enabled ? 'on' : 'off');
}
public static async toggleWorkspaceEmbedding(page: Page) {
const input = await page.getByTestId(WORKSPACE_EMBEDDING_SWITCH_TEST_ID);
await input.click();
}
public static async enableWorkspaceEmbedding(
page: Page,
waitForEnabled = true
) {
const enabled = await this.isWorkspaceEmbeddingEnabled(page);
if (!enabled) {
await this.toggleWorkspaceEmbedding(page);
}
if (waitForEnabled) {
await this.waitForWorkspaceEmbeddingSwitchToBe(page, true);
}
}
public static async disableWorkspaceEmbedding(
page: Page,
waitForDisabled = true
) {
const enabled = await this.isWorkspaceEmbeddingEnabled(page);
if (enabled) {
await this.toggleWorkspaceEmbedding(page);
}
if (waitForDisabled) {
await this.waitForWorkspaceEmbeddingSwitchToBe(page, false);
}
}
public static async uploadWorkspaceEmbedding(
page: Page,
attachments: { name: string; mimeType: string; buffer: Buffer }[]
) {
await page.evaluate(() => {
delete window.showOpenFilePicker;
});
for (const attachment of attachments) {
const fileChooserPromise = page.waitForEvent('filechooser');
await page
.getByTestId('workspace-embedding-setting-upload-button')
.click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(attachment);
await page
.getByTestId('workspace-embedding-setting-attachment-uploading-item')
.waitFor({ state: 'hidden', timeout: 30_000 });
}
}
public static async removeAllAttachments(page: Page) {
const itemId = 'workspace-embedding-setting-attachment-item';
let count = await page.getByTestId(itemId).count();
while (count > 0) {
const attachmentItem = await page.getByTestId(itemId).first();
const hasErrorItem = await attachmentItem
.getByTestId('workspace-embedding-setting-attachment-error-item')
.isVisible();
await attachmentItem
.getByTestId('workspace-embedding-setting-attachment-delete-button')
.click();
if (!hasErrorItem) {
await page.getByTestId('confirm-modal-confirm').click();
}
await page.waitForTimeout(1000);
count = await page.getByTestId(itemId).count();
}
}
public static async clickRemoveAttachment(
page: Page,
attachment: string,
shouldConfirm = true
) {
const attachmentItem = await page
.getByTestId('workspace-embedding-setting-attachment-item')
.filter({ hasText: attachment });
await attachmentItem
.getByTestId('workspace-embedding-setting-attachment-delete-button')
.click();
if (shouldConfirm) {
await page.getByTestId('confirm-modal-confirm').click();
}
}
public static async removeAttachment(
page: Page,
attachment: string,
shouldConfirm = true
) {
await this.clickRemoveAttachment(page, attachment, shouldConfirm);
await page
.getByTestId('workspace-embedding-setting-attachment-item')
.filter({ hasText: attachment })
.waitFor({
state: 'hidden',
});
}
public static async ignoreDocForEmbedding(
page: Page,
doc: string,
shouldWaitForRefresh = true
) {
// Open Dos Searcher
const ignoreDocsButton = await page.getByTestId(
'workspace-embedding-setting-ignore-docs-button'
);
await ignoreDocsButton.click();
// Search and select the doc
const searcher = await page.getByTestId('doc-selector-layout');
const searchInput = await page.getByTestId('doc-selector-search-input');
await searchInput.waitFor({ state: 'visible' });
await searchInput.focus();
await page.keyboard.insertText(doc);
const pageListItem = searcher
.getByTestId('doc-list-item')
.filter({
has: page
.getByTestId('doc-list-item-title')
.getByText(doc, { exact: true }),
})
.first();
await expect(pageListItem).toBeVisible();
await expect(pageListItem.getByTestId('doc-list-item-title')).toHaveText(
doc
);
await pageListItem.click();
await searcher.getByTestId('doc-selector-confirm-button').click();
if (shouldWaitForRefresh) {
const ignoredDocs = await page.getByTestId(
'workspace-embedding-setting-ignore-docs-list'
);
await expect(
ignoredDocs
.getByTestId('workspace-embedding-setting-ignore-docs-list-item')
.filter({ hasText: doc })
).toBeVisible();
}
}
public static async clearAllIgnoredDocs(page: Page) {
const ignoredDocs = await page.getByTestId('ignore-doc-title').all();
for (const ignoredDoc of ignoredDocs) {
const doc = await ignoredDoc.innerText();
// Open Dos Searcher
const ignoreDocsButton = await page.getByTestId(
'workspace-embedding-setting-ignore-docs-button'
);
await ignoreDocsButton.click();
// Search and select the doc
const searcher = await page.getByTestId('doc-selector-layout');
const searchInput = await page.getByTestId('doc-selector-search-input');
await searchInput.focus();
await page.keyboard.insertText(doc);
const pageListItem = searcher.getByTestId('doc-list-item');
await expect(pageListItem).toHaveCount(1);
await pageListItem.getByTestId('affine-checkbox').uncheck();
await searcher.getByTestId('doc-selector-confirm-button').click();
}
}
private static async waitForEmbeddingStatus(
page: Page,
timeout: number,
status = 'synced'
) {
await expect(async () => {
await this.openSettingsPanel(page);
const title = page.getByTestId('embedding-progress-title');
// oxlint-disable-next-line prefer-dom-node-dataset
const progressAttr = await title.getAttribute('data-progress');
expect(progressAttr).not.toBe('loading');
expect(progressAttr).toBe(status);
}).toPass({ timeout });
}
public static async waitForEmbeddingComplete(page: Page, timeout = 30000) {
await this.waitForEmbeddingStatus(page, timeout);
// check embedding progress count
await expect(async () => {
const count = page.getByTestId('embedding-progress-count');
const countText = await count.textContent();
if (countText) {
const [embedded, total] = countText.split('/').map(Number);
expect(embedded).toBe(total);
expect(embedded).toBeGreaterThan(0);
}
}).toPass({ timeout });
}
public static async waitForFileEmbeddingReadiness(
page: Page,
expectedFileCount: number,
timeout = 30000
) {
await expect(async () => {
const attachmentList = page.getByTestId(
'workspace-embedding-setting-attachment-list'
);
const attachmentItems = attachmentList.getByTestId(
'workspace-embedding-setting-attachment-item'
);
await expect(attachmentItems).toHaveCount(expectedFileCount);
await expect(
attachmentList.getByTestId(
'workspace-embedding-setting-attachment-uploading-item'
)
).toHaveCount(0);
}).toPass({ timeout });
await expect(async () => {
await expect(
page.getByTestId('workspace-embedding-setting-attachment-ready-item')
).toHaveCount(expectedFileCount);
}).toPass({ timeout });
}
}

View File

@@ -0,0 +1,70 @@
import { skipOnboarding } from '@affine-test/kit/playwright';
import { createRandomAIUser } from '@affine-test/kit/utils/cloud';
import { openHomePage, setCoreUrl } from '@affine-test/kit/utils/load-page';
import {
clickNewPageButton,
waitForEditorLoad,
} from '@affine-test/kit/utils/page-logic';
import { createLocalWorkspace } from '@affine-test/kit/utils/workspace';
import type { Store } from '@blocksuite/affine/store';
import type { Page } from '@playwright/test';
declare global {
interface Window {
doc: Store;
}
}
export class TestUtils {
private static instance: TestUtils;
private isProduction: boolean;
private constructor() {
this.isProduction = process.env.NODE_ENV === 'production';
if (
process.env.PLAYWRIGHT_USER_AGENT &&
process.env.PLAYWRIGHT_EMAIL &&
!process.env.PLAYWRIGHT_PASSWORD
) {
setCoreUrl(process.env.PLAYWRIGHT_CORE_URL || 'http://localhost:8080');
this.isProduction = true;
}
}
public static getInstance(): TestUtils {
if (!TestUtils.instance) {
TestUtils.instance = new TestUtils();
}
return TestUtils.instance;
}
public getUser() {
if (
!this.isProduction ||
!process.env.PLAYWRIGHT_EMAIL ||
!process.env.PLAYWRIGHT_PASSWORD
) {
return createRandomAIUser();
}
return {
email: process.env.PLAYWRIGHT_EMAIL,
password: process.env.PLAYWRIGHT_PASSWORD,
};
}
public async createNewPage(page: Page) {
await clickNewPageButton(page);
await waitForEditorLoad(page);
}
public async setupTestEnvironment(page: Page) {
await skipOnboarding(page.context());
await openHomePage(page);
await this.createNewPage(page);
}
public async createTestWorkspace(page: Page, name: string = 'test') {
await createLocalWorkspace({ name }, page);
}
}