Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(e2e): add integration test infrastructure for real E2E testing

cyh3d028ddc4da1
diff --git a/.env.e2e.example b/.env.e2e.example
new file mode 100644
index 000000000..711c87896
--- /dev/null
+++ b/.env.e2e.example
@@ -0,0 +1,50 @@
+# E2E Integration Test Environment Variables
+# Copy to .env.e2e and fill in your tokens.
+# This file must NEVER be committed.
+
+# === Bot A (SUT - vibe-remote bot, runs inside Docker) ===
+
+# Slack Bot A
+SLACK_BOT_TOKEN=xoxb-your-bot-token
+SLACK_APP_TOKEN=xapp-your-app-token
+
+# Discord Bot A
+DISCORD_BOT_TOKEN=your-discord-bot-token
+
+# Feishu Bot A
+LARK_APP_ID=cli_your_app_id
+LARK_APP_SECRET=your_app_secret
+
+# === Bot B (Test Driver, runs on host / CI) ===
+
+# Slack Bot B (needs: chat:write, channels:history, channels:read)
+E2E_SLACK_BOT_B_TOKEN=xoxb-your-test-driver-token
+
+# Discord Bot B (needs: Send Messages, Read Message History, Message Content Intent)
+E2E_DISCORD_BOT_B_TOKEN=your-discord-test-driver-token
+
+# Feishu Bot B (needs: im:message:send_as_bot, im:chat:readonly)
+E2E_FEISHU_BOT_B_APP_ID=cli_your_test_driver_app_id
+E2E_FEISHU_BOT_B_APP_SECRET=your_test_driver_app_secret
+
+# === Test Channels (Bot A and Bot B must both be members) ===
+
+E2E_SLACK_CHANNEL=C0123456789
+E2E_DISCORD_CHANNEL=1234567890123456789
+E2E_FEISHU_CHAT_ID=oc_your_chat_id
+
+# === Bot A User IDs (used to identify Bot A's replies) ===
+
+E2E_SLACK_BOT_A_ID=U0123456789
+E2E_DISCORD_BOT_A_ID=1234567890123456789
+E2E_FEISHU_BOT_A_ID=ou_your_bot_user_id
+
+# === Agent API Keys (used by agent CLIs inside Docker) ===
+
+ANTHROPIC_API_KEY=sk-ant-your-key
+OPENAI_API_KEY=sk-your-key
+
+# === Platform selection (which platform to test) ===
+# Set to the platform Bot A is configured for.
+# vibe-remote runs one platform at a time.
+E2E_PLATFORM=slack
diff --git a/.gitignore b/.gitignore
index bab1a5dac..c398e257f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -104,6 +104,8 @@ celerybeat.pid
# Environments
.env
+.env.e2e
+.env.*.local
.venv
env/
venv/
diff --git a/Dockerfile b/Dockerfile
index c9d6584d2..e265ddf10 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,18 @@
-# --- Build stage: install dependencies + build UI if needed ---
+# ============================================================
+# Stage 1: Build UI (React + Vite)
+# ============================================================
+FROM node:20-slim AS ui-builder
+
+WORKDIR /app/ui
+COPY ui/package.json ui/package-lock.json ./
+RUN npm ci --ignore-scripts
+COPY ui/ .
+RUN npm run build
+
+
+# ============================================================
+# Stage 2: Python base (API-only tests)
+# ============================================================
FROM python:3.12-slim AS base
RUN apt-get update && apt-get install -y --no-install-recommends \
@@ -10,9 +24,8 @@ WORKDIR /app
# Copy project files
COPY . .
-# Create a minimal UI dist placeholder (pyproject.toml force-includes ui/dist)
-RUN mkdir -p ui/dist && \
- echo '<html><body>E2E Test</body></html>' > ui/dist/index.html
+# Copy built UI from stage 1
+COPY --from=ui-builder /app/ui/dist /app/ui/dist
# hatch-vcs needs git to determine version; .git is excluded by .dockerignore.
# Use SETUPTOOLS_SCM_PRETEND_VERSION to provide a fake version for the build.
@@ -30,3 +43,26 @@ COPY scripts/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]
+
+
+# ============================================================
+# Stage 3: Integration target (base + agent CLIs)
+# For full E2E tests with real agent backends.
+# Build with: docker build --target integration .
+# ============================================================
+FROM base AS integration
+
+# Install Node.js runtime (needed by opencode and claude CLIs)
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ curl \
+ && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
+ && apt-get install -y --no-install-recommends nodejs \
+ && rm -rf /var/lib/apt/lists/*
+
+# Install agent CLIs (failures are non-fatal: not all may be needed)
+RUN npm install -g @anthropic-ai/claude-code 2>/dev/null || echo "WARN: claude-code install failed (optional)"
+RUN npm install -g @openai/codex 2>/dev/null || echo "WARN: codex install failed (optional)"
+# OpenCode: try npm, fall back to noting it's unavailable
+RUN npm install -g opencode 2>/dev/null || echo "WARN: opencode install failed (optional)"
+
+ENTRYPOINT ["/docker-entrypoint.sh"]
diff --git a/docker-compose.e2e-integration.yml b/docker-compose.e2e-integration.yml
new file mode 100644
index 000000000..9f5b5d99c
--- /dev/null
+++ b/docker-compose.e2e-integration.yml
@@ -0,0 +1,35 @@
+# Full E2E integration test compose.
+# Runs vibe-remote in full mode (service + UI) with platform connections.
+#
+# Usage:
+# cp .env.e2e.example .env.e2e
+# # Fill in tokens...
+# docker compose -f docker-compose.e2e-integration.yml up -d
+# pytest tests/e2e/ -v -k integration
+
+services:
+ vibe:
+ build:
+ context: .
+ dockerfile: Dockerfile
+ target: integration
+ ports:
+ - "${VIBE_E2E_PORT:-15123}:5123"
+ env_file:
+ - .env.e2e
+ environment:
+ - VIBE_REMOTE_HOME=/data/vibe_remote
+ - VIBE_UI_PORT=5123
+ - E2E_TEST_MODE=true
+ volumes:
+ - vibe-e2e-data:/data/vibe_remote
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5123/health', timeout=3)"]
+ interval: 3s
+ timeout: 5s
+ retries: 20
+ start_period: 30s
+ command: ["full"]
+
+volumes:
+ vibe-e2e-data:
diff --git a/pyproject.toml b/pyproject.toml
index 6dfc646ac..28d1b1820 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -85,3 +85,9 @@ src = ["."]
[tool.ruff.lint]
select = ["E9", "F63", "F7", "F82"]
extend-ignore = ["E501"]
+
+[tool.pytest.ini_options]
+asyncio_mode = "auto"
+markers = [
+ "integration: platform integration tests requiring Docker + platform tokens",
+]
diff --git a/tests/e2e/conftest_integration.py b/tests/e2e/conftest_integration.py
new file mode 100644
index 000000000..e476d1163
--- /dev/null
+++ b/tests/e2e/conftest_integration.py
@@ -0,0 +1,79 @@
+"""Fixtures for platform integration E2E tests.
+
+These tests require:
+1. Docker container running in full mode (docker-compose.e2e-integration.yml)
+2. Platform tokens configured in .env.e2e
+3. Bot A and Bot B both present in the test channel
+"""
+
+import asyncio
+import os
+
+import pytest
+
+
+def _env(key: str) -> str:
+ """Get required env var or empty string."""
+ return os.environ.get(key, "")
+
+
+def _has_slack_config() -> bool:
+ return bool(_env("E2E_SLACK_BOT_B_TOKEN") and _env("E2E_SLACK_CHANNEL"))
+
+
+def _has_discord_config() -> bool:
+ return bool(_env("E2E_DISCORD_BOT_B_TOKEN") and _env("E2E_DISCORD_CHANNEL"))
+
+
+def _has_feishu_config() -> bool:
+ return bool(_env("E2E_FEISHU_BOT_B_APP_ID") and _env("E2E_FEISHU_BOT_B_APP_SECRET") and _env("E2E_FEISHU_CHAT_ID"))
+
+
[email protected](scope="session")
+def event_loop():
+ """Create a session-scoped event loop for async fixtures."""
+ loop = asyncio.new_event_loop()
+ yield loop
+ loop.close()
+
+
[email protected](scope="session")
+def slack_driver(event_loop):
+ """Session-scoped Slack driver. Skips if not configured."""
+ if not _has_slack_config():
+ pytest.skip("Slack E2E not configured (missing E2E_SLACK_BOT_B_TOKEN or E2E_SLACK_CHANNEL)")
+
+ from tests.e2e.drivers.slack_driver import SlackDriver
+
+ driver = SlackDriver()
+ event_loop.run_until_complete(driver.setup())
+ yield driver
+ event_loop.run_until_complete(driver.teardown())
+
+
[email protected](scope="session")
+def discord_driver(event_loop):
+ """Session-scoped Discord driver. Skips if not configured."""
+ if not _has_discord_config():
+ pytest.skip("Discord E2E not configured (missing E2E_DISCORD_BOT_B_TOKEN or E2E_DISCORD_CHANNEL)")
+
+ from tests.e2e.drivers.discord_driver import DiscordDriver
+
+ driver = DiscordDriver()
+ event_loop.run_until_complete(driver.setup())
+ yield driver
+ event_loop.run_until_complete(driver.teardown())
+
+
[email protected](scope="session")
+def feishu_driver(event_loop):
+ """Session-scoped Feishu driver. Skips if not configured."""
+ if not _has_feishu_config():
+ pytest.skip("Feishu E2E not configured (missing E2E_FEISHU_BOT_B_* or E2E_FEISHU_CHAT_ID)")
+
+ from tests.e2e.drivers.feishu_driver import FeishuDriver
+
+ driver = FeishuDriver()
+ event_loop.run_until_complete(driver.setup())
+ yield driver
+ event_loop.run_until_complete(driver.teardown())
diff --git a/tests/e2e/drivers/__init__.py b/tests/e2e/drivers/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/e2e/drivers/base.py b/tests/e2e/drivers/base.py
new file mode 100644
index 000000000..41e2b844e
--- /dev/null
+++ b/tests/e2e/drivers/base.py
@@ -0,0 +1,110 @@
+"""Abstract base class for platform-agnostic E2E test drivers."""
+
+import asyncio
+import logging
+import time
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class BotReply:
+ """A reply from Bot A."""
+
+ text: str
+ message_id: str
+ thread_id: Optional[str] = None
+ raw: Optional[dict] = None
+
+
+class PlatformDriver(ABC):
+ """Platform-agnostic test driver interface.
+
+ Each platform implements this to send messages as Bot B
+ and read Bot A's replies.
+ """
+
+ def __init__(self, bot_a_id: str, channel_id: str):
+ self.bot_a_id = bot_a_id
+ self.channel_id = channel_id
+
+ @abstractmethod
+ async def setup(self) -> None:
+ """Initialize the driver (authenticate, etc.)."""
+
+ @abstractmethod
+ async def teardown(self) -> None:
+ """Clean up resources."""
+
+ @abstractmethod
+ async def send_message(self, text: str, thread_id: Optional[str] = None) -> str:
+ """Send a message as Bot B. Returns message ID."""
+
+ @abstractmethod
+ async def get_messages_after(self, after_ts: str, limit: int = 20) -> list[dict]:
+ """Get messages in the channel after a given timestamp/message ID.
+
+ Each dict should have at minimum: user, text, ts (message id).
+ """
+
+ async def send_and_wait_reply(
+ self,
+ text: str,
+ timeout: float = 120,
+ poll_interval: float = 3,
+ thread_id: Optional[str] = None,
+ ) -> BotReply:
+ """Send a message and wait for Bot A to reply.
+
+ Args:
+ text: Message to send as Bot B
+ timeout: Max seconds to wait for reply
+ poll_interval: Seconds between polls
+ thread_id: Send in a thread (optional)
+
+ Returns:
+ BotReply with Bot A's response
+
+ Raises:
+ TimeoutError if Bot A doesn't reply within timeout
+ """
+ msg_id = await self.send_message(text, thread_id=thread_id)
+ logger.info(
+ "Sent message '%s...' (id=%s), waiting for Bot A reply...",
+ text[:50],
+ msg_id,
+ )
+
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ messages = await self.get_messages_after(msg_id)
+ for msg in messages:
+ if msg.get("user") == self.bot_a_id:
+ reply_text = msg.get("text", "")
+ logger.info("Bot A replied: '%s...'", reply_text[:100])
+ return BotReply(
+ text=reply_text,
+ message_id=msg.get("ts", msg.get("id", "")),
+ thread_id=msg.get("thread_ts", msg.get("thread_id")),
+ raw=msg,
+ )
+ await asyncio.sleep(poll_interval)
+
+ raise TimeoutError(f"Bot A did not reply within {timeout}s after message: {text[:80]}")
+
+ async def send_command(self, command: str, args: str = "", timeout: float = 120) -> BotReply:
+ """Send a slash-style text command and wait for reply.
+
+ Args:
+ command: Command name without slash (e.g., "start", "cwd")
+ args: Command arguments
+ timeout: Max seconds to wait for reply
+
+ Returns:
+ BotReply with Bot A's response
+ """
+ text = f"/{command}" + (f" {args}" if args else "")
+ return await self.send_and_wait_reply(text, timeout=timeout)
diff --git a/tests/e2e/drivers/discord_driver.py b/tests/e2e/drivers/discord_driver.py
new file mode 100644
index 000000000..e9bd0b6f7
--- /dev/null
+++ b/tests/e2e/drivers/discord_driver.py
@@ -0,0 +1,93 @@
+"""Discord test driver using HTTP API (no gateway connection needed)."""
+
+import logging
+import os
+from typing import Optional
+
+import aiohttp
+
+from .base import PlatformDriver
+
+logger = logging.getLogger(__name__)
+
+DISCORD_API = "https://discord.com/api/v10"
+
+
+class DiscordDriver(PlatformDriver):
+ """Drive tests via Discord HTTP API using Bot B's token."""
+
+ def __init__(
+ self,
+ bot_b_token: Optional[str] = None,
+ bot_a_id: Optional[str] = None,
+ channel_id: Optional[str] = None,
+ ):
+ _bot_a_id = bot_a_id or os.environ.get("E2E_DISCORD_BOT_A_ID", "")
+ _channel_id = channel_id or os.environ.get("E2E_DISCORD_CHANNEL", "")
+ super().__init__(bot_a_id=_bot_a_id, channel_id=_channel_id)
+ self.token = bot_b_token or os.environ.get("E2E_DISCORD_BOT_B_TOKEN", "")
+ self._session: Optional[aiohttp.ClientSession] = None
+
+ def _headers(self) -> dict:
+ return {
+ "Authorization": f"Bot {self.token}",
+ "Content-Type": "application/json",
+ }
+
+ async def setup(self) -> None:
+ if not self.token:
+ raise RuntimeError("Discord Bot B token not configured (E2E_DISCORD_BOT_B_TOKEN)")
+
+ self._session = aiohttp.ClientSession()
+ # Verify auth
+ async with self._session.get(f"{DISCORD_API}/users/@me", headers=self._headers()) as resp:
+ if resp.status != 200:
+ raise RuntimeError(f"Discord auth failed: {resp.status}")
+ data = await resp.json()
+ logger.info(
+ "Discord Bot B authenticated as: %s#%s",
+ data["username"],
+ data.get("discriminator", "0"),
+ )
+
+ async def teardown(self) -> None:
+ if self._session:
+ await self._session.close()
+ self._session = None
+
+ async def send_message(self, text: str, thread_id: Optional[str] = None) -> str:
+ assert self._session is not None, "Driver not set up"
+ payload: dict = {"content": text}
+ if thread_id:
+ # Discord uses message_reference for threads
+ payload["message_reference"] = {"message_id": thread_id}
+
+ async with self._session.post(
+ f"{DISCORD_API}/channels/{self.channel_id}/messages",
+ headers=self._headers(),
+ json=payload,
+ ) as resp:
+ data = await resp.json()
+ return data["id"]
+
+ async def get_messages_after(self, after_ts: str, limit: int = 20) -> list[dict]:
+ assert self._session is not None, "Driver not set up"
+ async with self._session.get(
+ f"{DISCORD_API}/channels/{self.channel_id}/messages",
+ headers=self._headers(),
+ params={"after": after_ts, "limit": limit},
+ ) as resp:
+ messages = await resp.json()
+
+ # Discord returns newest first, reverse for chronological
+ messages.reverse()
+ # Normalize to common format
+ return [
+ {
+ "user": msg["author"]["id"],
+ "text": msg.get("content", ""),
+ "ts": msg["id"],
+ "raw": msg,
+ }
+ for msg in messages
+ ]
diff --git a/tests/e2e/drivers/feishu_driver.py b/tests/e2e/drivers/feishu_driver.py
new file mode 100644
index 000000000..be2df26e3
--- /dev/null
+++ b/tests/e2e/drivers/feishu_driver.py
@@ -0,0 +1,146 @@
+"""Feishu (Lark) test driver using HTTP API."""
+
+import json
+import logging
+import os
+import time
+from typing import Optional
+
+import aiohttp
+
+from .base import PlatformDriver
+
+logger = logging.getLogger(__name__)
+
+FEISHU_API = "https://open.feishu.cn/open-apis"
+
+
+class FeishuDriver(PlatformDriver):
+ """Drive tests via Feishu HTTP API using Bot B's credentials."""
+
+ def __init__(
+ self,
+ app_id: Optional[str] = None,
+ app_secret: Optional[str] = None,
+ bot_a_id: Optional[str] = None,
+ chat_id: Optional[str] = None,
+ ):
+ _bot_a_id = bot_a_id or os.environ.get("E2E_FEISHU_BOT_A_ID", "")
+ _chat_id = chat_id or os.environ.get("E2E_FEISHU_CHAT_ID", "")
+ super().__init__(bot_a_id=_bot_a_id, channel_id=_chat_id)
+ self.app_id = app_id or os.environ.get("E2E_FEISHU_BOT_B_APP_ID", "")
+ self.app_secret = app_secret or os.environ.get("E2E_FEISHU_BOT_B_APP_SECRET", "")
+ self._session: Optional[aiohttp.ClientSession] = None
+ self._tenant_token: str = ""
+ self._token_expires: float = 0
+
+ async def _refresh_token(self) -> None:
+ """Get or refresh tenant access token."""
+ if time.monotonic() < self._token_expires - 60:
+ return # Still valid
+
+ assert self._session is not None
+ async with self._session.post(
+ f"{FEISHU_API}/auth/v3/tenant_access_token/internal",
+ json={"app_id": self.app_id, "app_secret": self.app_secret},
+ ) as resp:
+ data = await resp.json()
+ if data.get("code") != 0:
+ raise RuntimeError(f"Feishu auth failed: {data}")
+ self._tenant_token = data["tenant_access_token"]
+ self._token_expires = time.monotonic() + data.get("expire", 7200)
+ logger.info("Feishu Bot B token refreshed")
+
+ def _headers(self) -> dict:
+ return {
+ "Authorization": f"Bearer {self._tenant_token}",
+ "Content-Type": "application/json",
+ }
+
+ async def setup(self) -> None:
+ if not self.app_id or not self.app_secret:
+ raise RuntimeError("Feishu Bot B credentials not configured")
+
+ self._session = aiohttp.ClientSession()
+ await self._refresh_token()
+ logger.info("Feishu Bot B authenticated")
+
+ async def teardown(self) -> None:
+ if self._session:
+ await self._session.close()
+ self._session = None
+
+ async def send_message(self, text: str, thread_id: Optional[str] = None) -> str:
+ assert self._session is not None, "Driver not set up"
+ await self._refresh_token()
+
+ payload: dict = {
+ "receive_id": self.channel_id,
+ "msg_type": "text",
+ "content": json.dumps({"text": text}),
+ }
+ if thread_id:
+ payload["reply_in_thread"] = True
+
+ async with self._session.post(
+ f"{FEISHU_API}/im/v1/messages",
+ headers=self._headers(),
+ params={"receive_id_type": "chat_id"},
+ json=payload,
+ ) as resp:
+ data = await resp.json()
+ if data.get("code") != 0:
+ raise RuntimeError(f"Feishu send failed: {data}")
+ return data["data"]["message_id"]
+
+ async def get_messages_after(self, after_ts: str, limit: int = 20) -> list[dict]:
+ assert self._session is not None, "Driver not set up"
+ await self._refresh_token()
+
+ # Feishu uses container_id (chat_id) for message list
+ async with self._session.get(
+ f"{FEISHU_API}/im/v1/messages",
+ headers=self._headers(),
+ params={
+ "container_id_type": "chat",
+ "container_id": self.channel_id,
+ "page_size": limit,
+ "sort_type": "ByCreateTimeAsc",
+ },
+ ) as resp:
+ data = await resp.json()
+ if data.get("code") != 0:
+ logger.warning("Feishu get_messages failed: %s", data)
+ return []
+
+ items = data.get("data", {}).get("items", [])
+ # Filter to messages after our reference and normalize
+ result = []
+ found_reference = False
+ for item in items:
+ msg_id = item.get("message_id", "")
+ if msg_id == after_ts:
+ found_reference = True
+ continue
+ if not found_reference:
+ continue
+
+ # Parse content
+ content = item.get("body", {}).get("content", "{}")
+ try:
+ content_data = json.loads(content) if isinstance(content, str) else content
+ text = content_data.get("text", "")
+ except (json.JSONDecodeError, AttributeError):
+ text = str(content)
+
+ sender_id = item.get("sender", {}).get("id", "")
+ result.append(
+ {
+ "user": sender_id,
+ "text": text,
+ "ts": msg_id,
+ "raw": item,
+ }
+ )
+
+ return result
diff --git a/tests/e2e/drivers/slack_driver.py b/tests/e2e/drivers/slack_driver.py
new file mode 100644
index 000000000..1c5ea51e3
--- /dev/null
+++ b/tests/e2e/drivers/slack_driver.py
@@ -0,0 +1,67 @@
+"""Slack test driver using slack_sdk Web API."""
+
+import logging
+import os
+from typing import Optional
+
+from .base import PlatformDriver
+
+logger = logging.getLogger(__name__)
+
+
+class SlackDriver(PlatformDriver):
+ """Drive tests via Slack Web API using Bot B's token."""
+
+ def __init__(
+ self,
+ bot_b_token: Optional[str] = None,
+ bot_a_id: Optional[str] = None,
+ channel_id: Optional[str] = None,
+ ):
+ _bot_a_id = bot_a_id or os.environ.get("E2E_SLACK_BOT_A_ID", "")
+ _channel_id = channel_id or os.environ.get("E2E_SLACK_CHANNEL", "")
+ super().__init__(bot_a_id=_bot_a_id, channel_id=_channel_id)
+ self.token = bot_b_token or os.environ.get("E2E_SLACK_BOT_B_TOKEN", "")
+ self.client = None
+
+ async def setup(self) -> None:
+ try:
+ from slack_sdk.web.async_client import AsyncWebClient
+ except ImportError:
+ raise RuntimeError("slack_sdk not installed. Run: pip install slack_sdk")
+
+ if not self.token:
+ raise RuntimeError("Slack Bot B token not configured (E2E_SLACK_BOT_B_TOKEN)")
+
+ self.client = AsyncWebClient(token=self.token)
+ # Verify auth
+ auth = await self.client.auth_test()
+ logger.info(
+ "Slack Bot B authenticated as: %s (team: %s)",
+ auth["user"],
+ auth["team"],
+ )
+
+ async def teardown(self) -> None:
+ self.client = None
+
+ async def send_message(self, text: str, thread_id: Optional[str] = None) -> str:
+ assert self.client is not None, "Driver not set up"
+ kwargs = {"channel": self.channel_id, "text": text}
+ if thread_id:
+ kwargs["thread_ts"] = thread_id
+ resp = await self.client.chat_postMessage(**kwargs)
+ return resp["ts"]
+
+ async def get_messages_after(self, after_ts: str, limit: int = 20) -> list[dict]:
+ assert self.client is not None, "Driver not set up"
+ resp = await self.client.conversations_history(
+ channel=self.channel_id,
+ oldest=after_ts,
+ limit=limit,
+ inclusive=False,
+ )
+ messages = resp.get("messages", [])
+ # Slack returns newest first, reverse for chronological order
+ messages.reverse()
+ return messages
diff --git a/tests/e2e/integration_cases.py b/tests/e2e/integration_cases.py
new file mode 100644
index 000000000..74b2198a1
--- /dev/null
+++ b/tests/e2e/integration_cases.py
@@ -0,0 +1,61 @@
+"""Shared integration test cases for all platforms.
+
+Each platform test module imports these and runs them with its driver.
+This avoids duplicating test logic across slack/discord/feishu.
+"""
+
+import pytest
+
+
+class PlatformIntegrationTests:
+ """Mixin class with shared integration test cases.
+
+ Subclass must provide a `driver` fixture that returns a PlatformDriver.
+ """
+
+ @pytest.mark.asyncio
+ async def test_send_message_and_get_reply(self, driver):
+ """Bot B sends a message, Bot A replies."""
+ reply = await driver.send_and_wait_reply(
+ "Hello, please respond with exactly: PONG",
+ timeout=120,
+ )
+ assert "PONG" in reply.text.upper() or len(reply.text) > 0, f"Expected Bot A to reply, got: {reply.text!r}"
+
+ @pytest.mark.asyncio
+ async def test_start_command(self, driver):
+ """Bot B sends /start, Bot A replies with welcome."""
+ reply = await driver.send_command("start", timeout=30)
+ # /start should produce a welcome message (exact text varies by language)
+ assert len(reply.text) > 0, "Expected non-empty reply from /start"
+
+ @pytest.mark.asyncio
+ async def test_cwd_command(self, driver):
+ """Bot B sends /cwd, Bot A replies with current working directory."""
+ reply = await driver.send_command("cwd", timeout=30)
+ assert "/" in reply.text or "cwd" in reply.text.lower(), f"Expected CWD path in reply, got: {reply.text!r}"
+
+ @pytest.mark.asyncio
+ async def test_clear_command(self, driver):
+ """Bot B sends /clear, Bot A confirms session cleared."""
+ reply = await driver.send_command("clear", timeout=30)
+ assert len(reply.text) > 0, "Expected confirmation from /clear"
+
+ @pytest.mark.asyncio
+ async def test_thread_continuation(self, driver):
+ """Bot B sends a message, then continues in the same thread."""
+ # First message
+ reply1 = await driver.send_and_wait_reply(
+ "Please respond with: FIRST",
+ timeout=120,
+ )
+ assert reply1.message_id, "Expected a message ID for threading"
+
+ # Follow-up in the thread (use reply's thread_id or message_id)
+ thread_id = reply1.thread_id or reply1.message_id
+ reply2 = await driver.send_and_wait_reply(
+ "Now respond with: SECOND",
+ timeout=120,
+ thread_id=thread_id,
+ )
+ assert len(reply2.text) > 0, "Expected Bot A to reply in thread"
diff --git a/tests/e2e/test_discord_integration.py b/tests/e2e/test_discord_integration.py
new file mode 100644
index 000000000..439857092
--- /dev/null
+++ b/tests/e2e/test_discord_integration.py
@@ -0,0 +1,24 @@
+"""Discord platform integration E2E tests.
+
+Requires:
+- E2E_DISCORD_BOT_B_TOKEN, E2E_DISCORD_CHANNEL, E2E_DISCORD_BOT_A_ID
+- Bot A running in Docker with Discord connection
+- Bot B in the same server/channel
+"""
+
+import pytest
+
+from tests.e2e.integration_cases import PlatformIntegrationTests
+
+
+class TestDiscordIntegration(PlatformIntegrationTests):
+ """Run shared integration tests against Discord platform."""
+
+ @pytest.fixture(autouse=True)
+ def _use_driver(self, discord_driver):
+ self._driver = discord_driver
+
+ @pytest.fixture
+ def driver(self):
+ return self._driver
diff --git a/tests/e2e/test_feishu_integration.py b/tests/e2e/test_feishu_integration.py
new file mode 100644
index 000000000..c0048d249
--- /dev/null
+++ b/tests/e2e/test_feishu_integration.py
@@ -0,0 +1,24 @@
+"""Feishu platform integration E2E tests.
+
+Requires:
+- E2E_FEISHU_BOT_B_APP_ID, E2E_FEISHU_BOT_B_APP_SECRET, E2E_FEISHU_CHAT_ID, E2E_FEISHU_BOT_A_ID
+- Bot A running in Docker with Feishu connection
+- Bot B in the same chat
+"""
+
+import pytest
+
+from tests.e2e.integration_cases import PlatformIntegrationTests
+
+
+class TestFeishuIntegration(PlatformIntegrationTests):
+ """Run shared integration tests against Feishu platform."""
+
+ @pytest.fixture(autouse=True)
+ def _use_driver(self, feishu_driver):
+ self._driver = feishu_driver
+
+ @pytest.fixture
+ def driver(self):
+ return self._driver
diff --git a/tests/e2e/test_slack_integration.py b/tests/e2e/test_slack_integration.py
new file mode 100644
index 000000000..e4df5f31b
--- /dev/null
+++ b/tests/e2e/test_slack_integration.py
@@ -0,0 +1,24 @@
+"""Slack platform integration E2E tests.
+
+Requires:
+- E2E_SLACK_BOT_B_TOKEN, E2E_SLACK_CHANNEL, E2E_SLACK_BOT_A_ID
+- Bot A running in Docker with Slack connection
+- Bot B in the same channel
+"""
+
+import pytest
+
+from tests.e2e.integration_cases import PlatformIntegrationTests
+
+
+class TestSlackIntegration(PlatformIntegrationTests):
+ """Run shared integration tests against Slack platform."""
+
+ @pytest.fixture(autouse=True)
+ def _use_driver(self, slack_driver):
+ self._driver = slack_driver
+
+ @pytest.fixture
+ def driver(self):
+ return self._driver
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index f78df4b89..628aa94cc 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -562,6 +562,97 @@ def setup_first_bind_code():
return jsonify(api.get_first_bind_code())
+# =============================================================================
+# E2E Test-Only Endpoints (gated by E2E_TEST_MODE env var)
+# =============================================================================
+
+import os as _os
+
+if _os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):
+
+ @app.route("/e2e/simulate-interaction", methods=["POST"])
+ def e2e_simulate_interaction():
+ """Simulate a modal submission via the settings/config APIs.
+
+ Only registered when E2E_TEST_MODE=true.
+
+ NOTE: Button clicks (cmd_settings, cmd_routing, etc.) should be
+ triggered by sending text commands via Bot B (/settings, /routing, etc.).
+ This endpoint handles modal *submissions* that Bot B cannot trigger
+ because they require UI interaction (select dropdowns, click Save).
+
+ The UI server and the service process are separate processes, so this
+ endpoint operates through the SettingsStore (shared JSON file) rather
+ than invoking the controller directly.
+
+ JSON fields:
+ action (str): "settings_submit" | "routing_submit" | "cwd_submit"
+ modal_values (dict): the values to submit
+ """
+ from vibe import api as vibe_api
+ from config.v2_settings import SettingsStore
+
+ payload = request.json or {}
+ action = payload.get("action", "")
+ modal_values = payload.get("modal_values", {})
+
+ if not action:
+ return jsonify({"ok": False, "error": "action required"}), 400
+
+ try:
+ if action == "settings_submit":
+ # Write settings via the existing settings API
+ result = vibe_api.save_settings(modal_values)
+ return jsonify({"ok": True, "action": action, "result": result})
+
+ elif action == "routing_submit":
+ # Write routing config for a specific channel/user
+ channel_id = modal_values.get("channel_id") or modal_values.get("settings_key")
+ if not channel_id:
+ return jsonify({"ok": False, "error": "channel_id required in modal_values"}), 400
+
+ store = SettingsStore.get_instance()
+ store.maybe_reload()
+ ch = store.settings.channels.get(channel_id)
+ if ch:
+ from config.v2_settings import RoutingSettings
+
+ ch.routing = RoutingSettings(
+ agent_backend=modal_values.get("backend", "opencode"),
+ opencode_agent=modal_values.get("opencode_agent"),
+ opencode_model=modal_values.get("opencode_model"),
+ opencode_reasoning_effort=modal_values.get("opencode_reasoning_effort"),
+ claude_agent=modal_values.get("claude_agent"),
+ claude_model=modal_values.get("claude_model"),
+ codex_model=modal_values.get("codex_model"),
+ codex_reasoning_effort=modal_values.get("codex_reasoning_effort"),
+ )
+ store.save()
+ return jsonify({"ok": True, "action": action})
+ else:
+ return jsonify({"ok": False, "error": f"channel {channel_id} not found in settings"}), 404
+
+ elif action == "cwd_submit":
+ # Update CWD via config API
+ new_cwd = modal_values.get("cwd", "/tmp")
+ result = vibe_api.save_config({"runtime": {"default_cwd": new_cwd}})
+ return jsonify({"ok": True, "action": action, "result": result})
+
+ else:
+ return jsonify({"ok": False, "error": f"unknown action: {action}"}), 400
+
+ except Exception as e:
+ logger.exception("E2E simulate-interaction failed")
+ return jsonify({"ok": False, "error": str(e)}), 500
+
+ @app.route("/e2e/ping", methods=["GET"])
+ def e2e_ping():
+ """Simple check that E2E test mode is active."""
+ return jsonify({"ok": True, "e2e_test_mode": True})
+
+ logger.info("E2E_TEST_MODE enabled: /e2e/* endpoints registered")
+
+
# =============================================================================
# Static Files (SPA)
# =============================================================================