🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✅ test: add E2E tests for Home sidebar Agent and Group management (#11421)
Arvin Xub12885a8d0e3
diff --git a/e2e/CLAUDE.md b/e2e/CLAUDE.mdindex 77dd6108b79..33f1cfb4390 100644--- a/e2e/CLAUDE.md+++ b/e2e/CLAUDE.md@@ -108,57 +108,42 @@ e2e/> 详细流程参考 [e2e/docs/local-setup.md](./docs/local-setup.md)-### 快速启动流程+### 一键启动(推荐)++使用 TypeScript 脚本自动完成环境设置:```bash-# Step 1: 清理环境-docker stop postgres-e2e 2> /dev/null; docker rm postgres-e2e 2> /dev/null-lsof -ti:3006 | xargs kill -9 2> /dev/null-lsof -ti:5433 | xargs kill -9 2> /dev/null--# Step 2: 启动数据库(使用 paradedb 镜像,支持 pgvector)-docker run -d --name postgres-e2e \- -e POSTGRES_PASSWORD=postgres \- -p 5433:5432 \- paradedb/paradedb:latest--# 等待数据库就绪-until docker exec postgres-e2e pg_isready; do sleep 2; done--# Step 3: 运行数据库迁移(项目根目录)-DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- DATABASE_DRIVER=node \- KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \- bun run db:migrate--# Step 4: 构建应用(首次或代码变更后)-DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- DATABASE_DRIVER=node \- KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \- BETTER_AUTH_SECRET=e2e-test-secret-key-for-better-auth-32chars! \- NEXT_PUBLIC_ENABLE_BETTER_AUTH=1 \- SKIP_LINT=1 \- bun run build--# Step 5: 启动服务器(必须在项目根目录运行!)-DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- DATABASE_DRIVER=node \- KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \- BETTER_AUTH_SECRET=e2e-test-secret-key-for-better-auth-32chars! \- NEXT_PUBLIC_ENABLE_BETTER_AUTH=1 \- NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION=0 \- S3_ACCESS_KEY_ID=e2e-mock-access-key \- S3_SECRET_ACCESS_KEY=e2e-mock-secret-key \- S3_BUCKET=e2e-mock-bucket \- S3_ENDPOINT=https://e2e-mock-s3.localhost \- bunx next start -p 3006+# 在项目根目录运行++# 仅设置数据库(启动 PostgreSQL + 运行迁移)+bun e2e/scripts/setup.ts++# 设置数据库并启动服务器+bun e2e/scripts/setup.ts --start++# 完整设置(数据库 + 构建 + 启动服务器)+bun e2e/scripts/setup.ts --build --start++# 清理环境+bun e2e/scripts/setup.ts --clean```+### 脚本选项++| 选项 | 说明 |+| ---------------- | ---------------------------- |+| `--clean` | 清理现有容器和进程 |+| `--skip-db` | 跳过数据库设置(使用已有的) |+| `--skip-migrate` | 跳过数据库迁移 |+| `--build` | 启动前构建应用 |+| `--start` | 设置完成后启动服务器 |+| `--port <port>` | 服务器端口(默认 3006) |+**重要提示**:- 必须使用 `paradedb/paradedb:latest` 镜像(支持 pgvector 扩展)- 服务器必须在**项目根目录**启动,不能在 e2e 目录-- S3 环境变量是**必需**的,即使不测试文件上传+- S3 环境变量是**必需**的,即使不测试文件上传(脚本已自动处理)## 运行测试@@ -328,45 +313,21 @@ S3_ENDPOINT=https://e2e-mock-s3.localhost## 清理环境-测试完成后或需要重置环境时,执行以下清理操作:--### 停止服务器+测试完成后或需要重置环境时:```bash-# 查找并停止占用端口的进程-lsof -ti:3006 | xargs kill -9 2> /dev/null-lsof -ti:3010 | xargs kill -9 2> /dev/null+# 一键清理(推荐)+bun e2e/scripts/setup.ts --clean```-### 停止 Docker 容器+或手动清理:```bash# 停止并删除 PostgreSQL 容器-docker stop postgres-e2e 2> /dev/null-docker rm postgres-e2e 2> /dev/null-```+docker stop postgres-e2e && docker rm postgres-e2e-### 一键清理(推荐)--```bash-# 清理所有 E2E 相关进程和容器-docker stop postgres-e2e 2> /dev/null-docker rm postgres-e2e 2> /dev/null-lsof -ti:3006 | xargs kill -9 2> /dev/null-lsof -ti:3010 | xargs kill -9 2> /dev/null-lsof -ti:5433 | xargs kill -9 2> /dev/null-echo "Cleanup done"-```--### 清理端口占用--如果遇到端口被占用的错误,可以清理特定端口:--```bash-# 清理 Next.js 服务器端口+# 清理端口占用lsof -ti:3006 | xargs kill -9--# 清理 PostgreSQL 端口lsof -ti:5433 | xargs kill -9```diff --git a/e2e/docs/local-setup.md b/e2e/docs/local-setup.mdindex b9376a94ed0..980387d2e9a 100644--- a/e2e/docs/local-setup.md+++ b/e2e/docs/local-setup.md@@ -7,216 +7,108 @@- pnpm 已安装- 项目已 `pnpm install`-## 完整启动流程+## 一键启动(推荐)-### Step 0: 环境清理(重要!)--每次运行测试前,建议先清理环境,避免残留状态导致问题。+使用 TypeScript 脚本自动完成环境设置:```bash-# 0.1 确保 Docker Desktop 正在运行-# 如果未运行,请先启动 Docker Desktop+# 在项目根目录运行-# 0.2 清理旧的 PostgreSQL 容器-docker stop postgres-e2e 2> /dev/null-docker rm postgres-e2e 2> /dev/null+# 仅设置数据库(启动 PostgreSQL + 运行迁移)+bun e2e/scripts/setup.ts-# 0.3 清理占用的端口-lsof -ti:3006 | xargs kill -9 2> /dev/null # Next.js 服务器端口-lsof -ti:5433 | xargs kill -9 2> /dev/null # PostgreSQL 端口-```+# 设置数据库并启动服务器+bun e2e/scripts/setup.ts --start-### Step 1: 启动数据库+# 完整设置(数据库 + 构建 + 启动服务器)+bun e2e/scripts/setup.ts --build --start-```bash-# 启动 PostgreSQL (端口 5433)-docker run -d --name postgres-e2e \- -e POSTGRES_PASSWORD=postgres \- -p 5433:5432 \- paradedb/paradedb:latest--# 等待数据库就绪-until docker exec postgres-e2e pg_isready; do sleep 2; done-echo "PostgreSQL is ready!"+# 清理环境+bun e2e/scripts/setup.ts --clean```-### Step 2: 运行数据库迁移+### 脚本选项-```bash-# 在项目根目录运行-DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- DATABASE_DRIVER=node \- bun run db:migrate-```+| 选项 | 说明 |+| ---------------- | ---------------------------- |+| `--clean` | 清理现有容器和进程 |+| `--skip-db` | 跳过数据库设置(使用已有的) |+| `--skip-migrate` | 跳过数据库迁移 |+| `--build` | 启动前构建应用 |+| `--start` | 设置完成后启动服务器 |+| `--port <port>` | 服务器端口(默认 3006) |+| `--help` | 显示帮助信息 |-### Step 3: 构建应用(首次或代码变更后)+## 运行测试```bash-# 在项目根目录运行-DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- DATABASE_DRIVER=node \- KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \- BETTER_AUTH_SECRET=e2e-test-secret-key-for-better-auth-32chars! \- NEXT_PUBLIC_ENABLE_BETTER_AUTH=1 \- SKIP_LINT=1 \- bun run build-```+cd e2e-### Step 4: 启动应用服务器+# 运行所有测试+BASE_URL=http://localhost:3006 bun run test-**重要**: 必须在**项目根目录**运行,不能在 e2e 目录运行!+# 运行特定标签+BASE_URL=http://localhost:3006 bun run test -- --tags "@conversation"-```bash-# 在项目根目录运行(注意:不是 e2e 目录)-DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- DATABASE_DRIVER=node \- KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \- BETTER_AUTH_SECRET=e2e-test-secret-key-for-better-auth-32chars! \- NEXT_PUBLIC_ENABLE_BETTER_AUTH=1 \- NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION=0 \- S3_ACCESS_KEY_ID=e2e-mock-access-key \- S3_SECRET_ACCESS_KEY=e2e-mock-secret-key \- S3_BUCKET=e2e-mock-bucket \- S3_ENDPOINT=https://e2e-mock-s3.localhost \- bunx next start -p 3006+# 调试模式(显示浏览器)+HEADLESS=false BASE_URL=http://localhost:3006 bun run test -- --tags "@smoke"```-### Step 5: 等待服务器就绪+## 手动启动流程-```bash-# 在另一个终端运行,确认服务器已启动-until curl -s http://localhost:3006 > /dev/null; do- sleep 2- echo "Waiting..."-done-echo "Server is ready!"-```+如果需要手动控制各个步骤,可以按照以下流程操作:-### Step 6: 运行测试+### Step 1: 环境清理```bash-# 在 e2e 目录运行测试-cd e2e--# 运行特定标签(默认无头模式)-BASE_URL=http://localhost:3006 \- DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- pnpm exec cucumber-js --config cucumber.config.js --tags "@conversation"+# 清理旧的 PostgreSQL 容器+docker stop postgres-e2e 2> /dev/null+docker rm postgres-e2e 2> /dev/null-# 运行所有测试-BASE_URL=http://localhost:3006 \- DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- pnpm exec cucumber-js --config cucumber.config.js--# 调试模式(显示浏览器,观察执行过程)-HEADLESS=false \- BASE_URL=http://localhost:3006 \- DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- pnpm exec cucumber-js --config cucumber.config.js --tags "@conversation"+# 清理占用的端口+lsof -ti:3006 | xargs kill -9 2> /dev/null+lsof -ti:5433 | xargs kill -9 2> /dev/null```-## 一键启动脚本--### 完整初始化(首次运行或需要重建)--在项目根目录创建 `e2e-init.sh`:+### Step 2: 启动数据库```bash-#!/bin/bash-set -e--echo "🧹 Step 0: Cleaning up..."-docker stop postgres-e2e 2> /dev/null || true-docker rm postgres-e2e 2> /dev/null || true-lsof -ti:3006 | xargs kill -9 2> /dev/null || true-lsof -ti:5433 | xargs kill -9 2> /dev/null || true--echo "🐘 Step 1: Starting PostgreSQL..."+# 启动 PostgreSQL (端口 5433)docker run -d --name postgres-e2e \-e POSTGRES_PASSWORD=postgres \-p 5433:5432 \paradedb/paradedb:latest-echo "⏳ Waiting for PostgreSQL..."-until docker exec postgres-e2e pg_isready 2> /dev/null; do sleep 2; done-echo "✅ PostgreSQL is ready!"+# 等待数据库就绪+until docker exec postgres-e2e pg_isready; do sleep 2; done+```-echo "🔄 Step 2: Running migrations..."-DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- DATABASE_DRIVER=node \- bun run db:migrate+### Step 3: 运行数据库迁移-echo "🔨 Step 3: Building application..."+```bashDATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \DATABASE_DRIVER=node \KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \- BETTER_AUTH_SECRET=e2e-test-secret-key-for-better-auth-32chars! \- NEXT_PUBLIC_ENABLE_BETTER_AUTH=1 \- SKIP_LINT=1 \- bun run build--echo "✅ Initialization complete! Now run e2e-start.sh to start the server."+ bun run db:migrate```-### 快速启动服务器--在项目根目录创建 `e2e-start.sh`:+### Step 4: 构建应用(首次或代码变更后)```bash-#!/bin/bash-set -e--echo "🧹 Cleaning up ports..."-lsof -ti:3006 | xargs kill -9 2> /dev/null || true--echo "🚀 Starting Next.js server on port 3006..."DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \DATABASE_DRIVER=node \KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \BETTER_AUTH_SECRET=e2e-test-secret-key-for-better-auth-32chars! \NEXT_PUBLIC_ENABLE_BETTER_AUTH=1 \- NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION=0 \- S3_ACCESS_KEY_ID=e2e-mock-access-key \- S3_SECRET_ACCESS_KEY=e2e-mock-secret-key \- S3_BUCKET=e2e-mock-bucket \- S3_ENDPOINT=https://e2e-mock-s3.localhost \- bunx next start -p 3006-```--### 运行测试--在 e2e 目录创建 `run-test.sh`:--```bash-#!/bin/bash--# 默认参数-TAGS="${1:-@journey}"-HEADLESS="${HEADLESS:-true}" # 默认无头模式--echo "🧪 Running E2E tests with tags: $TAGS"-echo " Headless: $HEADLESS"--HEADLESS=$HEADLESS \- BASE_URL=http://localhost:3006 \- DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- pnpm exec cucumber-js --config cucumber.config.js --tags "$TAGS"+ SKIP_LINT=1 \+ bun run build```-使用方式:+### Step 5: 启动应用服务器-```bash-# 运行特定标签(默认无头模式)-./run-test.sh "@conversation"--# 调试模式(显示浏览器)-HEADLESS=false ./run-test.sh "@conversation"-```--## 快速启动(假设数据库和构建已完成)+**重要**: 必须在**项目根目录**运行!```bash-# Terminal 1: 启动服务器(项目根目录)DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \DATABASE_DRIVER=node \KEY_VAULTS_SECRET=LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s= \@@ -228,30 +120,11 @@ DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \S3_BUCKET=e2e-mock-bucket \S3_ENDPOINT=https://e2e-mock-s3.localhost \bunx next start -p 3006--# Terminal 2: 运行测试(e2e 目录,默认无头模式)-cd e2e-BASE_URL=http://localhost:3006 \- DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- pnpm exec cucumber-js --config cucumber.config.js --tags "@conversation"--# 调试模式(显示浏览器)-HEADLESS=false BASE_URL=http://localhost:3006 \- DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres \- pnpm exec cucumber-js --config cucumber.config.js --tags "@conversation"```## 环境变量参考-### 测试运行时环境变量--| 变量 | 值 | 说明 |-| -------------- | -------------------------------------------------------- | --------------------------------------------------- |-| `BASE_URL` | `http://localhost:3006` | 测试服务器地址 |-| `DATABASE_URL` | `postgresql://postgres:postgres@localhost:5433/postgres` | 数据库连接 |-| `HEADLESS` | `true`(默认)/`false` | 是否无头模式运行浏览器,设为 `false` 可观察执行过程 |--### 服务器启动环境变量(全部必需)+### 服务器启动环境变量| 变量 | 值 | 说明 || ------------------------------------- | -------------------------------------------------------- | ---------------- |@@ -262,7 +135,7 @@ HEADLESS=false BASE_URL=http://localhost:3006 \| `NEXT_PUBLIC_ENABLE_BETTER_AUTH` | `1` | 启用 Better Auth || `NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION` | `0` | 禁用邮箱验证 |-### S3 Mock 变量(必需!)+### S3 Mock 变量(必需)| 变量 | 值 || ---------------------- | ------------------------------- |@@ -271,9 +144,15 @@ HEADLESS=false BASE_URL=http://localhost:3006 \| `S3_BUCKET` | `e2e-mock-bucket` || `S3_ENDPOINT` | `https://e2e-mock-s3.localhost` |-**注意**: S3 环境变量是**必需**的,即使不测试文件上传功能。缺少这些变量会导致发送消息时报错 "S3 environment variables are not set completely"。+### 测试运行时环境变量++| 变量 | 值 | 说明 |+| -------------- | -------------------------------------------------------- | ---------------------- |+| `BASE_URL` | `http://localhost:3006` | 测试服务器地址 |+| `DATABASE_URL` | `postgresql://postgres:postgres@localhost:5433/postgres` | 数据库连接 |+| `HEADLESS` | `true`(默认)/`false` | 是否显示浏览器执行过程 |-## 常见问题排查+## 常见问题### Docker daemon is not running@@ -283,37 +162,34 @@ HEADLESS=false BASE_URL=http://localhost:3006 \### PostgreSQL 容器已存在-**症状**: `docker: Error response from daemon: Conflict. The container name "/postgres-e2e" is already in use`+**症状**: `The container name "/postgres-e2e" is already in use`-**解决**:+**解决**: `bun e2e/scripts/setup.ts --clean` 或手动执行:```bash-docker stop postgres-e2e-docker rm postgres-e2e+docker stop postgres-e2e && docker rm postgres-e2e```### S3 environment variables are not set completely**原因**: 服务器启动时缺少 S3 环境变量-**解决**: 启动服务器时必须设置所有 S3 mock 变量+**解决**: 使用 `bun e2e/scripts/setup.ts --start` 或确保手动设置所有 S3 mock 变量### Cannot find module './src/libs/next/config/define-config'**原因**: 在 e2e 目录下运行 `next start`-**解决**: 必须在**项目根目录**运行 `bunx next start`,不能在 e2e 目录运行+**解决**: 必须在**项目根目录**运行服务器### EADDRINUSE: address already in use**原因**: 端口被占用-**解决**:+**解决**: `bun e2e/scripts/setup.ts --clean` 或:```bash-# 查找并杀掉占用端口的进程lsof -ti:3006 | xargs kill -9-lsof -ti:5433 | xargs kill -9```### BeforeAll hook errored: net::ERR_CONNECTION_REFUSED@@ -324,31 +200,3 @@ lsof -ti:5433 | xargs kill -91. 确认服务器已启动:`curl http://localhost:3006`2. 确认 `BASE_URL` 环境变量设置正确-3. 等待服务器完全就绪后再运行测试--### 测试超时或不稳定--**可能原因**:--1. 网络延迟-2. 服务器响应慢-3. 元素定位问题--**解决**:--1. 使用 `HEADLESS=false` 观察测试执行过程-2. 检查 `screenshots/` 目录中的失败截图-3. 增加等待时间或使用更稳定的定位器--## 清理环境--测试完成后,清理环境:--```bash-# 停止服务器-lsof -ti:3006 | xargs kill -9--# 停止并删除 PostgreSQL 容器-docker stop postgres-e2e-docker rm postgres-e2e-```diff --git a/e2e/scripts/setup.ts b/e2e/scripts/setup.tsnew file mode 100644index 00000000000..0083c833d37--- /dev/null+++ b/e2e/scripts/setup.ts@@ -0,0 +1,529 @@+#!/usr/bin/env bun+/**+ * E2E Test Environment Setup Script+ *+ * One-click setup for E2E testing environment.+ *+ * Usage:+ * bun e2e/scripts/setup.ts [options]+ *+ * Options:+ * --clean Clean up existing containers and processes+ * --skip-db Skip database setup (use existing)+ * --skip-migrate Skip database migration+ * --build Build the application before starting+ * --start Start the server after setup+ * --port <port> Server port (default: 3006)+ * --help Show help message+ */++import { type ChildProcess, spawn, spawnSync } from 'node:child_process';+import { existsSync, unlinkSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';++// ============================================================================+// Configuration+// ============================================================================++const CONFIG = {+ containerName: 'postgres-e2e',+ databaseDriver: 'node',+ databaseUrl: 'postgresql://postgres:postgres@localhost:5433/postgres',+ dbPort: 5433,+ defaultPort: 3006,+ dockerImage: 'paradedb/paradedb:latest',+ projectRoot: resolve(__dirname, '../..'),+ serverTimeout: 120_000, // 2 minutes++ // Secrets (for e2e testing only)+ secrets: {+ betterAuthSecret: 'e2e-test-secret-key-for-better-auth-32chars!',+ keyVaultsSecret: 'LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=',+ },++ // S3 Mock (required even if not testing file uploads)+ s3Mock: {+ accessKeyId: 'e2e-mock-access-key',+ bucket: 'e2e-mock-bucket',+ endpoint: 'https://e2e-mock-s3.localhost',+ secretAccessKey: 'e2e-mock-secret-key',+ },+};++// ============================================================================+// Utilities+// ============================================================================++const colors = {+ cyan: (s: string) => `\x1b[36m${s}\x1b[0m`,+ dim: (s: string) => `\x1b[2m${s}\x1b[0m`,+ green: (s: string) => `\x1b[32m${s}\x1b[0m`,+ red: (s: string) => `\x1b[31m${s}\x1b[0m`,+ yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,+};++function log(emoji: string, message: string) {+ console.log(`${emoji} ${message}`);+}++function logStep(step: number, total: number, message: string) {+ console.log(`\n${colors.cyan(`[${step}/${total}]`)} ${message}`);+}++function exec(+ command: string,+ args: string[] = [],+ options: { cwd?: string; silent?: boolean } = {}+) {+ const { cwd = CONFIG.projectRoot, silent = false } = options;+ const result = spawnSync(command, args, {+ cwd,+ encoding: 'utf-8',+ shell: true,+ stdio: silent ? 'pipe' : 'inherit',+ });+ return result;+}++function execAsync(+ command: string,+ args: string[] = [],+ env: Record<string, string> = {}+): Promise<void> {+ return new Promise((resolve, reject) => {+ const child = spawn(command, args, {+ cwd: CONFIG.projectRoot,+ env: { ...process.env, ...env },+ shell: true,+ stdio: 'inherit',+ });++ child.on('close', (code) => {+ if (code === 0) {+ resolve();+ } else {+ reject(new Error(`Command failed with code ${code}`));+ }+ });++ child.on('error', reject);+ });+}++async function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function waitForCondition(+ check: () => Promise<boolean>,+ timeout: number,+ interval: number = 1000,+ onWait?: () => void+): Promise<boolean> {+ const startTime = Date.now();+ while (Date.now() - startTime < timeout) {+ if (await check()) {+ return true;+ }+ onWait?.();+ await sleep(interval);+ }+ return false;+}++// ============================================================================+// Docker Operations+// ============================================================================++function isDockerRunning(): boolean {+ const result = exec('docker', ['info'], { silent: true });+ return result.status === 0;+}++function isContainerRunning(name: string): boolean {+ const result = exec('docker', ['ps', '-q', '-f', `name=${name}`], { silent: true });+ return !!result.stdout?.trim();+}++function containerExists(name: string): boolean {+ const result = exec('docker', ['ps', '-aq', '-f', `name=${name}`], { silent: true });+ return !!result.stdout?.trim();+}++function stopContainer(name: string): void {+ if (isContainerRunning(name)) {+ log('🛑', `Stopping container: ${name}`);+ exec('docker', ['stop', name], { silent: true });+ }+}++function removeContainer(name: string): void {+ if (containerExists(name)) {+ log('🗑️ ', `Removing container: ${name}`);+ exec('docker', ['rm', name], { silent: true });+ }+}++async function startPostgres(): Promise<void> {+ // Check Docker is running+ if (!isDockerRunning()) {+ throw new Error('Docker is not running. Please start Docker Desktop first.');+ }++ if (isContainerRunning(CONFIG.containerName)) {+ log('✅', 'PostgreSQL container is already running');+ return;+ }++ // Remove existing container if exists+ removeContainer(CONFIG.containerName);++ log('🐘', 'Starting PostgreSQL container...');+ const result = exec('docker', [+ 'run',+ '-d',+ '--name',+ CONFIG.containerName,+ '-e',+ 'POSTGRES_PASSWORD=postgres',+ '-p',+ `${CONFIG.dbPort}:5432`,+ CONFIG.dockerImage,+ ]);++ if (result.status !== 0) {+ throw new Error('Failed to start PostgreSQL container');+ }++ // Wait for database to be ready+ process.stdout.write(' Waiting for PostgreSQL to be ready');+ const isReady = await waitForCondition(+ async () => {+ const result = exec('docker', ['exec', CONFIG.containerName, 'pg_isready'], { silent: true });+ return result.status === 0;+ },+ 30_000,+ 2000,+ () => process.stdout.write('.')+ );++ console.log();++ if (!isReady) {+ throw new Error('PostgreSQL failed to start within 30 seconds');+ }++ log('✅', 'PostgreSQL is ready');+}++// ============================================================================+// Process Management+// ============================================================================++function killProcessOnPort(port: number): void {+ const result = exec('lsof', ['-ti', `:${port}`], { silent: true });+ const pids = result.stdout?.trim();+ if (pids) {+ log('🔪', `Killing processes on port ${port}`);+ for (const pid of pids.split('\n')) {+ if (pid) {+ exec('kill', ['-9', pid], { silent: true });+ }+ }+ }+}++// ============================================================================+// Database Operations+// ============================================================================++async function runMigration(): Promise<void> {+ log('🔄', 'Running database migration...');++ await execAsync('bun', ['run', 'db:migrate'], {+ DATABASE_DRIVER: CONFIG.databaseDriver,+ DATABASE_URL: CONFIG.databaseUrl,+ KEY_VAULTS_SECRET: CONFIG.secrets.keyVaultsSecret,+ });++ log('✅', 'Database migration completed');+}++// ============================================================================+// Build Operations+// ============================================================================++async function buildApp(): Promise<void> {+ log('🔨', 'Building application (this may take a few minutes)...');++ await execAsync('bun', ['run', 'build'], {+ BETTER_AUTH_SECRET: CONFIG.secrets.betterAuthSecret,+ DATABASE_DRIVER: CONFIG.databaseDriver,+ DATABASE_URL: CONFIG.databaseUrl,+ KEY_VAULTS_SECRET: CONFIG.secrets.keyVaultsSecret,+ NEXT_PUBLIC_ENABLE_BETTER_AUTH: '1',+ SKIP_LINT: '1',+ });++ log('✅', 'Application built successfully');+}++// ============================================================================+// Server Operations+// ============================================================================++async function isServerRunning(port: number): Promise<boolean> {+ try {+ const response = await fetch(`http://localhost:${port}/chat`, { method: 'HEAD' });+ return response.ok;+ } catch {+ return false;+ }+}++function getServerEnv(port: number): Record<string, string> {+ return {+ BETTER_AUTH_SECRET: CONFIG.secrets.betterAuthSecret,+ DATABASE_DRIVER: CONFIG.databaseDriver,+ DATABASE_URL: CONFIG.databaseUrl,+ KEY_VAULTS_SECRET: CONFIG.secrets.keyVaultsSecret,+ NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION: '0',+ NEXT_PUBLIC_ENABLE_BETTER_AUTH: '1',+ NODE_OPTIONS: '--max-old-space-size=6144',+ PORT: String(port),+ S3_ACCESS_KEY_ID: CONFIG.s3Mock.accessKeyId,+ S3_BUCKET: CONFIG.s3Mock.bucket,+ S3_ENDPOINT: CONFIG.s3Mock.endpoint,+ S3_SECRET_ACCESS_KEY: CONFIG.s3Mock.secretAccessKey,+ };+}++async function startServer(port: number): Promise<void> {+ if (await isServerRunning(port)) {+ log('✅', `Server is already running on port ${port}`);+ return;+ }++ // Kill any process on the port first+ killProcessOnPort(port);++ log('🚀', `Starting server on port ${port}...`);++ const env = getServerEnv(port);++ // Start server in background+ const child = spawn('bunx', ['next', 'start', '-p', String(port)], {+ cwd: CONFIG.projectRoot,+ detached: true,+ env: { ...process.env, ...env },+ stdio: 'ignore',+ });++ child.unref();++ // Wait for server to be ready+ process.stdout.write(' Waiting for server to be ready');+ const isReady = await waitForCondition(+ () => isServerRunning(port),+ CONFIG.serverTimeout,+ 2000,+ () => process.stdout.write('.')+ );++ console.log();++ if (!isReady) {+ throw new Error(`Server failed to start within ${CONFIG.serverTimeout / 1000} seconds`);+ }++ log('✅', `Server is ready at http://localhost:${port}`);+}++// ============================================================================+// Cleanup+// ============================================================================++function cleanup(): void {+ log('🧹', 'Cleaning up environment...');++ stopContainer(CONFIG.containerName);+ removeContainer(CONFIG.containerName);+ killProcessOnPort(3006);+ killProcessOnPort(3010);+ killProcessOnPort(5433);++ log('✅', 'Cleanup completed');+}++// ============================================================================+// CLI+// ============================================================================++function showHelp(): void {+ console.log(`+${colors.cyan('E2E Test Environment Setup Script')}++${colors.dim('Usage:')}+ bun e2e/scripts/setup.ts [options]++${colors.dim('Options:')}+ --clean Clean up existing containers and processes+ --skip-db Skip database setup (use existing)+ --skip-migrate Skip database migration+ --build Build the application before starting+ --start Start the server after setup+ --port <port> Server port (default: ${CONFIG.defaultPort})+ --help Show this help message++${colors.dim('Examples:')}+ ${colors.green('bun e2e/scripts/setup.ts')} # Setup DB only+ ${colors.green('bun e2e/scripts/setup.ts --start')} # Setup DB and start server+ ${colors.green('bun e2e/scripts/setup.ts --build --start')} # Full setup with build+ ${colors.green('bun e2e/scripts/setup.ts --clean')} # Clean up environment++${colors.dim('After setup, run tests with:')}+ cd e2e+ BASE_URL=http://localhost:3006 bun run test+`);+}++interface Options {+ build: boolean;+ clean: boolean;+ help: boolean;+ port: number;+ skipDb: boolean;+ skipMigrate: boolean;+ start: boolean;+}++function parseArgs(): Options {+ const args = process.argv.slice(2);+ const options: Options = {+ build: false,+ clean: false,+ help: false,+ port: CONFIG.defaultPort,+ skipDb: false,+ skipMigrate: false,+ start: false,+ };++ for (let i = 0; i < args.length; i++) {+ switch (args[i]) {+ case '--help':+ case '-h':+ options.help = true;+ break;+ case '--clean':+ options.clean = true;+ break;+ case '--skip-db':+ options.skipDb = true;+ break;+ case '--skip-migrate':+ options.skipMigrate = true;+ break;+ case '--build':+ options.build = true;+ break;+ case '--start':+ options.start = true;+ break;+ case '--port':+ options.port = parseInt(args[++i], 10) || CONFIG.defaultPort;+ break;+ }+ }++ return options;+}++// ============================================================================+// Main+// ============================================================================++async function main(): Promise<void> {+ const options = parseArgs();++ if (options.help) {+ showHelp();+ process.exit(0);+ }++ console.log(`+${colors.cyan('🤯 LobeHub E2E Environment Setup')}+${'─'.repeat(50)}+`);++ try {+ if (options.clean) {+ cleanup();+ process.exit(0);+ }++ // Calculate total steps+ let totalSteps = 0;+ if (!options.skipDb) totalSteps++;+ if (!options.skipMigrate) totalSteps++;+ if (options.build) totalSteps++;+ if (options.start) totalSteps++;++ let currentStep = 0;++ // Step 1: Start database+ if (!options.skipDb) {+ logStep(++currentStep, totalSteps, 'Setting up PostgreSQL database');+ await startPostgres();+ }++ // Step 2: Run migration+ if (!options.skipMigrate) {+ logStep(++currentStep, totalSteps, 'Running database migrations');+ await runMigration();+ }++ // Step 3: Build (optional)+ if (options.build) {+ logStep(++currentStep, totalSteps, 'Building application');+ await buildApp();+ }++ // Step 4: Start server (optional)+ if (options.start) {+ logStep(++currentStep, totalSteps, 'Starting application server');+ await startServer(options.port);+ }++ console.log(`+${'─'.repeat(50)}+${colors.green('✅ E2E environment setup completed!')}+`);++ // Print next steps+ if (!options.start) {+ console.log(`${colors.dim('Next steps:')}`);+ console.log(`+ 1. Start the server (in project root):+ ${colors.cyan(`bun e2e/scripts/setup.ts --start`)}++ 2. Or start manually:+ ${colors.cyan(`bunx next start -p ${options.port}`)}+`);+ }++ console.log(`${colors.dim('Run tests:')}`);+ console.log(`+ cd e2e+ ${colors.cyan(`BASE_URL=http://localhost:${options.port} bun run test`)}++ ${colors.dim('# Debug mode (show browser)')}+ ${colors.cyan(`HEADLESS=false BASE_URL=http://localhost:${options.port} bun run test`)}+`);+ } catch (error) {+ console.error(`\n${colors.red('❌ Setup failed:')}`, error);+ process.exit(1);+ }+}++main();diff --git a/e2e/src/features/home/sidebarAgent.feature b/e2e/src/features/home/sidebarAgent.featurenew file mode 100644index 00000000000..8939808c9d4--- /dev/null+++ b/e2e/src/features/home/sidebarAgent.feature@@ -0,0 +1,62 @@+@journey @home @sidebar @agent+Feature: Home 页面 Agent 管理+ 作为用户,我希望能够在 Home 页面管理 Agent++ Background:+ Given 用户已登录系统+ And 用户在 Home 页面有一个 Agent++ # ============================================+ # 重命名+ # ============================================++ @HOME-AGENT-RENAME-001 @P0+ Scenario: 通过右键菜单重命名 Agent+ When 用户右键点击该 Agent+ And 用户在菜单中选择重命名+ And 用户输入新的名称 "My Renamed Agent"+ Then 该项名称应该更新为 "My Renamed Agent"++ @HOME-AGENT-RENAME-002 @P0+ Scenario: 通过更多操作菜单重命名 Agent+ When 用户悬停在该 Agent 上+ And 用户点击更多操作按钮+ And 用户在菜单中选择重命名+ And 用户输入新的名称 "Agent From Menu"+ Then 该项名称应该更新为 "Agent From Menu"++ @HOME-AGENT-RENAME-003 @P1+ Scenario: 重命名后按 Enter 确认+ When 用户右键点击该 Agent+ And 用户在菜单中选择重命名+ And 用户输入新的名称 "Enter Confirmed" 并按 Enter+ Then 该项名称应该更新为 "Enter Confirmed"++ # ============================================+ # 置顶+ # ============================================++ @HOME-AGENT-PIN-001 @P1+ Scenario: 置顶 Agent+ Given 该 Agent 未被置顶+ When 用户右键点击该 Agent+ And 用户在菜单中选择置顶+ Then Agent 应该显示置顶图标++ @HOME-AGENT-PIN-002 @P1+ Scenario: 取消置顶 Agent+ Given 该 Agent 已被置顶+ When 用户右键点击该 Agent+ And 用户在菜单中选择取消置顶+ Then Agent 不应该显示置顶图标++ # ============================================+ # 删除+ # ============================================++ @HOME-AGENT-DELETE-001 @P0+ Scenario: 删除 Agent+ When 用户右键点击该 Agent+ And 用户在菜单中选择删除+ And 用户在弹窗中确认删除+ Then Agent 应该从列表中移除diff --git a/e2e/src/features/home/sidebarGroup.feature b/e2e/src/features/home/sidebarGroup.featurenew file mode 100644index 00000000000..e8ac33964e4--- /dev/null+++ b/e2e/src/features/home/sidebarGroup.feature@@ -0,0 +1,62 @@+@journey @home @sidebar @group+Feature: Home 页面 Agent Group 管理+ 作为用户,我希望能够在 Home 页面管理 Agent Group++ Background:+ Given 用户已登录系统+ And 用户在 Home 页面有一个 Agent Group++ # ============================================+ # 重命名+ # ============================================++ @HOME-GROUP-RENAME-001 @P0+ Scenario: 通过右键菜单重命名 Agent Group+ When 用户右键点击该 Agent Group+ And 用户在菜单中选择重命名+ And 用户输入新的名称 "My Renamed Group"+ Then 该项名称应该更新为 "My Renamed Group"++ @HOME-GROUP-RENAME-002 @P0+ Scenario: 通过更多操作菜单重命名 Agent Group+ When 用户悬停在该 Agent Group 上+ And 用户点击更多操作按钮+ And 用户在菜单中选择重命名+ And 用户输入新的名称 "Group From Menu"+ Then 该项名称应该更新为 "Group From Menu"++ @HOME-GROUP-RENAME-003 @P1+ Scenario: 重命名后按 Enter 确认+ When 用户右键点击该 Agent Group+ And 用户在菜单中选择重命名+ And 用户输入新的名称 "Enter Confirmed" 并按 Enter+ Then 该项名称应该更新为 "Enter Confirmed"++ # ============================================+ # 置顶+ # ============================================++ @HOME-GROUP-PIN-001 @P1+ Scenario: 置顶 Agent Group+ Given 该 Agent Group 未被置顶+ When 用户右键点击该 Agent Group+ And 用户在菜单中选择置顶+ Then Agent Group 应该显示置顶图标++ @HOME-GROUP-PIN-002 @P1+ Scenario: 取消置顶 Agent Group+ Given 该 Agent Group 已被置顶+ When 用户右键点击该 Agent Group+ And 用户在菜单中选择取消置顶+ Then Agent Group 不应该显示置顶图标++ # ============================================+ # 删除+ # ============================================++ @HOME-GROUP-DELETE-001 @P0+ Scenario: 删除 Agent Group+ When 用户右键点击该 Agent Group+ And 用户在菜单中选择删除+ And 用户在弹窗中确认删除+ Then Agent Group 应该从列表中移除diff --git a/e2e/src/steps/home/sidebarAgent.steps.ts b/e2e/src/steps/home/sidebarAgent.steps.tsnew file mode 100644index 00000000000..887bf064245--- /dev/null+++ b/e2e/src/steps/home/sidebarAgent.steps.ts@@ -0,0 +1,373 @@+/**+ * Home Sidebar Agent Steps+ *+ * Step definitions for Home page Agent management E2E tests+ * - Rename+ * - Pin/Unpin+ * - Delete+ */+import { Given, Then, When } from '@cucumber/cucumber';+import { expect } from '@playwright/test';++import { TEST_USER } from '../../support/seedTestUser';+import { CustomWorld } from '../../support/world';++/**+ * Create a test agent directly in database+ */+async function createTestAgent(title: string = 'Test Agent'): Promise<string> {+ const databaseUrl = process.env.DATABASE_URL;+ if (!databaseUrl) throw new Error('DATABASE_URL not set');++ const { default: pg } = await import('pg');+ const client = new pg.Client({ connectionString: databaseUrl });++ try {+ await client.connect();++ const now = new Date().toISOString();+ const agentId = `agent_e2e_test_${Date.now()}`;+ const slug = `test-agent-${Date.now()}`;++ await client.query(+ `INSERT INTO agents (id, slug, title, user_id, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $5)+ ON CONFLICT DO NOTHING`,+ [agentId, slug, title, TEST_USER.id, now],+ );++ console.log(` 📍 Created test agent in DB: ${agentId}`);+ return agentId;+ } finally {+ await client.end();+ }+}++// ============================================+// Given Steps+// ============================================++Given('用户在 Home 页面有一个 Agent', async function (this: CustomWorld) {+ console.log(' 📍 Step: 在数据库中创建测试 Agent...');+ const agentId = await createTestAgent('E2E Test Agent');+ this.testContext.createdAgentId = agentId;++ console.log(' 📍 Step: 导航到 Home 页面...');+ await this.page.goto('/');+ await this.page.waitForLoadState('networkidle', { timeout: 15_000 });+ await this.page.waitForTimeout(1000);++ console.log(' 📍 Step: 查找新创建的 Agent...');+ // Look for the newly created agent in the sidebar by its specific ID+ const agentItem = this.page.locator(`a[href="/agent/${agentId}"]`).first();+ await expect(agentItem).toBeVisible({ timeout: 10_000 });++ // Store agent reference for later use+ const agentLabel = await agentItem.getAttribute('aria-label');+ this.testContext.targetItemId = agentLabel || agentId;+ this.testContext.targetItemSelector = `a[href="/agent/${agentId}"]`;+ this.testContext.targetType = 'agent';++ console.log(` ✅ 找到 Agent: ${agentLabel}, id: ${agentId}`);+});++Given('该 Agent 未被置顶', async function (this: CustomWorld) {+ console.log(' 📍 Step: 检查 Agent 未被置顶...');+ // Check if the agent has a pin icon - if so, unpin it first+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');++ if ((await pinIcon.count()) > 0) {+ // Unpin it first+ await targetItem.click({ button: 'right' });+ await this.page.waitForTimeout(300);+ const unpinOption = this.page.getByRole('menuitem', { name: /取消置顶|Unpin/i });+ if ((await unpinOption.count()) > 0) {+ await unpinOption.click();+ await this.page.waitForTimeout(500);+ }+ // Close menu if still open+ await this.page.click('body', { position: { x: 10, y: 10 } });+ }++ console.log(' ✅ Agent 未被置顶');+});++Given('该 Agent 已被置顶', async function (this: CustomWorld) {+ console.log(' 📍 Step: 确保 Agent 已被置顶...');+ // Check if the agent has a pin icon - if not, pin it first+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');++ if ((await pinIcon.count()) === 0) {+ // Pin it first+ await targetItem.click({ button: 'right' });+ await this.page.waitForTimeout(300);+ const pinOption = this.page.getByRole('menuitem', { name: /置顶|Pin/i });+ if ((await pinOption.count()) > 0) {+ await pinOption.click();+ await this.page.waitForTimeout(500);+ }+ // Close menu if still open+ await this.page.click('body', { position: { x: 10, y: 10 } });+ }++ console.log(' ✅ Agent 已被置顶');+});++// ============================================+// When Steps+// ============================================++When('用户右键点击该 Agent', async function (this: CustomWorld) {+ console.log(' 📍 Step: 右键点击 Agent...');++ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();++ // Right-click on the inner content (the NavItem Block component)+ // The ContextMenuTrigger wraps the Block, not the Link+ const innerBlock = targetItem.locator('> div').first();+ if ((await innerBlock.count()) > 0) {+ await innerBlock.click({ button: 'right' });+ } else {+ await targetItem.click({ button: 'right' });+ }++ await this.page.waitForTimeout(800);++ // Debug: check what menus are visible+ const menuItems = await this.page.locator('[role="menuitem"]').count();+ console.log(` 📍 Debug: Found ${menuItems} menu items after right-click`);++ console.log(' ✅ 已右键点击 Agent');+});++When('用户悬停在该 Agent 上', async function (this: CustomWorld) {+ console.log(' 📍 Step: 悬停在 Agent 上...');++ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ await targetItem.hover();+ await this.page.waitForTimeout(500);++ console.log(' ✅ 已悬停在 Agent 上');+});++When('用户点击更多操作按钮', async function (this: CustomWorld) {+ console.log(' 📍 Step: 点击更多操作按钮...');++ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const moreButton = targetItem.locator('svg.lucide-ellipsis, svg.lucide-more-horizontal').first();++ if ((await moreButton.count()) > 0) {+ await moreButton.click();+ } else {+ // Fallback: find any visible ellipsis button+ const allEllipsis = this.page.locator('svg.lucide-ellipsis');+ for (let i = 0; i < (await allEllipsis.count()); i++) {+ const ellipsis = allEllipsis.nth(i);+ if (await ellipsis.isVisible()) {+ await ellipsis.click();+ break;+ }+ }+ }++ await this.page.waitForTimeout(500);+ console.log(' ✅ 已点击更多操作按钮');+});++When('用户在菜单中选择重命名', async function (this: CustomWorld) {+ console.log(' 📍 Step: 选择重命名选项...');++ const renameOption = this.page.getByRole('menuitem', { name: /^(Rename|重命名)$/i });+ await expect(renameOption).toBeVisible({ timeout: 5000 });+ await renameOption.click();+ await this.page.waitForTimeout(500);++ console.log(' ✅ 已选择重命名选项');+});++When('用户在菜单中选择置顶', async function (this: CustomWorld) {+ console.log(' 📍 Step: 选择置顶选项...');++ const pinOption = this.page.getByRole('menuitem', { name: /^(Pin|置顶)$/i });+ await expect(pinOption).toBeVisible({ timeout: 5000 });+ await pinOption.click();+ await this.page.waitForTimeout(500);++ console.log(' ✅ 已选择置顶选项');+});++When('用户在菜单中选择取消置顶', async function (this: CustomWorld) {+ console.log(' 📍 Step: 选择取消置顶选项...');++ const unpinOption = this.page.getByRole('menuitem', { name: /^(Unpin|取消置顶)$/i });+ await expect(unpinOption).toBeVisible({ timeout: 5000 });+ await unpinOption.click();+ await this.page.waitForTimeout(500);++ console.log(' ✅ 已选择取消置顶选项');+});++When('用户在菜单中选择删除', async function (this: CustomWorld) {+ console.log(' 📍 Step: 选择删除选项...');++ const deleteOption = this.page.getByRole('menuitem', { name: /^(Delete|删除)$/i });+ await expect(deleteOption).toBeVisible({ timeout: 5000 });+ await deleteOption.click();+ await this.page.waitForTimeout(300);++ console.log(' ✅ 已选择删除选项');+});++When('用户在弹窗中确认删除', async function (this: CustomWorld) {+ console.log(' 📍 Step: 确认删除...');++ const confirmButton = this.page.locator('.ant-modal-confirm-btns button.ant-btn-dangerous');+ await expect(confirmButton).toBeVisible({ timeout: 5000 });+ await confirmButton.click();+ await this.page.waitForTimeout(500);++ console.log(' ✅ 已确认删除');+});++When('用户输入新的名称 {string}', async function (this: CustomWorld, newName: string) {+ console.log(` 📍 Step: 输入新名称 "${newName}"...`);+ await inputNewName.call(this, newName, false);+});++When(+ '用户输入新的名称 {string} 并按 Enter',+ async function (this: CustomWorld, newName: string) {+ console.log(` 📍 Step: 输入新名称 "${newName}" 并按 Enter...`);+ await inputNewName.call(this, newName, true);+ },+);++// ============================================+// Then Steps+// ============================================++Then('该项名称应该更新为 {string}', async function (this: CustomWorld, expectedName: string) {+ console.log(` 📍 Step: 验证名称为 "${expectedName}"...`);++ await this.page.waitForTimeout(1000);+ const renamedItem = this.page.getByText(expectedName, { exact: true }).first();+ await expect(renamedItem).toBeVisible({ timeout: 5000 });++ console.log(` ✅ 名称已更新为 "${expectedName}"`);+});++Then('Agent 应该显示置顶图标', async function (this: CustomWorld) {+ console.log(' 📍 Step: 验证显示置顶图标...');++ await this.page.waitForTimeout(500);+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');+ await expect(pinIcon).toBeVisible({ timeout: 5000 });++ console.log(' ✅ 置顶图标已显示');+});++Then('Agent 不应该显示置顶图标', async function (this: CustomWorld) {+ console.log(' 📍 Step: 验证不显示置顶图标...');++ await this.page.waitForTimeout(500);+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');+ await expect(pinIcon).not.toBeVisible({ timeout: 5000 });++ console.log(' ✅ 置顶图标未显示');+});++Then('Agent 应该从列表中移除', async function (this: CustomWorld) {+ console.log(' 📍 Step: 验证 Agent 已移除...');++ await this.page.waitForTimeout(500);++ if (this.testContext.targetItemId) {+ const deletedItem = this.page.locator(`a[aria-label="${this.testContext.targetItemId}"]`);+ await expect(deletedItem).not.toBeVisible({ timeout: 5000 });+ }++ console.log(' ✅ Agent 已从列表中移除');+});++// ============================================+// Helper Functions+// ============================================++async function inputNewName(+ this: CustomWorld,+ newName: string,+ pressEnter: boolean,+): Promise<void> {+ await this.page.waitForTimeout(300);++ // Try to find the popover input+ const popoverInputSelectors = [+ '.ant-popover-inner input',+ '.ant-popover-content input',+ '.ant-popover input',+ ];++ let renameInput = null;++ for (const selector of popoverInputSelectors) {+ try {+ const locator = this.page.locator(selector).first();+ await locator.waitFor({ state: 'visible', timeout: 2000 });+ renameInput = locator;+ break;+ } catch {+ // Try next selector+ }+ }++ if (!renameInput) {+ // Fallback: find any visible input+ const allInputs = this.page.locator('input:visible');+ const count = await allInputs.count();++ for (let i = 0; i < count; i++) {+ const input = allInputs.nth(i);+ const placeholder = (await input.getAttribute('placeholder').catch(() => '')) || '';+ if (placeholder.includes('Search') || placeholder.includes('搜索')) continue;++ const isInPopover = await input.evaluate((el) => {+ return el.closest('.ant-popover') !== null || el.closest('[class*="popover"]') !== null;+ });++ if (isInPopover || count <= 2) {+ renameInput = input;+ break;+ }+ }+ }++ if (renameInput) {+ await renameInput.click();+ await renameInput.clear();+ await renameInput.fill(newName);++ if (pressEnter) {+ await renameInput.press('Enter');+ } else {+ await this.page.click('body', { position: { x: 10, y: 10 } });+ }+ } else {+ // Keyboard fallback+ await this.page.keyboard.press('Meta+A');+ await this.page.waitForTimeout(50);+ await this.page.keyboard.type(newName, { delay: 20 });++ if (pressEnter) {+ await this.page.keyboard.press('Enter');+ } else {+ await this.page.click('body', { position: { x: 10, y: 10 } });+ }+ }++ await this.page.waitForTimeout(1000);+ console.log(` ✅ 已输入新名称 "${newName}"`);+}diff --git a/e2e/src/steps/home/sidebarGroup.steps.ts b/e2e/src/steps/home/sidebarGroup.steps.tsnew file mode 100644index 00000000000..eb9699c7790--- /dev/null+++ b/e2e/src/steps/home/sidebarGroup.steps.ts@@ -0,0 +1,168 @@+/**+ * Home Sidebar Agent Group Steps+ *+ * Step definitions for Home page Agent Group management E2E tests+ * - Rename+ * - Pin/Unpin+ * - Delete+ */+import { Given, Then, When } from '@cucumber/cucumber';+import { expect } from '@playwright/test';++import { TEST_USER } from '../../support/seedTestUser';+import { CustomWorld } from '../../support/world';++/**+ * Create a test chat group directly in database+ */+async function createTestGroup(title: string = 'Test Group'): Promise<string> {+ const databaseUrl = process.env.DATABASE_URL;+ if (!databaseUrl) throw new Error('DATABASE_URL not set');++ const { default: pg } = await import('pg');+ const client = new pg.Client({ connectionString: databaseUrl });++ try {+ await client.connect();++ const now = new Date().toISOString();+ const groupId = `group_e2e_test_${Date.now()}`;++ await client.query(+ `INSERT INTO chat_groups (id, title, user_id, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $4)+ ON CONFLICT DO NOTHING`,+ [groupId, title, TEST_USER.id, now],+ );++ console.log(` 📍 Created test group in DB: ${groupId}`);+ return groupId;+ } finally {+ await client.end();+ }+}++// ============================================+// Given Steps+// ============================================++Given('用户在 Home 页面有一个 Agent Group', async function (this: CustomWorld) {+ console.log(' 📍 Step: 在数据库中创建测试 Agent Group...');+ const groupId = await createTestGroup('E2E Test Group');+ this.testContext.createdGroupId = groupId;++ console.log(' 📍 Step: 导航到 Home 页面...');+ await this.page.goto('/');+ await this.page.waitForLoadState('networkidle', { timeout: 15_000 });+ await this.page.waitForTimeout(1000);++ console.log(' 📍 Step: 查找新创建的 Agent Group...');+ const groupItem = this.page.locator(`a[href="/group/${groupId}"]`).first();+ await expect(groupItem).toBeVisible({ timeout: 10_000 });++ const groupLabel = await groupItem.getAttribute('aria-label');+ this.testContext.targetItemId = groupLabel || groupId;+ this.testContext.targetItemSelector = `a[href="/group/${groupId}"]`;+ this.testContext.targetType = 'group';++ console.log(` ✅ 找到 Agent Group: ${groupLabel}, id: ${groupId}`);+});++Given('该 Agent Group 未被置顶', async function (this: CustomWorld) {+ console.log(' 📍 Step: 检查 Agent Group 未被置顶...');+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');++ if ((await pinIcon.count()) > 0) {+ await targetItem.click({ button: 'right' });+ await this.page.waitForTimeout(300);+ const unpinOption = this.page.getByRole('menuitem', { name: /取消置顶|Unpin/i });+ if ((await unpinOption.count()) > 0) {+ await unpinOption.click();+ await this.page.waitForTimeout(500);+ }+ await this.page.click('body', { position: { x: 10, y: 10 } });+ }++ console.log(' ✅ Agent Group 未被置顶');+});++Given('该 Agent Group 已被置顶', async function (this: CustomWorld) {+ console.log(' 📍 Step: 确保 Agent Group 已被置顶...');+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');++ if ((await pinIcon.count()) === 0) {+ await targetItem.click({ button: 'right' });+ await this.page.waitForTimeout(300);+ const pinOption = this.page.getByRole('menuitem', { name: /置顶|Pin/i });+ if ((await pinOption.count()) > 0) {+ await pinOption.click();+ await this.page.waitForTimeout(500);+ }+ await this.page.click('body', { position: { x: 10, y: 10 } });+ }++ console.log(' ✅ Agent Group 已被置顶');+});++// ============================================+// When Steps+// ============================================++When('用户右键点击该 Agent Group', async function (this: CustomWorld) {+ console.log(' 📍 Step: 右键点击 Agent Group...');++ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ await targetItem.click({ button: 'right' });+ await this.page.waitForTimeout(500);++ console.log(' ✅ 已右键点击 Agent Group');+});++When('用户悬停在该 Agent Group 上', async function (this: CustomWorld) {+ console.log(' 📍 Step: 悬停在 Agent Group 上...');++ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ await targetItem.hover();+ await this.page.waitForTimeout(500);++ console.log(' ✅ 已悬停在 Agent Group 上');+});++// ============================================+// Then Steps+// ============================================++Then('Agent Group 应该显示置顶图标', async function (this: CustomWorld) {+ console.log(' 📍 Step: 验证显示置顶图标...');++ await this.page.waitForTimeout(500);+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');+ await expect(pinIcon).toBeVisible({ timeout: 5000 });++ console.log(' ✅ 置顶图标已显示');+});++Then('Agent Group 不应该显示置顶图标', async function (this: CustomWorld) {+ console.log(' 📍 Step: 验证不显示置顶图标...');++ await this.page.waitForTimeout(500);+ const targetItem = this.page.locator(this.testContext.targetItemSelector).first();+ const pinIcon = targetItem.locator('svg.lucide-pin');+ await expect(pinIcon).not.toBeVisible({ timeout: 5000 });++ console.log(' ✅ 置顶图标未显示');+});++Then('Agent Group 应该从列表中移除', async function (this: CustomWorld) {+ console.log(' 📍 Step: 验证 Agent Group 已移除...');++ await this.page.waitForTimeout(500);++ const deletedItem = this.page.locator(this.testContext.targetItemSelector);+ await expect(deletedItem).not.toBeVisible({ timeout: 5000 });++ console.log(' ✅ Agent Group 已从列表中移除');+});diff --git a/e2e/src/steps/hooks.ts b/e2e/src/steps/hooks.tsindex e569bf97cb6..4b9d4897123 100644--- a/e2e/src/steps/hooks.ts+++ b/e2e/src/steps/hooks.ts@@ -84,6 +84,7 @@ Before(async function (this: CustomWorld, { pickle }) {(tag) =>tag.name.startsWith('@COMMUNITY-') ||tag.name.startsWith('@AGENT-') ||+ tag.name.startsWith('@HOME-') ||tag.name.startsWith('@ROUTES-'),);console.log(`\n📝 Running: ${pickle.name}${testId ? ` (${testId.name.replace('@', '')})` : ''}`);@@ -104,6 +105,7 @@ After(async function (this: CustomWorld, { pickle, result }) {(tag) =>tag.name.startsWith('@COMMUNITY-') ||tag.name.startsWith('@AGENT-') ||+ tag.name.startsWith('@HOME-') ||tag.name.startsWith('@ROUTES-'),)?.name.replace('@', '');diff --git a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/Editing.tsx b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/Editing.tsxindex 2971c5cfe85..24d61e62667 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/Editing.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/Editing.tsx@@ -10,7 +10,7 @@ interface EditingProps {}const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {- const editing = useHomeStore((s) => s.agentRenamingId === id);+ const editing = useHomeStore((s) => s.groupRenamingId === id);const [newTitle, setNewTitle] = useState(title);@@ -19,17 +19,10 @@ const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {if (hasChanges) {try {- // Set loading state- useHomeStore.getState().setAgentUpdatingId(id);-- // TODO: Add group title update logic here- // await updateGroupTitle(id, newTitle);-- // Refresh agent list to update sidebar display- await useHomeStore.getState().refreshAgentList();+ useHomeStore.getState().setGroupUpdatingId(id);+ await useHomeStore.getState().renameAgentGroup(id, newTitle);} finally {- // Clear loading state- useHomeStore.getState().setAgentUpdatingId(null);+ useHomeStore.getState().setGroupUpdatingId(null);}}toggleEditing(false);diff --git a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsxindex 8721b4e30af..255d8bf26a0 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx@@ -30,8 +30,8 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className }) => {// Get UI state from homeStore (editing, updating)const [editing, isUpdating] = useHomeStore((s) => [- s.agentRenamingId === id,- s.agentUpdatingId === id,+ s.groupRenamingId === id,+ s.groupUpdatingId === id,]);// Get display title with fallback@@ -63,7 +63,7 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className }) => {const toggleEditing = useCallback((visible?: boolean) => {- useHomeStore.getState().setAgentRenamingId(visible ? id : null);+ useHomeStore.getState().setGroupRenamingId(visible ? id : null);},[id],);diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.tsindex 41104186dd2..67cb9427f90 100644--- a/src/store/home/slices/sidebarUI/action.ts+++ b/src/store/home/slices/sidebarUI/action.ts@@ -40,6 +40,10 @@ export interface SidebarUIAction {* Remove an agent group (group chat)*/removeAgentGroup: (groupId: string) => Promise<void>;+ /**+ * Rename an agent group (group chat)+ */+ renameAgentGroup: (groupId: string, title: string) => Promise<void>;/*** Update agent's group*/@@ -162,6 +166,11 @@ export const createSidebarUISlice: StateCreator<await get().refreshAgentList();},+ renameAgentGroup: async (groupId, title) => {+ await chatGroupService.updateGroup(groupId, { title });+ await get().refreshAgentList();+ },+updateAgentGroup: async (agentId, groupId) => {await homeService.updateAgentSessionGroupId(agentId, groupId === 'default' ? null : groupId);await get().refreshAgentList();