Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: don't gate sidebar navigation on email verification (#1613)

Hiep Leddcf5881d216
diff --git a/.pr/a1.gif b/.pr/a1.gif
deleted file mode 100644
index b03ff96b5d..0000000000
Binary files a/.pr/a1.gif and /dev/null differ
diff --git a/.pr/a2.gif b/.pr/a2.gif
deleted file mode 100644
index 88a51865f6..0000000000
Binary files a/.pr/a2.gif and /dev/null differ
diff --git a/.pr/a3.gif b/.pr/a3.gif
deleted file mode 100644
index 1a4d912156..0000000000
Binary files a/.pr/a3.gif and /dev/null differ
diff --git a/.pr/a4.gif b/.pr/a4.gif
deleted file mode 100644
index 1f5d82fcba..0000000000
Binary files a/.pr/a4.gif and /dev/null differ
diff --git a/.pr/a5.gif b/.pr/a5.gif
deleted file mode 100644
index 8b6237f71b..0000000000
Binary files a/.pr/a5.gif and /dev/null differ
diff --git a/.pr/b1.gif b/.pr/b1.gif
deleted file mode 100644
index 0c91fe413e..0000000000
Binary files a/.pr/b1.gif and /dev/null differ
diff --git a/.pr/b2.gif b/.pr/b2.gif
deleted file mode 100644
index ea3e3c6a3d..0000000000
Binary files a/.pr/b2.gif and /dev/null differ
diff --git a/.pr/b3.gif b/.pr/b3.gif
deleted file mode 100644
index f8bd14b405..0000000000
Binary files a/.pr/b3.gif and /dev/null differ
diff --git a/.pr/b4.gif b/.pr/b4.gif
deleted file mode 100644
index ce5b2ad6da..0000000000
Binary files a/.pr/b4.gif and /dev/null differ
diff --git a/.pr/b5.gif b/.pr/b5.gif
deleted file mode 100644
index b436fa6066..0000000000
Binary files a/.pr/b5.gif and /dev/null differ
diff --git a/.pr/c1.gif b/.pr/c1.gif
deleted file mode 100644
index af24e3dda1..0000000000
Binary files a/.pr/c1.gif and /dev/null differ
diff --git a/.pr/c2.gif b/.pr/c2.gif
deleted file mode 100644
index d9deeb10bb..0000000000
Binary files a/.pr/c2.gif and /dev/null differ
diff --git a/.pr/c3.gif b/.pr/c3.gif
deleted file mode 100644
index 58e95f23c3..0000000000
Binary files a/.pr/c3.gif and /dev/null differ
diff --git a/.pr/c4.gif b/.pr/c4.gif
deleted file mode 100644
index 62b85291d9..0000000000
Binary files a/.pr/c4.gif and /dev/null differ
diff --git a/.pr/c5.gif b/.pr/c5.gif
deleted file mode 100644
index eee03413af..0000000000
Binary files a/.pr/c5.gif and /dev/null differ
diff --git a/.pr/capture-a-series.mjs b/.pr/capture-a-series.mjs
deleted file mode 100644
index a8c612bd9b..0000000000
--- a/.pr/capture-a-series.mjs
+++ /dev/null
@@ -1,601 +0,0 @@
-import { chromium } from "@playwright/test";
-import { spawnSync } from "node:child_process";
-import fs from "node:fs";
-import path from "node:path";
-
-const FRONTEND_URL = process.env.FRONTEND_URL ?? "http://127.0.0.1:3101";
-const BACKEND_URL = process.env.BACKEND_URL ?? "http://127.0.0.1:18110";
-const SESSION_API_KEY =
- process.env.SESSION_API_KEY ?? "codex-mcp-gif-isolated-key";
-const MOCK_LLM_URL = process.env.MOCK_LLM_URL ?? "http://127.0.0.1:19999";
-const MOCK_MODEL = "openai/mock-test-model";
-const MOCK_LLM_API_KEY = "mock-api-key-for-testing";
-const RUN_TAG =
- process.env.RUN_TAG ??
- new Date()
- .toISOString()
- .replace(/[-:TZ.]/g, "")
- .slice(0, 14);
-const ROOT = path.resolve(import.meta.dirname, "..");
-const PR_DIR = path.resolve(import.meta.dirname);
-
-const flows = [
- {
- id: "a1",
- title: "a1: Local backend + unauthenticated weather MCP",
- serverName: "a1_weather",
- url: "http://127.0.0.1:19200/mcp",
- auth: { mode: "None" },
- toolName: "weather_forecast",
- toolArgs: { city: "Pittsburgh" },
- prompt: "Use the weather MCP to get the Pittsburgh forecast.",
- finalText: "A1 local weather MCP complete.",
- successToken: "weather_fixture_success",
- },
- {
- id: "a2",
- title: "a2: Local backend + bearer-token MCP",
- serverName: "a2_elevenlabs",
- url: "http://127.0.0.1:19201/mcp",
- auth: { mode: "Bearer token", token: "elevenlabs-test-token" },
- toolName: "elevenlabs_voice_note",
- toolArgs: { text: "Canvas demo voice note" },
- prompt: "Use the elevenlabs MCP to draft a voice note.",
- finalText: "A2 bearer-token MCP complete.",
- successToken: "elevenlabs_fixture_success",
- },
- {
- id: "a3",
- title: "a3: Local backend + header-authenticated MCP",
- serverName: "a3_datadog",
- url: "http://127.0.0.1:19202/mcp",
- auth: {
- mode: "Header",
- headers: "DD-API-KEY=datadog-api-key\nDD-APPLICATION-KEY=datadog-app-key",
- },
- toolName: "datadog_metric_snapshot",
- toolArgs: { service: "canvas-api" },
- prompt: "Use the datadog MCP to inspect canvas-api metrics.",
- finalText: "A3 header-auth MCP complete.",
- successToken: "datadog_fixture_success",
- },
- {
- id: "a4",
- title: "a4: Local backend + OAuth client-id/secret MCP",
- serverName: "a4_notion",
- url: "http://127.0.0.1:19203/mcp",
- auth: {
- mode: "OAuth",
- clientAuthMethod: "Client secret POST",
- clientId: "notion-client",
- clientSecret: "notion-secret",
- scopes: "read:mock",
- },
- toolName: "notion_page_lookup",
- toolArgs: { title: "Roadmap" },
- prompt: "Use the notion MCP to look up the Roadmap page.",
- finalText: "A4 OAuth client-secret MCP complete.",
- successToken: "notion_fixture_success",
- },
- {
- id: "a5",
- title: "a5: Local backend + dynamic OAuth MCP",
- serverName: "a5_linear",
- url: "http://127.0.0.1:19204/mcp",
- auth: { mode: "OAuth", scopes: "read:mock write:mock" },
- toolName: "linear_issue_summary",
- toolArgs: { issue_key: "LIN-42" },
- prompt: "Use the linear MCP to summarize issue LIN-42.",
- finalText: "A5 dynamic OAuth MCP complete.",
- successToken: "linear_fixture_success",
- },
-];
-
-async function adminPost(pathname, body = undefined) {
- const response = await fetch(`${MOCK_LLM_URL}${pathname}`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: body === undefined ? undefined : JSON.stringify(body),
- });
- if (!response.ok) {
- throw new Error(
- `Mock LLM ${pathname} failed: ${response.status} ${await response.text()}`,
- );
- }
- return response.json().catch(() => ({}));
-}
-
-async function registerTrajectory(flow) {
- await adminPost("/admin/reset");
- await adminPost("/admin/trajectory/register", {
- name: flow.id,
- turns: [
- { tool_call: { name: flow.toolName, arguments: flow.toolArgs } },
- {
- text: `${flow.finalText} The MCP observation contains ${flow.successToken}.`,
- },
- ],
- });
- await adminPost("/admin/trajectory/activate", { name: flow.id });
-}
-
-async function setupPage() {
- const browser = await chromium.launch({
- headless: true,
- args: [
- "--disable-dev-shm-usage",
- "--disable-gpu",
- "--renderer-process-limit=1",
- "--single-process",
- "--no-zygote",
- ],
- });
- const context = await browser.newContext({
- baseURL: FRONTEND_URL,
- viewport: { width: 960, height: 600 },
- deviceScaleFactor: 1,
- });
- await context.addInitScript(
- ({ apiKey, backendUrl }) => {
- window.localStorage.setItem("analytics-consent", "false");
- window.localStorage.setItem("openhands-telemetry-consent", "denied");
- window.localStorage.setItem("openhands-telemetry-first-use", "true");
- window.localStorage.setItem("openhands-onboarded", "1");
- const active = { backendId: "default-local", orgId: null };
- window.localStorage.setItem(
- "openhands-backends",
- JSON.stringify([
- {
- id: "default-local",
- name: "Local",
- host: backendUrl,
- apiKey,
- kind: "local",
- },
- ]),
- );
- window.localStorage.setItem(
- "openhands-active-backend",
- JSON.stringify(active),
- );
- window.sessionStorage.setItem(
- "openhands-active-backend",
- JSON.stringify(active),
- );
-
- window.open = (url) => {
- const mount = () => {
- const frame = document.createElement("iframe");
- frame.setAttribute("data-testid", "mcp-oauth-hidden-popup");
- frame.style.position = "fixed";
- frame.style.width = "1px";
- frame.style.height = "1px";
- frame.style.opacity = "0";
- frame.style.pointerEvents = "none";
- frame.style.left = "-10px";
- frame.style.bottom = "-10px";
- document.body.appendChild(frame);
- if (url && url !== "about:blank") frame.src = String(url);
- return frame;
- };
- let frame = document.body ? mount() : null;
- const ensureFrame = () => {
- if (!frame) frame = mount();
- return frame;
- };
- return {
- closed: false,
- close() {
- this.closed = true;
- frame?.remove();
- },
- get location() {
- return ensureFrame().contentWindow?.location;
- },
- set location(value) {
- ensureFrame().src = String(value);
- },
- focus() {},
- };
- };
- },
- { apiKey: SESSION_API_KEY, backendUrl: BACKEND_URL },
- );
- const page = await context.newPage();
- await page.route("**/*", async (route) => {
- const request = route.request();
- const url = new URL(request.url());
- const isBackend =
- url.origin === new URL(BACKEND_URL).origin ||
- (url.origin === FRONTEND_URL && url.pathname.startsWith("/api/"));
- if (!isBackend) {
- await route.continue();
- return;
- }
- await route.continue({
- headers: {
- ...request.headers(),
- "X-Session-API-Key": SESSION_API_KEY,
- },
- });
- });
- return { browser, context, page };
-}
-
-async function waitForTestId(page, testId, timeout = 30_000) {
- await page.getByTestId(testId).waitFor({ state: "visible", timeout });
-}
-
-async function dismissBlockingModals(page) {
- try {
- const form = page.getByTestId("telemetry-consent-form");
- await form.waitFor({ state: "visible", timeout: 2_000 });
- await page.getByTestId("confirm-telemetry-preferences").click();
- await form.waitFor({ state: "hidden", timeout: 5_000 });
- } catch {}
- try {
- const form = page.getByTestId("user-capture-consent-form");
- await form.waitFor({ state: "visible", timeout: 2_000 });
- await form.getByRole("button", { name: "Confirm preferences" }).click();
- await form.waitFor({ state: "hidden", timeout: 5_000 });
- } catch {}
- try {
- const skip = page.getByTestId("onboarding-skip");
- await skip.waitFor({ state: "visible", timeout: 2_000 });
- await skip.click();
- await page.getByTestId("onboarding-modal").waitFor({
- state: "hidden",
- timeout: 5_000,
- });
- } catch {}
- try {
- const close = page.getByTestId("onboarding-hello-close");
- await close.waitFor({ state: "visible", timeout: 2_000 });
- await close.click();
- await page.getByTestId("onboarding-modal").waitFor({
- state: "hidden",
- timeout: 5_000,
- });
- } catch {}
-}
-
-async function gotoPage(page, pathname) {
- let lastError;
- for (let attempt = 1; attempt <= 3; attempt += 1) {
- try {
- await page.goto(pathname, {
- waitUntil: "domcontentloaded",
- timeout: 45_000,
- });
- return;
- } catch (error) {
- lastError = error;
- await page.waitForTimeout(1_000 * attempt).catch(() => {});
- }
- }
- throw lastError;
-}
-
-async function selectDropdownOption(page, comboboxLabel, optionText) {
- const combobox = page.getByRole("combobox", { name: comboboxLabel });
- await combobox.waitFor({ state: "visible", timeout: 10_000 });
- await combobox.click();
- try {
- await combobox.fill("");
- } catch {}
- const option = page.getByRole("option", { name: optionText });
- await option.waitFor({ state: "visible", timeout: 10_000 });
- await option.click();
-}
-
-async function setChatInput(page, text) {
- await page.evaluate((inputText) => {
- const el = document.querySelector('[data-testid="chat-input"]');
- if (!(el instanceof HTMLElement)) {
- throw new Error("chat-input not found");
- }
- el.focus();
- el.textContent = inputText;
- el.dispatchEvent(
- new InputEvent("input", {
- bubbles: true,
- data: inputText,
- inputType: "insertText",
- }),
- );
- }, text);
-}
-
-async function waitForOutputText(page, text, timeout = 90_000) {
- const started = Date.now();
- while (Date.now() - started < timeout) {
- const found = await page.evaluate((needle) => {
- const selectors = [
- '[data-testid="agent-message"]',
- '[data-testid="environment-message"]',
- '[data-testid="model-messages"]',
- '[data-testid="event-group"]',
- '[data-testid="error-message-banner"]',
- ];
- return selectors.some((selector) =>
- Array.from(document.querySelectorAll(selector)).some((node) =>
- node.textContent?.includes(needle),
- ),
- );
- }, text);
- if (found) return;
- await page.waitForTimeout(1_000);
- }
- throw new Error(`Timed out waiting for output text: ${text}`);
-}
-
-function frameDir(flowId) {
- return path.join(PR_DIR, "frames", flowId);
-}
-
-async function capture(page, flowId, label) {
- const dir = frameDir(flowId);
- fs.mkdirSync(dir, { recursive: true });
- const count = fs
- .readdirSync(dir)
- .filter((name) => name.endsWith(".png")).length;
- const file = path.join(
- dir,
- `${String(count + 1).padStart(3, "0")}-${label}.png`,
- );
- await page.screenshot({ path: file, fullPage: false });
- return file;
-}
-
-function makeGif(flowId) {
- const frames = fs
- .readdirSync(frameDir(flowId))
- .filter((name) => name.endsWith(".png"))
- .sort()
- .map((name) => path.join(frameDir(flowId), name));
- const out = path.join(PR_DIR, `${flowId}.gif`);
- const script = String.raw`
-from PIL import Image
-import sys
-out = sys.argv[1]
-paths = sys.argv[2:]
-imgs = []
-for path in paths:
- img = Image.open(path).convert("RGB")
- max_width = 960
- if img.width > max_width:
- ratio = max_width / img.width
- img = img.resize((max_width, int(img.height * ratio)), Image.Resampling.LANCZOS)
- imgs.append(img.convert("P", palette=Image.Palette.ADAPTIVE, colors=128))
-durations = [900] * len(imgs)
-if durations:
- durations[-1] = 1800
-imgs[0].save(out, save_all=True, append_images=imgs[1:], duration=durations, loop=0, optimize=True)
-`;
- const result = spawnSync("python", ["-c", script, out, ...frames], {
- cwd: ROOT,
- encoding: "utf8",
- });
- if (result.status !== 0) {
- throw new Error(`GIF creation failed for ${flowId}: ${result.stderr}`);
- }
- return out;
-}
-
-async function ensureLlmSettings() {
- const profileName = `mcp-gif-${RUN_TAG}`;
- const saveResponse = await fetch(
- `${BACKEND_URL}/api/profiles/${encodeURIComponent(profileName)}`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-Session-API-Key": SESSION_API_KEY,
- },
- body: JSON.stringify({
- llm: {
- model: MOCK_MODEL,
- api_key: MOCK_LLM_API_KEY,
- base_url: MOCK_LLM_URL,
- },
- include_secrets: true,
- }),
- },
- );
- if (!saveResponse.ok) {
- throw new Error(
- `POST /api/profiles failed: ${saveResponse.status} ${await saveResponse.text()}`,
- );
- }
-
- const activateResponse = await fetch(
- `${BACKEND_URL}/api/profiles/${encodeURIComponent(profileName)}/activate`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-Session-API-Key": SESSION_API_KEY,
- },
- },
- );
- if (!activateResponse.ok) {
- throw new Error(
- `POST /api/profiles/activate failed: ${activateResponse.status} ${await activateResponse.text()}`,
- );
- }
-
- const response = await fetch(`${BACKEND_URL}/api/settings`, {
- method: "PATCH",
- headers: {
- "Content-Type": "application/json",
- "X-Session-API-Key": SESSION_API_KEY,
- },
- body: JSON.stringify({
- agent_settings_diff: {
- llm: {
- model: MOCK_MODEL,
- api_key: MOCK_LLM_API_KEY,
- base_url: MOCK_LLM_URL,
- },
- },
- }),
- });
- if (!response.ok) {
- throw new Error(
- `PATCH /api/settings failed: ${response.status} ${await response.text()}`,
- );
- }
-}
-
-async function installMcpServer(page, context, flow) {
- const flowUrl =
- flow.auth.mode === "OAuth"
- ? flow.url
- : `${flow.url}?run=${RUN_TAG}-${flow.id}`;
- const flowName = `${flow.serverName}_${RUN_TAG}`;
-
- await gotoPage(page, "/mcp");
- await dismissBlockingModals(page);
- await waitForTestId(page, "mcp-page");
- await capture(page, flow.id, "mcp-page");
-
- await page.getByTestId("mcp-add-custom-server").click();
- await waitForTestId(page, "mcp-custom-editor");
- await capture(page, flow.id, "custom-modal");
-
- await selectDropdownOption(page, /Server Type/i, /^SHTTP$/i);
- await page.getByTestId("server-name-input").fill(flowName);
- await page.getByTestId("url-input").fill(flowUrl);
- await capture(page, flow.id, "server-url");
-
- if (flow.auth.mode !== "None") {
- await selectDropdownOption(page, /Authentication/i, flow.auth.mode);
- }
- if (flow.auth.mode === "Bearer token") {
- await page.getByTestId("api-key-input").fill(flow.auth.token);
- }
- if (flow.auth.mode === "Header") {
- await page.getByTestId("headers-input").fill(flow.auth.headers);
- }
- if (flow.auth.mode === "OAuth") {
- if (flow.auth.clientAuthMethod) {
- await selectDropdownOption(
- page,
- /OAuth client auth/i,
- flow.auth.clientAuthMethod,
- );
- }
- if (flow.auth.clientId) {
- await page.getByTestId("oauth-client-id-input").fill(flow.auth.clientId);
- }
- if (flow.auth.clientSecret) {
- await page
- .getByTestId("oauth-client-secret-input")
- .fill(flow.auth.clientSecret);
- }
- if (flow.auth.scopes) {
- await page.getByTestId("oauth-scopes-input").fill(flow.auth.scopes);
- }
- }
- await capture(page, flow.id, "auth-filled");
-
- const useRealPopup = process.env.MCP_GIF_REAL_POPUP === "1";
- let popupPromise = null;
- if (flow.auth.mode === "OAuth" && useRealPopup) {
- popupPromise = context
- .waitForEvent("page", { timeout: 10_000 })
- .catch(() => null);
- }
- await page.getByTestId("submit-button").click();
- if (flow.auth.mode === "OAuth" && !useRealPopup) {
- await page.waitForTimeout(3_000);
- await capture(page, flow.id, "oauth-submitted");
- }
- const popup = popupPromise ? await popupPromise : null;
- if (popup) {
- await popup
- .waitForLoadState("domcontentloaded", { timeout: 30_000 })
- .catch(() => {});
- if (!popup.isClosed()) {
- await popup.waitForTimeout(1_000).catch(() => {});
- }
- if (!popup.isClosed()) {
- await capture(popup, flow.id, "oauth-popup").catch(() => {});
- }
- }
-
- try {
- await page.getByTestId("mcp-custom-editor").waitFor({
- state: "hidden",
- timeout: flow.auth.mode === "OAuth" ? 60_000 : 30_000,
- });
- } catch (error) {
- await capture(page, flow.id, "install-still-open").catch(() => {});
- const modalText = await page
- .getByTestId("mcp-custom-editor")
- .innerText()
- .catch(() => "");
- throw new Error(
- `MCP install modal did not close for ${flow.id}. Text:\n${modalText}`,
- { cause: error },
- );
- }
- await waitForTestId(page, "mcp-installed-list");
- await capture(page, flow.id, "installed");
- if (popup && !popup.isClosed()) {
- await popup.close().catch(() => {});
- }
-}
-
-async function runConversation(page, flow) {
- await registerTrajectory(flow);
- await gotoPage(page, "/");
- await dismissBlockingModals(page);
- await waitForTestId(page, "home-chat-launcher");
- await capture(page, flow.id, "home");
- await setChatInput(page, flow.prompt);
- await capture(page, flow.id, "prompt");
- await page.getByTestId("submit-button").click();
- await page.waitForURL(/\/conversations\/.+/, { timeout: 30_000 });
- await capture(page, flow.id, "conversation-started");
- await waitForOutputText(page, flow.successToken, 90_000);
- await capture(page, flow.id, "tool-observation");
- await waitForOutputText(page, flow.finalText, 90_000);
- await capture(page, flow.id, "final-reply");
-}
-
-async function main() {
- fs.mkdirSync(PR_DIR, { recursive: true });
- const selectedIds = new Set(
- (process.env.FLOW_IDS ?? "")
- .split(",")
- .map((id) => id.trim())
- .filter(Boolean),
- );
- const selectedFlows =
- selectedIds.size === 0
- ? flows
- : flows.filter((flow) => selectedIds.has(flow.id));
- if (selectedFlows.length === 0) {
- throw new Error(`No matching flows for FLOW_IDS=${process.env.FLOW_IDS}`);
- }
- const { browser, context, page } = await setupPage();
- try {
- await ensureLlmSettings();
- for (const flow of selectedFlows) {
- fs.rmSync(frameDir(flow.id), { recursive: true, force: true });
- console.log(`Capturing ${flow.title}`);
- await installMcpServer(page, context, flow);
- await runConversation(page, flow);
- const gif = makeGif(flow.id);
- console.log(`Wrote ${path.relative(ROOT, gif)}`);
- }
- } finally {
- await browser.close();
- }
-}
-
-main().catch((error) => {
- console.error(error);
- process.exit(1);
-});
diff --git a/.pr/capture-b-series.mjs b/.pr/capture-b-series.mjs
deleted file mode 100644
index a485706dc7..0000000000
--- a/.pr/capture-b-series.mjs
+++ /dev/null
@@ -1,758 +0,0 @@
-import { chromium } from "@playwright/test";
-import { spawnSync } from "node:child_process";
-import fs from "node:fs";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const FRONTEND_URL = process.env.FRONTEND_URL ?? "http://127.0.0.1:3101";
-const LOCAL_BACKEND_URL = process.env.BACKEND_URL ?? "http://127.0.0.1:18110";
-const LOCAL_SESSION_API_KEY =
- process.env.SESSION_API_KEY ?? "codex-mcp-gif-isolated-key";
-const CLOUD_BACKEND_URL =
- process.env.CLOUD_BACKEND_URL ?? "https://app.all-hands.dev";
-const ALLOW_PERSONAL_CLOUD_SETTINGS_MUTATION =
- process.env.ALLOW_PERSONAL_CLOUD_SETTINGS_MUTATION === "1";
-const FIXTURE_PUBLIC_URL =
- process.env.FIXTURE_PUBLIC_URL ?? "https://statusquo-dr-ohmcp.ngrok-free.app";
-const MOCK_LLM_ADMIN_URL = process.env.MOCK_LLM_URL ?? "http://127.0.0.1:19999";
-const MOCK_LLM_BASE_URL =
- process.env.MOCK_LLM_BASE_URL ?? `${FIXTURE_PUBLIC_URL}/mock-llm`;
-const MOCK_MODEL = "openai/mock-test-model";
-const MOCK_LLM_API_KEY = "mock-api-key-for-testing";
-const RUN_TAG =
- process.env.RUN_TAG ??
- new Date()
- .toISOString()
- .replace(/[-:TZ.]/g, "")
- .slice(0, 14);
-const PR_DIR = path.dirname(fileURLToPath(import.meta.url));
-const ROOT = path.resolve(PR_DIR, "..");
-const LLM_ENV_FILE =
- process.env.LLM_ENV_FILE ??
- (process.env.HOME ? path.join(process.env.HOME, ".env") : "");
-
-function readDotEnv(file) {
- if (!file || !fs.existsSync(file)) return {};
- return Object.fromEntries(
- fs
- .readFileSync(file, "utf8")
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => line && !line.startsWith("#"))
- .map((line) => line.replace(/^export\s+/, ""))
- .map((line) => {
- const eq = line.indexOf("=");
- if (eq === -1) return null;
- const key = line.slice(0, eq).trim();
- let value = line.slice(eq + 1).trim();
- if (
- (value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))
- ) {
- value = value.slice(1, -1);
- }
- return [key, value];
- })
- .filter(Boolean),
- );
-}
-
-const envFileValues = readDotEnv(LLM_ENV_FILE);
-function configuredEnv(name) {
- return process.env[name] ?? envFileValues[name];
-}
-
-const CONFIGURED_LLM_MODEL = configuredEnv("LLM_MODEL");
-const CONFIGURED_LLM_API_KEY = configuredEnv("LLM_API_KEY");
-const CONFIGURED_LLM_BASE_URL = configuredEnv("LLM_BASE_URL");
-const USE_CONFIGURED_LLM = Boolean(
- CONFIGURED_LLM_MODEL || CONFIGURED_LLM_API_KEY || CONFIGURED_LLM_BASE_URL,
-);
-if (USE_CONFIGURED_LLM && (!CONFIGURED_LLM_MODEL || !CONFIGURED_LLM_API_KEY)) {
- throw new Error("Configured LLM requires LLM_MODEL and LLM_API_KEY.");
-}
-const CAPTURE_LLM_MODEL = CONFIGURED_LLM_MODEL ?? MOCK_MODEL;
-const CAPTURE_LLM_API_KEY = CONFIGURED_LLM_API_KEY ?? MOCK_LLM_API_KEY;
-const CAPTURE_LLM_BASE_URL = CONFIGURED_LLM_BASE_URL ?? MOCK_LLM_BASE_URL;
-
-const flows = [
- {
- id: "b1",
- title: "b1: Cloud backend + unauthenticated weather MCP",
- serverName: "b1_weather",
- url: `${FIXTURE_PUBLIC_URL}/weather/mcp`,
- auth: { mode: "None" },
- toolName: "weather_forecast",
- toolArgs: { city: "Pittsburgh" },
- prompt: "Use the weather MCP to get the Pittsburgh forecast.",
- finalText: "B1 cloud weather MCP complete.",
- successToken: "weather_fixture_success",
- },
- {
- id: "b2",
- title: "b2: Cloud backend + bearer-token MCP",
- serverName: "b2_elevenlabs",
- url: `${FIXTURE_PUBLIC_URL}/elevenlabs/mcp`,
- auth: { mode: "Bearer token", token: "elevenlabs-test-token" },
- toolName: "elevenlabs_voice_note",
- toolArgs: { text: "Canvas demo voice note" },
- prompt: "Use the elevenlabs MCP to draft a voice note.",
- finalText: "B2 cloud bearer-token MCP complete.",
- successToken: "elevenlabs_fixture_success",
- },
- {
- id: "b3",
- title: "b3: Cloud backend + header-authenticated MCP",
- serverName: "b3_datadog",
- url: `${FIXTURE_PUBLIC_URL}/datadog/mcp`,
- auth: {
- mode: "Header",
- headers: "DD-API-KEY=datadog-api-key\nDD-APPLICATION-KEY=datadog-app-key",
- },
- toolName: "datadog_metric_snapshot",
- toolArgs: { service: "canvas-api" },
- prompt: "Use the datadog MCP to inspect canvas-api metrics.",
- finalText: "B3 cloud header-auth MCP complete.",
- successToken: "datadog_fixture_success",
- },
- {
- id: "b4",
- title: "b4: Cloud backend + OAuth client-id/secret MCP",
- serverName: "b4_notion",
- url: `${FIXTURE_PUBLIC_URL}/notion/mcp`,
- auth: {
- mode: "OAuth",
- clientAuthMethod: "Client secret POST",
- clientId: "notion-client",
- clientSecret: "notion-secret",
- scopes: "read:mock",
- },
- toolName: "notion_page_lookup",
- toolArgs: { title: "Roadmap" },
- prompt: "Use the notion MCP to look up the Roadmap page.",
- finalText: "B4 cloud OAuth client-secret MCP complete.",
- successToken: "notion_fixture_success",
- },
- {
- id: "b5",
- title: "b5: Cloud backend + dynamic OAuth MCP",
- serverName: "b5_linear",
- url: `${FIXTURE_PUBLIC_URL}/linear/mcp`,
- auth: { mode: "OAuth", scopes: "read:mock write:mock" },
- toolName: "linear_issue_summary",
- toolArgs: { issue_key: "LIN-42" },
- prompt: "Use the linear MCP to summarize issue LIN-42.",
- finalText: "B5 cloud dynamic OAuth MCP complete.",
- successToken: "linear_fixture_success",
- },
-];
-
-function readCloudApiKey() {
- if (process.env.OPENHANDS_CLOUD_API_KEY)
- return process.env.OPENHANDS_CLOUD_API_KEY;
- if (process.env.OPENHANDS_API_KEY) return process.env.OPENHANDS_API_KEY;
- const tokenFile = "/tmp/openhands-cloud-token.json";
- if (fs.existsSync(tokenFile)) {
- const token = JSON.parse(fs.readFileSync(tokenFile, "utf8"));
- return token.access_token ?? token.api_key ?? token.token;
- }
- throw new Error(
- "Missing cloud token. Set OPENHANDS_CLOUD_API_KEY or authorize device flow first.",
- );
-}
-
-const CLOUD_API_KEY = readCloudApiKey();
-
-function serverNameForFlow(flow) {
- return `${flow.serverName}_${RUN_TAG}`;
-}
-
-function modelToolNameForFlow(flow) {
- return `${serverNameForFlow(flow)}_${flow.toolName}`;
-}
-
-function conversationPrompt(flow) {
- if (!USE_CONFIGURED_LLM) return flow.prompt;
- return [
- `Call the MCP tool named ${modelToolNameForFlow(flow)} with these JSON arguments: ${JSON.stringify(flow.toolArgs)}.`,
- "Do not answer from memory. Wait for the MCP tool observation.",
- `After the tool observation, reply with exactly this full line: ${flow.finalText} The MCP observation contains ${flow.successToken}.`,
- ].join(" ");
-}
-
-async function adminPost(pathname, body = undefined) {
- const response = await fetch(`${MOCK_LLM_ADMIN_URL}${pathname}`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: body === undefined ? undefined : JSON.stringify(body),
- });
- if (!response.ok) {
- throw new Error(
- `Mock LLM ${pathname} failed: ${response.status} ${await response.text()}`,
- );
- }
- return response.json().catch(() => ({}));
-}
-
-async function registerTrajectory(flow) {
- if (USE_CONFIGURED_LLM) return;
- await adminPost("/admin/reset");
- await adminPost("/admin/trajectory/register", {
- name: flow.id,
- turns: [
- { text: flow.title },
- {
- tool_call: {
- name: modelToolNameForFlow(flow),
- arguments: flow.toolArgs,
- },
- },
- {
- text: `${flow.finalText} The MCP observation contains ${flow.successToken}.`,
- },
- ],
- });
- await adminPost("/admin/trajectory/activate", { name: flow.id });
-}
-
-async function cloudApi(pathname, options = {}) {
- const response = await fetch(`${CLOUD_BACKEND_URL}${pathname}`, {
- ...options,
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${CLOUD_API_KEY}`,
- ...(options.headers ?? {}),
- },
- });
- const text = await response.text();
- let payload;
- try {
- payload = text ? JSON.parse(text) : null;
- } catch {
- payload = text;
- }
- if (!response.ok) {
- throw new Error(
- `Cloud ${pathname} failed: ${response.status} ${
- typeof payload === "string" ? payload : JSON.stringify(payload)
- }`,
- );
- }
- return payload;
-}
-
-async function ensureCloudSettings() {
- const cloudUrl = new URL(CLOUD_BACKEND_URL);
- if (
- cloudUrl.hostname === "app.all-hands.dev" &&
- !ALLOW_PERSONAL_CLOUD_SETTINGS_MUTATION
- ) {
- throw new Error(
- "Refusing to mutate personal OpenHands Cloud settings. Use a feature deploy/dedicated Cloud backend, or set ALLOW_PERSONAL_CLOUD_SETTINGS_MUTATION=1 for this capture run.",
- );
- }
- await cloudApi("/api/v1/settings", {
- method: "POST",
- body: JSON.stringify({
- agent_settings_diff: {
- agent_kind: "openhands",
- agent: "CodeActAgent",
- llm: {
- model: CAPTURE_LLM_MODEL,
- api_key: CAPTURE_LLM_API_KEY,
- base_url: CAPTURE_LLM_BASE_URL,
- },
- },
- conversation_settings_diff: {
- max_iterations: 50,
- },
- }),
- });
-}
-
-async function cleanupCloudMcpServers() {
- const settings = await cloudApi("/api/v1/settings", { method: "GET" });
- const currentConfig =
- settings.agent_settings?.mcp_config ?? settings.mcp_config ?? {};
- if (!currentConfig || typeof currentConfig !== "object") return;
- const hasMcpServersWrapper =
- currentConfig.mcpServers &&
- typeof currentConfig.mcpServers === "object" &&
- !Array.isArray(currentConfig.mcpServers);
- const currentServers = hasMcpServersWrapper
- ? currentConfig.mcpServers
- : currentConfig;
- const flowPrefixes = flows.map((flow) => `${flow.serverName}_`);
- const filtered = Object.fromEntries(
- Object.entries(currentServers).filter(
- ([name]) =>
- !name.endsWith(`_${RUN_TAG}`) &&
- !flowPrefixes.some((prefix) => name.startsWith(prefix)),
- ),
- );
- if (Object.keys(filtered).length === Object.keys(currentServers).length)
- return;
- const nextConfig = hasMcpServersWrapper ? { mcpServers: filtered } : filtered;
- await cloudApi("/api/v1/settings", {
- method: "POST",
- body: JSON.stringify({
- agent_settings_diff: {
- mcp_config: Object.keys(filtered).length > 0 ? nextConfig : null,
- },
- }),
- });
-}
-
-async function setupPage() {
- const browser = await chromium.launch({
- headless: true,
- args: [
- "--disable-dev-shm-usage",
- "--disable-gpu",
- "--renderer-process-limit=1",
- "--single-process",
- "--no-zygote",
- ],
- });
- const context = await browser.newContext({
- baseURL: FRONTEND_URL,
- viewport: { width: 960, height: 600 },
- deviceScaleFactor: 1,
- });
- await context.addInitScript(
- ({ localApiKey, localBackendUrl, cloudApiKey, cloudBackendUrl }) => {
- window.localStorage.setItem("analytics-consent", "false");
- window.localStorage.setItem("openhands-telemetry-consent", "denied");
- window.localStorage.setItem("openhands-telemetry-first-use", "true");
- window.localStorage.setItem("openhands-onboarded", "1");
-
- const active = { backendId: "cloud-openhands", orgId: null };
- window.localStorage.setItem(
- "openhands-backends",
- JSON.stringify([
- {
- id: "default-local",
- name: "Local OAuth helper",
- host: localBackendUrl,
- apiKey: localApiKey,
- kind: "local",
- },
- {
- id: "cloud-openhands",
- name: "OpenHands Cloud",
- host: cloudBackendUrl,
- apiKey: cloudApiKey,
- kind: "cloud",
- },
- ]),
- );
- window.localStorage.setItem(
- "openhands-active-backend",
- JSON.stringify(active),
- );
- window.sessionStorage.setItem(
- "openhands-active-backend",
- JSON.stringify(active),
- );
-
- window.open = (url) => {
- const mount = () => {
- const frame = document.createElement("iframe");
- frame.setAttribute("data-testid", "mcp-oauth-hidden-popup");
- frame.style.position = "fixed";
- frame.style.width = "1px";
- frame.style.height = "1px";
- frame.style.opacity = "0";
- frame.style.pointerEvents = "none";
- frame.style.left = "-10px";
- frame.style.bottom = "-10px";
- document.body.appendChild(frame);
- if (url && url !== "about:blank") frame.src = String(url);
- return frame;
- };
- let frame = document.body ? mount() : null;
- const ensureFrame = () => {
- if (!frame) frame = mount();
- return frame;
- };
- return {
- closed: false,
- close() {
- this.closed = true;
- frame?.remove();
- },
- get location() {
- return ensureFrame().contentWindow?.location;
- },
- set location(value) {
- ensureFrame().src = String(value);
- },
- focus() {},
- };
- };
- },
- {
- localApiKey: LOCAL_SESSION_API_KEY,
- localBackendUrl: LOCAL_BACKEND_URL,
- cloudApiKey: CLOUD_API_KEY,
- cloudBackendUrl: CLOUD_BACKEND_URL,
- },
- );
- const page = await context.newPage();
- await page.route("**/*", async (route) => {
- const request = route.request();
- const url = new URL(request.url());
- const isLocalBackend =
- url.origin === new URL(LOCAL_BACKEND_URL).origin ||
- (url.origin === FRONTEND_URL && url.pathname.startsWith("/api/"));
- if (!isLocalBackend) {
- await route.continue();
- return;
- }
- await route.continue({
- headers: {
- ...request.headers(),
- "X-Session-API-Key": LOCAL_SESSION_API_KEY,
- },
- });
- });
- return { browser, context, page };
-}
-
-async function waitForTestId(page, testId, timeout = 30_000) {
- await page.getByTestId(testId).waitFor({ state: "visible", timeout });
-}
-
-async function dismissBlockingModals(page) {
- try {
- const form = page.getByTestId("telemetry-consent-form");
- await form.waitFor({ state: "visible", timeout: 2_000 });
- await page.getByTestId("confirm-telemetry-preferences").click();
- await form.waitFor({ state: "hidden", timeout: 5_000 });
- } catch {}
- try {
- const form = page.getByTestId("user-capture-consent-form");
- await form.waitFor({ state: "visible", timeout: 2_000 });
- await form.getByRole("button", { name: "Confirm preferences" }).click();
- await form.waitFor({ state: "hidden", timeout: 5_000 });
- } catch {}
- try {
- const skip = page.getByTestId("onboarding-skip");
- await skip.waitFor({ state: "visible", timeout: 2_000 });
- await skip.click();
- await page.getByTestId("onboarding-modal").waitFor({
- state: "hidden",
- timeout: 5_000,
- });
- } catch {}
- try {
- const close = page.getByTestId("onboarding-hello-close");
- await close.waitFor({ state: "visible", timeout: 2_000 });
- await close.click();
- await page.getByTestId("onboarding-modal").waitFor({
- state: "hidden",
- timeout: 5_000,
- });
- } catch {}
-}
-
-async function gotoPage(page, pathname) {
- let lastError;
- for (let attempt = 1; attempt <= 3; attempt += 1) {
- try {
- await page.goto(pathname, {
- waitUntil: "domcontentloaded",
- timeout: 45_000,
- });
- return;
- } catch (error) {
- lastError = error;
- await page.waitForTimeout(1_000 * attempt).catch(() => {});
- }
- }
- throw lastError;
-}
-
-async function selectDropdownOption(page, comboboxLabel, optionText) {
- const combobox = page.getByRole("combobox", { name: comboboxLabel });
- await combobox.waitFor({ state: "visible", timeout: 10_000 });
- await combobox.click();
- try {
- await combobox.fill("");
- } catch {}
- const option = page.getByRole("option", { name: optionText });
- await option.waitFor({ state: "visible", timeout: 10_000 });
- await option.click();
-}
-
-async function setChatInput(page, text) {
- await page.evaluate((inputText) => {
- const el = document.querySelector('[data-testid="chat-input"]');
- if (!(el instanceof HTMLElement)) {
- throw new Error("chat-input not found");
- }
- el.focus();
- el.textContent = inputText;
- el.dispatchEvent(
- new InputEvent("input", {
- bubbles: true,
- data: inputText,
- inputType: "insertText",
- }),
- );
- }, text);
-}
-
-function currentConversationId(page) {
- try {
- const pathname = new URL(page.url()).pathname;
- const match = pathname.match(/^\/conversations\/([^/]+)/);
- if (!match || match[1].startsWith("task-")) return null;
- return match[1];
- } catch {
- return null;
- }
-}
-
-async function cloudEventHistoryContains(conversationId, text) {
- if (!conversationId) return false;
- const params = new URLSearchParams({
- limit: "100",
- sort_order: "TIMESTAMP",
- });
- const page = await cloudApi(
- `/api/v1/conversation/${conversationId}/events/search?${params.toString()}`,
- { method: "GET" },
- );
- return JSON.stringify(page?.items ?? []).includes(text);
-}
-
-async function waitForOutputText(page, text, timeout = 180_000) {
- const started = Date.now();
- let lastCloudCheck = 0;
- while (Date.now() - started < timeout) {
- try {
- const found = await page.evaluate((needle) => {
- const selectors = [
- '[data-testid="agent-message"]',
- '[data-testid="environment-message"]',
- '[data-testid="model-messages"]',
- '[data-testid="event-group"]',
- '[data-testid="error-message-banner"]',
- ];
- return selectors.some((selector) =>
- Array.from(document.querySelectorAll(selector)).some((node) =>
- node.textContent?.includes(needle),
- ),
- );
- }, text);
- if (found) return;
- } catch {}
- if (Date.now() - lastCloudCheck > 2_000) {
- lastCloudCheck = Date.now();
- try {
- if (
- await cloudEventHistoryContains(currentConversationId(page), text)
- ) {
- return;
- }
- } catch {}
- }
- await page.waitForTimeout(1_000);
- }
- throw new Error(`Timed out waiting for output text: ${text}`);
-}
-
-function frameDir(flowId) {
- return path.join(PR_DIR, "frames", flowId);
-}
-
-async function capture(page, flowId, label) {
- const dir = frameDir(flowId);
- fs.mkdirSync(dir, { recursive: true });
- const count = fs
- .readdirSync(dir)
- .filter((name) => name.endsWith(".png")).length;
- const file = path.join(
- dir,
- `${String(count + 1).padStart(3, "0")}-${label}.png`,
- );
- await page.screenshot({ path: file, fullPage: false, timeout: 90_000 });
- return file;
-}
-
-function makeGif(flowId) {
- const frames = fs
- .readdirSync(frameDir(flowId))
- .filter((name) => name.endsWith(".png"))
- .sort()
- .map((name) => path.join(frameDir(flowId), name));
- const out = path.join(PR_DIR, `${flowId}.gif`);
- const script = String.raw`
-from PIL import Image
-import sys
-out = sys.argv[1]
-paths = sys.argv[2:]
-imgs = []
-for path in paths:
- img = Image.open(path).convert("RGB")
- max_width = 960
- if img.width > max_width:
- ratio = max_width / img.width
- img = img.resize((max_width, int(img.height * ratio)), Image.Resampling.LANCZOS)
- imgs.append(img.convert("P", palette=Image.Palette.ADAPTIVE, colors=128))
-durations = [900] * len(imgs)
-if durations:
- durations[-1] = 1800
-imgs[0].save(out, save_all=True, append_images=imgs[1:], duration=durations, loop=0, optimize=True)
-`;
- const result = spawnSync("python", ["-c", script, out, ...frames], {
- cwd: ROOT,
- encoding: "utf8",
- });
- if (result.status !== 0) {
- throw new Error(`GIF creation failed for ${flowId}: ${result.stderr}`);
- }
- return out;
-}
-
-async function installMcpServer(page, flow) {
- const flowUrl =
- flow.auth.mode === "OAuth"
- ? flow.url
- : `${flow.url}?run=${RUN_TAG}-${flow.id}`;
- const flowName = serverNameForFlow(flow);
-
- await gotoPage(page, "/mcp");
- await dismissBlockingModals(page);
- await waitForTestId(page, "mcp-page", 60_000);
- await capture(page, flow.id, "mcp-page");
-
- await page.getByTestId("mcp-add-custom-server").click();
- await waitForTestId(page, "mcp-custom-editor");
- await capture(page, flow.id, "custom-modal");
-
- await selectDropdownOption(page, /Server Type/i, /^SHTTP$/i);
- await page.getByTestId("server-name-input").fill(flowName);
- await page.getByTestId("url-input").fill(flowUrl);
- await capture(page, flow.id, "server-url");
-
- if (flow.auth.mode !== "None") {
- await selectDropdownOption(page, /Authentication/i, flow.auth.mode);
- }
- if (flow.auth.mode === "Bearer token") {
- await page.getByTestId("api-key-input").fill(flow.auth.token);
- }
- if (flow.auth.mode === "Header") {
- await page.getByTestId("headers-input").fill(flow.auth.headers);
- }
- if (flow.auth.mode === "OAuth") {
- if (flow.auth.clientAuthMethod) {
- await selectDropdownOption(
- page,
- /OAuth client auth/i,
- flow.auth.clientAuthMethod,
- );
- }
- if (flow.auth.clientId) {
- await page.getByTestId("oauth-client-id-input").fill(flow.auth.clientId);
- }
- if (flow.auth.clientSecret) {
- await page
- .getByTestId("oauth-client-secret-input")
- .fill(flow.auth.clientSecret);
- }
- if (flow.auth.scopes) {
- await page.getByTestId("oauth-scopes-input").fill(flow.auth.scopes);
- }
- }
- await capture(page, flow.id, "auth-filled");
-
- await page.getByTestId("submit-button").click();
- if (flow.auth.mode === "OAuth") {
- await page.waitForTimeout(3_000);
- await capture(page, flow.id, "oauth-submitted");
- }
-
- try {
- await page.getByTestId("mcp-custom-editor").waitFor({
- state: "hidden",
- timeout: flow.auth.mode === "OAuth" ? 90_000 : 45_000,
- });
- } catch (error) {
- await capture(page, flow.id, "install-still-open").catch(() => {});
- const modalText = await page
- .getByTestId("mcp-custom-editor")
- .innerText()
- .catch(() => "");
- throw new Error(
- `MCP install modal did not close for ${flow.id}. Text:\n${modalText}`,
- { cause: error },
- );
- }
- await waitForTestId(page, "mcp-installed-list");
- await capture(page, flow.id, "installed");
-}
-
-async function runConversation(page, flow) {
- await registerTrajectory(flow);
- await gotoPage(page, "/");
- await dismissBlockingModals(page);
- await waitForTestId(page, "home-chat-launcher", 60_000);
- await capture(page, flow.id, "home");
- await setChatInput(page, conversationPrompt(flow));
- await capture(page, flow.id, "prompt");
- await page.getByTestId("submit-button").click();
- await page.waitForURL(/\/conversations\/.+/, { timeout: 45_000 });
- await capture(page, flow.id, "conversation-provisioning");
- await page.waitForFunction(
- () => /^\/conversations\/(?!task-).+/.test(window.location.pathname),
- undefined,
- { timeout: 180_000 },
- );
- await waitForTestId(page, "chat-input", 180_000);
- await capture(page, flow.id, "conversation-started");
- await waitForOutputText(page, flow.successToken, 240_000);
- await capture(page, flow.id, "tool-observation");
- await waitForOutputText(page, flow.finalText, 120_000);
- await capture(page, flow.id, "final-reply");
-}
-
-async function main() {
- fs.mkdirSync(PR_DIR, { recursive: true });
- const selectedIds = new Set(
- (process.env.FLOW_IDS ?? "")
- .split(",")
- .map((id) => id.trim())
- .filter(Boolean),
- );
- const selectedFlows =
- selectedIds.size === 0
- ? flows
- : flows.filter((flow) => selectedIds.has(flow.id));
- if (selectedFlows.length === 0) {
- throw new Error(`No matching flows for FLOW_IDS=${process.env.FLOW_IDS}`);
- }
-
- await ensureCloudSettings();
- await cleanupCloudMcpServers();
-
- const { browser, page } = await setupPage();
- try {
- for (const flow of selectedFlows) {
- fs.rmSync(frameDir(flow.id), { recursive: true, force: true });
- console.log(`Capturing ${flow.title}`);
- await installMcpServer(page, flow);
- await runConversation(page, flow);
- const gif = makeGif(flow.id);
- console.log(`Wrote ${path.relative(ROOT, gif)}`);
- }
- } finally {
- await browser.close();
- }
-}
-
-main().catch((error) => {
- console.error(error);
- process.exit(1);
-});
diff --git a/.pr/capture-c-series.mjs b/.pr/capture-c-series.mjs
deleted file mode 100644
index a760bb7b7f..0000000000
--- a/.pr/capture-c-series.mjs
+++ /dev/null
@@ -1,782 +0,0 @@
-import { chromium } from "@playwright/test";
-import { spawnSync } from "node:child_process";
-import fs from "node:fs";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const FRONTEND_URL = process.env.FRONTEND_URL ?? "http://127.0.0.1:3101";
-const BACKEND_URL = process.env.BACKEND_URL ?? "http://127.0.0.1:18110";
-const SESSION_API_KEY =
- process.env.SESSION_API_KEY ?? "codex-mcp-gif-isolated-key";
-const MOCK_LLM_URL = process.env.MOCK_LLM_URL ?? "http://127.0.0.1:19999";
-const HUB_URL = process.env.HUB_URL ?? "http://localhost:8081";
-const HUB_API_URL = process.env.HUB_API_URL ?? "http://127.0.0.1:8081";
-const HUB_MCP_URL = process.env.HUB_MCP_URL ?? "http://127.0.0.1:8081/api/mcp";
-const HUB_TOKEN = process.env.HUB_TOKEN ?? "dev-token";
-const FIXTURE_DOCKER_HOST = process.env.FIXTURE_DOCKER_HOST ?? "172.18.0.1";
-const MOCK_MODEL = "openai/mock-test-model";
-const MOCK_LLM_API_KEY = "mock-api-key-for-testing";
-const RUN_TAG =
- process.env.RUN_TAG ??
- new Date()
- .toISOString()
- .replace(/[-:TZ.]/g, "")
- .slice(0, 14);
-const PR_DIR = path.dirname(fileURLToPath(import.meta.url));
-const ROOT = path.resolve(PR_DIR, "..");
-
-const flows = [
- {
- id: "c1",
- title: "c1: Integrations hub + unauthenticated weather MCP",
- integrationKey: `c1_weather_${RUN_TAG}`,
- displayName: `C1 Weather ${RUN_TAG}`,
- hubMode: "custom",
- fixtureUrl: `http://${FIXTURE_DOCKER_HOST}:19200/mcp`,
- credential: null,
- toolName: "weather_forecast",
- toolArgs: { city: "Pittsburgh" },
- prompt:
- "Use the integrations hub weather MCP to get the Pittsburgh forecast.",
- finalText: "C1 integrations hub weather MCP complete.",
- successToken: "weather_fixture_success",
- },
- {
- id: "c2",
- title: "c2: Integrations hub + bearer-token MCP",
- integrationKey: `c2_elevenlabs_${RUN_TAG}`,
- displayName: `C2 ElevenLabs ${RUN_TAG}`,
- hubMode: "custom",
- fixtureUrl: `http://${FIXTURE_DOCKER_HOST}:19201/mcp`,
- credential: { bearerToken: "elevenlabs-test-token" },
- toolName: "elevenlabs_voice_note",
- toolArgs: { text: "Canvas demo voice note" },
- prompt: "Use the integrations hub elevenlabs MCP to draft a voice note.",
- finalText: "C2 integrations hub bearer-token MCP complete.",
- successToken: "elevenlabs_fixture_success",
- },
- {
- id: "c3",
- title: "c3: Integrations hub + header-authenticated MCP",
- integrationKey: `c3_datadog_${RUN_TAG}`,
- displayName: `C3 Datadog ${RUN_TAG}`,
- hubMode: "custom",
- fixtureUrl: `http://${FIXTURE_DOCKER_HOST}:19202/mcp`,
- credential: { headerName: "DD-API-KEY", headerSecret: "datadog-api-key" },
- toolName: "datadog_metric_snapshot",
- toolArgs: { service: "canvas-api" },
- prompt:
- "Use the integrations hub datadog MCP to inspect canvas-api metrics.",
- finalText: "C3 integrations hub header-auth MCP complete.",
- successToken: "datadog_fixture_success",
- },
- {
- id: "c4",
- title: "c4: Integrations hub + OAuth client-id/secret MCP",
- integrationKey: `c4-notion-oauth-${RUN_TAG}`,
- displayName: `C4 Notion OAuth ${RUN_TAG}`,
- hubMode: "managed-oauth",
- fixtureUrl: `http://${FIXTURE_DOCKER_HOST}:19203/mcp`,
- managedConnector: {
- description: "Static client-id and client-secret OAuth MCP fixture.",
- oauthClientId: "notion-client",
- oauthClientSecret: "notion-secret",
- oauthConfig: {
- authorizationUrl: `http://${FIXTURE_DOCKER_HOST}:19203/authorize`,
- tokenUrl: `http://${FIXTURE_DOCKER_HOST}:19203/token`,
- scopes: ["read:mock"],
- pkce: true,
- clientAuthentication: "body",
- },
- },
- toolName: "notion_page_lookup",
- toolArgs: { title: "Roadmap" },
- prompt: "Use the integrations hub notion MCP to look up the Roadmap page.",
- finalText: "C4 integrations hub OAuth client-secret MCP complete.",
- successToken: "notion_fixture_success",
- },
- {
- id: "c5",
- title: "c5: Integrations hub + dynamic OAuth MCP",
- integrationKey: `c5-linear-dynamic-${RUN_TAG}`,
- displayName: `C5 Linear Dynamic ${RUN_TAG}`,
- hubMode: "managed-oauth",
- fixtureUrl: `http://${FIXTURE_DOCKER_HOST}:19204/mcp`,
- managedConnector: {
- description: "Dynamic OAuth client registration MCP fixture.",
- oauthConfig: {
- authorizationUrl: `http://${FIXTURE_DOCKER_HOST}:19204/authorize`,
- tokenUrl: `http://${FIXTURE_DOCKER_HOST}:19204/token`,
- registrationUrl: `http://${FIXTURE_DOCKER_HOST}:19204/register`,
- scopes: ["read:mock"],
- pkce: true,
- clientAuthentication: "none",
- },
- },
- toolName: "linear_issue_summary",
- toolArgs: { issue_key: "LIN-42" },
- prompt: "Use the integrations hub linear MCP to summarize issue LIN-42.",
- finalText: "C5 integrations hub dynamic OAuth MCP complete.",
- successToken: "linear_fixture_success",
- },
-];
-
-async function adminPost(pathname, body = undefined) {
- const response = await fetch(`${MOCK_LLM_URL}${pathname}`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: body === undefined ? undefined : JSON.stringify(body),
- });
- if (!response.ok) {
- throw new Error(
- `Mock LLM ${pathname} failed: ${response.status} ${await response.text()}`,
- );
- }
- return response.json().catch(() => ({}));
-}
-
-async function registerTrajectory(flow) {
- const hubToolName = `${flow.integrationKey}__${flow.toolName}`;
- await adminPost("/admin/reset");
- await adminPost("/admin/trajectory/register", {
- name: flow.id,
- turns: [
- { tool_call: { name: hubToolName, arguments: flow.toolArgs } },
- {
- text: `${flow.finalText} The MCP observation contains ${flow.successToken}.`,
- },
- ],
- });
- await adminPost("/admin/trajectory/activate", { name: flow.id });
-}
-
-async function setupPage() {
- const browser = await chromium.launch({
- headless: true,
- args: [
- "--disable-dev-shm-usage",
- "--disable-gpu",
- "--renderer-process-limit=1",
- "--single-process",
- "--no-zygote",
- ],
- });
- const context = await browser.newContext({
- viewport: { width: 960, height: 600 },
- deviceScaleFactor: 1,
- });
- await context.addInitScript(
- ({ apiKey, backendUrl, hubToken }) => {
- window.localStorage.setItem("analytics-consent", "false");
- window.localStorage.setItem("openhands-telemetry-consent", "denied");
- window.localStorage.setItem("openhands-telemetry-first-use", "true");
- window.localStorage.setItem("openhands-onboarded", "1");
- window.localStorage.setItem("integrations-hub-openhands-token", hubToken);
-
- const active = { backendId: "default-local", orgId: null };
- window.localStorage.setItem(
- "openhands-backends",
- JSON.stringify([
- {
- id: "default-local",
- name: "Local",
- host: backendUrl,
- apiKey,
- kind: "local",
- },
- ]),
- );
- window.localStorage.setItem(
- "openhands-active-backend",
- JSON.stringify(active),
- );
- window.sessionStorage.setItem(
- "openhands-active-backend",
- JSON.stringify(active),
- );
- },
- {
- apiKey: SESSION_API_KEY,
- backendUrl: BACKEND_URL,
- hubToken: HUB_TOKEN,
- },
- );
- const page = await context.newPage();
- await page.route("**/*", async (route) => {
- const request = route.request();
- const url = new URL(request.url());
- const backendOrigin = new URL(BACKEND_URL).origin;
- const frontendOrigin = new URL(FRONTEND_URL).origin;
- const hubOrigin = new URL(HUB_URL).origin;
- const isCanvasBackend =
- url.origin === backendOrigin ||
- (url.origin === frontendOrigin && url.pathname.startsWith("/api/"));
- const isHubBackend =
- url.origin === hubOrigin && url.pathname.startsWith("/api/");
- if (!isCanvasBackend && !isHubBackend) {
- await route.continue();
- return;
- }
- await route.continue({
- headers: {
- ...request.headers(),
- ...(isCanvasBackend ? { "X-Session-API-Key": SESSION_API_KEY } : {}),
- ...(isHubBackend ? { Authorization: `Bearer ${HUB_TOKEN}` } : {}),
- },
- });
- });
- return { browser, context, page };
-}
-
-async function waitForTestId(page, testId, timeout = 30_000) {
- await page.getByTestId(testId).waitFor({ state: "visible", timeout });
-}
-
-async function dismissBlockingModals(page) {
- try {
- const form = page.getByTestId("telemetry-consent-form");
- await form.waitFor({ state: "visible", timeout: 2_000 });
- await page.getByTestId("confirm-telemetry-preferences").click();
- await form.waitFor({ state: "hidden", timeout: 5_000 });
- } catch {}
- try {
- const form = page.getByTestId("user-capture-consent-form");
- await form.waitFor({ state: "visible", timeout: 2_000 });
- await form.getByRole("button", { name: "Confirm preferences" }).click();
- await form.waitFor({ state: "hidden", timeout: 5_000 });
- } catch {}
- try {
- const skip = page.getByTestId("onboarding-skip");
- await skip.waitFor({ state: "visible", timeout: 2_000 });
- await skip.click();
- await page.getByTestId("onboarding-modal").waitFor({
- state: "hidden",
- timeout: 5_000,
- });
- } catch {}
- try {
- const close = page.getByTestId("onboarding-hello-close");
- await close.waitFor({ state: "visible", timeout: 2_000 });
- await close.click();
- await page.getByTestId("onboarding-modal").waitFor({
- state: "hidden",
- timeout: 5_000,
- });
- } catch {}
-}
-
-async function gotoPage(page, url) {
- let lastError;
- for (let attempt = 1; attempt <= 3; attempt += 1) {
- try {
- await page.goto(url, { waitUntil: "domcontentloaded", timeout: 45_000 });
- return;
- } catch (error) {
- lastError = error;
- await page.waitForTimeout(1_000 * attempt).catch(() => {});
- }
- }
- throw lastError;
-}
-
-async function selectDropdownOption(page, comboboxLabel, optionText) {
- const combobox = page.getByRole("combobox", { name: comboboxLabel });
- await combobox.waitFor({ state: "visible", timeout: 10_000 });
- await combobox.click();
- try {
- await combobox.fill("");
- } catch {}
- const option = page.getByRole("option", { name: optionText });
- await option.waitFor({ state: "visible", timeout: 10_000 });
- await option.click();
-}
-
-async function setChatInput(page, text) {
- await page.evaluate((inputText) => {
- const el = document.querySelector('[data-testid="chat-input"]');
- if (!(el instanceof HTMLElement)) {
- throw new Error("chat-input not found");
- }
- el.focus();
- el.textContent = inputText;
- el.dispatchEvent(
- new InputEvent("input", {
- bubbles: true,
- data: inputText,
- inputType: "insertText",
- }),
- );
- }, text);
-}
-
-async function waitForBodyText(page, text, timeout = 60_000) {
- await page.locator("body").filter({ hasText: text }).waitFor({ timeout });
-}
-
-async function waitForOutputText(page, text, timeout = 90_000) {
- const started = Date.now();
- while (Date.now() - started < timeout) {
- const found = await page.evaluate((needle) => {
- const selectors = [
- '[data-testid="agent-message"]',
- '[data-testid="environment-message"]',
- '[data-testid="model-messages"]',
- '[data-testid="event-group"]',
- '[data-testid="error-message-banner"]',
- ];
- return selectors.some((selector) =>
- Array.from(document.querySelectorAll(selector)).some((node) =>
- node.textContent?.includes(needle),
- ),
- );
- }, text);
- if (found) return;
- await page.waitForTimeout(1_000);
- }
- throw new Error(`Timed out waiting for output text: ${text}`);
-}
-
-function frameDir(flowId) {
- return path.join(PR_DIR, "frames", flowId);
-}
-
-async function capture(page, flowId, label) {
- const dir = frameDir(flowId);
- fs.mkdirSync(dir, { recursive: true });
- const count = fs
- .readdirSync(dir)
- .filter((name) => name.endsWith(".png")).length;
- const file = path.join(
- dir,
- `${String(count + 1).padStart(3, "0")}-${label}.png`,
- );
- await page.screenshot({ path: file, fullPage: false, timeout: 90_000 });
- return file;
-}
-
-function makeGif(flowId) {
- const frames = fs
- .readdirSync(frameDir(flowId))
- .filter((name) => name.endsWith(".png"))
- .sort()
- .map((name) => path.join(frameDir(flowId), name));
- const out = path.join(PR_DIR, `${flowId}.gif`);
- const script = String.raw`
-from PIL import Image
-import sys
-out = sys.argv[1]
-paths = sys.argv[2:]
-imgs = []
-for path in paths:
- img = Image.open(path).convert("RGB")
- max_width = 960
- if img.width > max_width:
- ratio = max_width / img.width
- img = img.resize((max_width, int(img.height * ratio)), Image.Resampling.LANCZOS)
- imgs.append(img.convert("P", palette=Image.Palette.ADAPTIVE, colors=128))
-durations = [900] * len(imgs)
-if durations:
- durations[-1] = 1800
-imgs[0].save(out, save_all=True, append_images=imgs[1:], duration=durations, loop=0, optimize=True)
-`;
- const result = spawnSync("python", ["-c", script, out, ...frames], {
- cwd: ROOT,
- encoding: "utf8",
- });
- if (result.status !== 0) {
- throw new Error(`GIF creation failed for ${flowId}: ${result.stderr}`);
- }
- return out;
-}
-
-async function ensureLlmSettings() {
- const profileName = `mcp-gif-c-${RUN_TAG}`;
- const saveResponse = await fetch(
- `${BACKEND_URL}/api/profiles/${encodeURIComponent(profileName)}`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-Session-API-Key": SESSION_API_KEY,
- },
- body: JSON.stringify({
- llm: {
- model: MOCK_MODEL,
- api_key: MOCK_LLM_API_KEY,
- base_url: MOCK_LLM_URL,
- },
- include_secrets: true,
- }),
- },
- );
- if (!saveResponse.ok) {
- throw new Error(
- `POST /api/profiles failed: ${saveResponse.status} ${await saveResponse.text()}`,
- );
- }
-
- const activateResponse = await fetch(
- `${BACKEND_URL}/api/profiles/${encodeURIComponent(profileName)}/activate`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-Session-API-Key": SESSION_API_KEY,
- },
- },
- );
- if (!activateResponse.ok) {
- throw new Error(
- `POST /api/profiles/activate failed: ${activateResponse.status} ${await activateResponse.text()}`,
- );
- }
-
- const response = await fetch(`${BACKEND_URL}/api/settings`, {
- method: "PATCH",
- headers: {
- "Content-Type": "application/json",
- "X-Session-API-Key": SESSION_API_KEY,
- },
- body: JSON.stringify({
- agent_settings_diff: {
- agent_kind: "openhands",
- agent: "CodeActAgent",
- llm: {
- model: MOCK_MODEL,
- api_key: MOCK_LLM_API_KEY,
- base_url: MOCK_LLM_URL,
- },
- },
- }),
- });
- if (!response.ok) {
- throw new Error(
- `PATCH /api/settings failed: ${response.status} ${await response.text()}`,
- );
- }
-}
-
-async function cleanupStaleHubMcpServers() {
- const settingsResponse = await fetch(`${BACKEND_URL}/api/settings`, {
- headers: { "X-Session-API-Key": SESSION_API_KEY },
- });
- if (!settingsResponse.ok) {
- throw new Error(
- `GET /api/settings failed: ${settingsResponse.status} ${await settingsResponse.text()}`,
- );
- }
- const settings = await settingsResponse.json();
- const currentConfig = settings.agent_settings?.mcp_config ?? {};
- const staleNames = Object.keys(currentConfig).filter((name) =>
- /^c[1-5]_hub_\d+/.test(name),
- );
- if (staleNames.length === 0) {
- return;
- }
-
- const response = await fetch(`${BACKEND_URL}/api/settings`, {
- method: "PATCH",
- headers: {
- "Content-Type": "application/json",
- "X-Session-API-Key": SESSION_API_KEY,
- },
- body: JSON.stringify({
- agent_settings_diff: {
- mcp_config: Object.fromEntries(staleNames.map((name) => [name, null])),
- },
- }),
- });
- if (!response.ok) {
- throw new Error(
- `PATCH /api/settings mcp_config failed: ${response.status} ${await response.text()}`,
- );
- }
-}
-
-async function hubApi(pathname, options = {}) {
- const response = await fetch(`${HUB_API_URL}${pathname}`, {
- ...options,
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${HUB_TOKEN}`,
- ...(options.headers ?? {}),
- },
- });
- const text = await response.text();
- let payload;
- try {
- payload = text ? JSON.parse(text) : null;
- } catch {
- payload = text;
- }
- if (!response.ok) {
- throw new Error(
- `Hub ${pathname} failed: ${response.status} ${
- typeof payload === "string" ? payload : JSON.stringify(payload)
- }`,
- );
- }
- return payload;
-}
-
-async function ensureManagedConnector(flow) {
- if (flow.hubMode !== "managed-oauth") return;
- await hubApi("/api/managed-connectors", {
- method: "POST",
- body: JSON.stringify({
- slug: flow.integrationKey,
- name: flow.displayName,
- description: flow.managedConnector.description,
- categories: ["QA"],
- authModes: ["oauth2"],
- authStrategy: "oauth2",
- provider: "mcp",
- serverUrl: flow.fixtureUrl,
- oauthConfigured: true,
- oauthClientId: flow.managedConnector.oauthClientId,
- oauthClientSecret: flow.managedConnector.oauthClientSecret,
- oauthConfig: flow.managedConnector.oauthConfig,
- credentialLabel: `Connect ${flow.displayName}`,
- credentialPlaceholder: `Connect ${flow.displayName}`,
- credentialHelp: "Use the fixture OAuth server.",
- tools: [],
- enabled: true,
- }),
- }).catch(async (error) => {
- if (!String(error.message).includes("409")) throw error;
- });
-}
-
-async function getHubAgentKey() {
- const response = await hubApi("/api/user/agent-key", {
- method: "GET",
- });
- if (!response?.apiKey) {
- throw new Error(
- `Hub agent key response missing apiKey: ${JSON.stringify(response)}`,
- );
- }
- return response.apiKey;
-}
-
-async function addCustomHubIntegration(page, flow) {
- await gotoPage(page, `${HUB_URL}/integrations?showIntegrationWizard=1`);
- await waitForBodyText(page, "Integrations");
- await capture(page, flow.id, "hub-integrations");
-
- const customButton = page.getByRole("button", {
- name: /Use a custom MCP server URL instead/i,
- });
- await customButton.waitFor({ state: "visible", timeout: 20_000 });
- await customButton.click();
- await page.getByPlaceholder("my-mcp").waitFor({ state: "visible" });
- await capture(page, flow.id, "hub-custom-form");
-
- await page.getByPlaceholder("my-mcp").fill(flow.integrationKey);
- await page.getByPlaceholder("My MCP").fill(flow.displayName);
- await page.getByPlaceholder("https://example.com/mcp").fill(flow.fixtureUrl);
- if (flow.credential) {
- await page.getByText("Add", { exact: true }).click();
- await page.getByPlaceholder("OAuth or bearer token").waitFor({
- state: "visible",
- timeout: 10_000,
- });
- }
- if (flow.credential?.bearerToken) {
- await page
- .getByPlaceholder("OAuth or bearer token")
- .fill(flow.credential.bearerToken);
- }
- if (flow.credential?.headerSecret) {
- await page
- .getByPlaceholder("Secret used with a header")
- .fill(flow.credential.headerSecret);
- await page.getByPlaceholder("X-API-Key").fill(flow.credential.headerName);
- }
- await capture(page, flow.id, "hub-custom-filled");
-
- await page.getByRole("button", { name: "Discover tools" }).click();
- await waitForBodyText(page, flow.toolName, 60_000);
- await capture(page, flow.id, "hub-tools-discovered");
-
- await page
- .getByRole("button", { name: /Add integration|Create integration/i })
- .click();
- await waitForBodyText(page, flow.displayName, 60_000);
- await waitForBodyText(page, flow.toolName, 60_000);
- await capture(page, flow.id, "hub-integration-created");
-}
-
-async function addManagedOauthIntegration(page, flow) {
- await ensureManagedConnector(flow);
- await gotoPage(
- page,
- `${HUB_URL}/integrations?showIntegrationWizard=1&managedConnector=${flow.integrationKey}`,
- );
- await waitForBodyText(page, flow.displayName, 30_000);
- await capture(page, flow.id, "hub-managed-form");
-
- const connectButton = page.getByRole("button", { name: /^Connect$/ }).first();
- await connectButton.waitFor({ state: "visible", timeout: 20_000 });
- await connectButton.click();
- await page.waitForURL(/\/integrations/, { timeout: 60_000 });
- await waitForBodyText(page, "Connected", 60_000);
- await capture(page, flow.id, "hub-oauth-connected");
-
- await page.getByRole("button", { name: "Discover tools" }).click();
- await waitForBodyText(page, flow.toolName, 60_000);
- await capture(page, flow.id, "hub-tools-discovered");
-
- await page
- .getByRole("button", { name: /Add integration|Create integration/i })
- .click();
- await waitForBodyText(page, flow.displayName, 60_000);
- await waitForBodyText(page, flow.toolName, 60_000);
- await capture(page, flow.id, "hub-integration-created");
-}
-
-async function showAgentConnection(page, flow) {
- await gotoPage(page, `${HUB_URL}/agent-connection`);
- await waitForBodyText(page, "Agent Connection", 30_000);
- await capture(page, flow.id, "hub-agent-connection");
- const revealButton = page.getByRole("button", { name: /Reveal/i }).first();
- if (await revealButton.isVisible().catch(() => false)) {
- await revealButton.click();
- await page.waitForTimeout(500);
- await capture(page, flow.id, "hub-agent-key-revealed");
- }
-}
-
-async function installHubMcpInCanvas(page, flow, hubAgentKey) {
- const serverName = `${flow.id}_hub_${RUN_TAG}`;
- await gotoPage(page, `${FRONTEND_URL}/mcp`);
- await dismissBlockingModals(page);
- await waitForTestId(page, "mcp-page", 180_000);
- await capture(page, flow.id, "canvas-mcp-page");
-
- await page.getByTestId("mcp-add-custom-server").click({ noWaitAfter: true });
- await waitForTestId(page, "mcp-custom-editor");
- await capture(page, flow.id, "canvas-custom-modal");
-
- await page.getByTestId("server-type-dropdown").fill("SHTTP");
- await page.getByTestId("server-type-dropdown").press("Enter");
- await page.getByTestId("server-name-input").fill(serverName);
- await page
- .getByTestId("url-input")
- .fill(`${HUB_MCP_URL}?run=${RUN_TAG}-${flow.id}`);
- await selectDropdownOption(page, /Authentication/i, "Bearer token");
- await page.getByTestId("api-key-input").fill(hubAgentKey);
- await capture(page, flow.id, "canvas-hub-auth-filled");
-
- await page
- .getByTestId("mcp-custom-editor")
- .getByRole("button", { name: "Add Server" })
- .click({ noWaitAfter: true });
- try {
- await page.getByTestId("mcp-custom-editor").waitFor({
- state: "hidden",
- timeout: 60_000,
- });
- } catch (error) {
- await capture(page, flow.id, "canvas-install-still-open").catch(() => {});
- const modalText = await page
- .getByTestId("mcp-custom-editor")
- .innerText()
- .catch(() => "");
- throw new Error(
- `Hub MCP install modal did not close for ${flow.id}. Text:\n${modalText}`,
- { cause: error },
- );
- }
- await waitForTestId(page, "mcp-installed-list");
- await capture(page, flow.id, "canvas-hub-installed");
-}
-
-async function runConversation(page, flow) {
- await registerTrajectory(flow);
- await waitForTestId(page, "conversation-panel-new-thread-picker", 60_000);
- await page.getByTestId("conversation-panel-new-thread-picker").click();
- await waitForTestId(page, "launch-no-workspace", 30_000);
- await capture(page, flow.id, "new-chat-menu");
- const conversationResponsePromise = page.waitForResponse((response) => {
- return (
- response.url().startsWith(`${BACKEND_URL}/api/conversations`) &&
- response.request().method() === "POST" &&
- response.status() >= 200 &&
- response.status() < 300
- );
- });
- await page.getByTestId("launch-no-workspace").click({ noWaitAfter: true });
- const conversationResponse = await conversationResponsePromise;
- const conversation = await conversationResponse.json();
- const conversationShortId = String(conversation.id).slice(0, 5);
- await waitForBodyText(page, `Conversation ${conversationShortId}`, 60_000);
- await page.keyboard.press("Escape");
- const createdConversationCard = page
- .getByTestId("conversation-card")
- .filter({ hasText: `Conversation ${conversationShortId}` })
- .first();
- await createdConversationCard.waitFor({ state: "visible", timeout: 30_000 });
- await capture(page, flow.id, "conversation-card-created");
- await createdConversationCard.dispatchEvent("click");
- try {
- await page.waitForURL(/\/conversations\/.+/, { timeout: 10_000 });
- } catch {
- await gotoPage(page, `${FRONTEND_URL}/conversations/${conversation.id}`);
- }
- await waitForTestId(page, "chat-input", 180_000);
- await capture(page, flow.id, "conversation-ready");
- await setChatInput(page, flow.prompt);
- await capture(page, flow.id, "prompt");
- await page.getByTestId("submit-button").click({ noWaitAfter: true });
- await capture(page, flow.id, "conversation-started");
- await waitForOutputText(page, flow.successToken, 90_000);
- await capture(page, flow.id, "tool-observation");
- await waitForOutputText(page, flow.finalText, 90_000);
- await capture(page, flow.id, "final-reply");
-}
-
-async function main() {
- fs.mkdirSync(PR_DIR, { recursive: true });
- const selectedIds = new Set(
- (process.env.FLOW_IDS ?? "")
- .split(",")
- .map((id) => id.trim())
- .filter(Boolean),
- );
- const selectedFlows =
- selectedIds.size === 0
- ? flows
- : flows.filter((flow) => selectedIds.has(flow.id));
- if (selectedFlows.length === 0) {
- throw new Error(`No matching flows for FLOW_IDS=${process.env.FLOW_IDS}`);
- }
-
- const { browser, page } = await setupPage();
- try {
- await ensureLlmSettings();
- await cleanupStaleHubMcpServers();
- const hubAgentKey = await getHubAgentKey();
- for (const flow of selectedFlows) {
- fs.rmSync(frameDir(flow.id), { recursive: true, force: true });
- console.log(`Capturing ${flow.title}`);
- if (flow.hubMode === "custom") {
- await addCustomHubIntegration(page, flow);
- } else {
- await addManagedOauthIntegration(page, flow);
- }
- await showAgentConnection(page, flow);
- await installHubMcpInCanvas(page, flow, hubAgentKey);
- await runConversation(page, flow);
- const gif = makeGif(flow.id);
- console.log(`Wrote ${path.relative(ROOT, gif)}`);
- }
- } finally {
- await browser.close();
- }
-}
-
-main().catch((error) => {
- console.error(error);
- process.exit(1);
-});
diff --git a/.pr/mcp-fixtures/mock_mcp_server.py b/.pr/mcp-fixtures/mock_mcp_server.py
deleted file mode 100644
index 3a37e9f841..0000000000
--- a/.pr/mcp-fixtures/mock_mcp_server.py
+++ /dev/null
@@ -1,232 +0,0 @@
-#!/usr/bin/env python3
-"""FastMCP fixture servers for Agent Canvas authenticated-MCP GIF capture."""
-
-from __future__ import annotations
-
-import argparse
-from typing import Any
-from urllib.parse import urlparse
-
-from fastmcp import FastMCP
-from fastmcp.server.auth import DebugTokenVerifier
-from fastmcp.server.auth.auth import ClientRegistrationOptions
-from fastmcp.server.auth.providers.in_memory import InMemoryOAuthProvider
-from fastmcp.server.dependencies import (
- CurrentAccessToken,
- CurrentHeaders,
-)
-from mcp.server.auth.provider import AccessToken
-from mcp.shared.auth import (
- InvalidRedirectUriError,
- OAuthClientInformationFull,
-)
-from pydantic import AnyUrl
-
-
-BEARER_TOKEN = "elevenlabs-test-token"
-DATADOG_API_KEY = "datadog-api-key"
-DATADOG_APP_KEY = "datadog-app-key"
-STATIC_CLIENT_ID = "notion-client"
-STATIC_CLIENT_SECRET = "notion-secret"
-OAUTH_SCOPES = "read:mock write:mock"
-
-
-class LocalhostRedirectClient(OAuthClientInformationFull):
- """Static OAuth client that accepts FastMCP's generated localhost callback."""
-
- def validate_redirect_uri(self, redirect_uri: AnyUrl | None) -> AnyUrl:
- if redirect_uri is None:
- raise InvalidRedirectUriError("redirect_uri is required for this fixture")
-
- parsed = urlparse(str(redirect_uri))
- if (
- parsed.scheme == "http"
- and parsed.hostname in {
- "127.0.0.1",
- "localhost",
- "::1",
- }
- and (
- parsed.path == "/callback"
- or parsed.path.startswith("/api/oauth/")
- )
- ):
- return redirect_uri
-
- raise InvalidRedirectUriError(
- f"Redirect URI '{redirect_uri}' is not an Agent Canvas callback"
- )
-
-
-class StaticClientOAuthProvider(InMemoryOAuthProvider):
- async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:
- if client_id == STATIC_CLIENT_ID:
- return LocalhostRedirectClient(
- client_id=STATIC_CLIENT_ID,
- client_secret=STATIC_CLIENT_SECRET,
- client_secret_expires_at=0,
- token_endpoint_auth_method="client_secret_post",
- redirect_uris=[AnyUrl("http://127.0.0.1/callback")],
- grant_types=["authorization_code", "refresh_token"],
- response_types=["code"],
- scope=OAUTH_SCOPES,
- client_name="Mock Notion Static OAuth",
- )
- return await super().get_client(client_id)
-
- async def authorize(
- self,
- client: OAuthClientInformationFull,
- params: Any,
- ) -> str:
- if client.client_id == STATIC_CLIENT_ID and client.client_id not in self.clients:
- self.clients[client.client_id] = client
- return await super().authorize(client, params)
-
-
-def build_weather_server() -> FastMCP:
- mcp = FastMCP("Mock Weather MCP")
-
- @mcp.tool
- def weather_forecast(city: str) -> str:
- """Return a deterministic mock forecast."""
-
- return f"weather_fixture_success city={city} forecast=sunny-72F"
-
- return mcp
-
-
-def build_elevenlabs_server() -> FastMCP:
- auth = DebugTokenVerifier(validate=lambda token: token == BEARER_TOKEN)
- mcp = FastMCP("Mock ElevenLabs MCP", auth=auth)
-
- @mcp.tool
- def elevenlabs_voice_note(
- text: str,
- token: AccessToken = CurrentAccessToken(),
- ) -> str:
- """Return a deterministic mock voice note id."""
-
- return (
- "elevenlabs_fixture_success "
- f"client={token.client_id} voice_id=mock-voice text={text}"
- )
-
- return mcp
-
-
-def build_datadog_server() -> FastMCP:
- mcp = FastMCP("Mock Datadog MCP")
-
- @mcp.tool
- def datadog_metric_snapshot(
- service: str,
- headers: dict[str, str] = CurrentHeaders(),
- ) -> str:
- """Validate Datadog-style headers and return a metric sample."""
-
- normalized = {key.lower(): value for key, value in headers.items()}
- if normalized.get("dd-api-key") != DATADOG_API_KEY:
- return "datadog_fixture_error missing-or-invalid-dd-api-key"
- if (
- "dd-application-key" in normalized
- and normalized.get("dd-application-key") != DATADOG_APP_KEY
- ):
- return "datadog_fixture_error missing-or-invalid-dd-application-key"
-
- return f"datadog_fixture_success service={service} cpu=0.37 errors=0"
-
- return mcp
-
-
-def build_static_oauth_server(base_url: str) -> FastMCP:
- # The local install-time OAuth helper used for GIF capture does not
- # consistently forward the requested scope parameter. Keep the fixture
- # focused on proving OAuth token acquisition and MCP tool use rather than
- # failing before the tool call on a missing demo scope.
- auth = StaticClientOAuthProvider(base_url=base_url)
- mcp = FastMCP("Mock Notion Static OAuth MCP", auth=auth)
-
- @mcp.tool
- def notion_page_lookup(
- title: str,
- token: AccessToken = CurrentAccessToken(),
- ) -> str:
- """Return a deterministic mock Notion page lookup."""
-
- scopes = ",".join(token.scopes)
- return (
- "notion_fixture_success "
- f"client={token.client_id} scopes={scopes} title={title}"
- )
-
- return mcp
-
-
-def build_dynamic_oauth_server(base_url: str) -> FastMCP:
- auth = InMemoryOAuthProvider(
- base_url=base_url,
- client_registration_options=ClientRegistrationOptions(
- enabled=True,
- valid_scopes=["read:mock", "write:mock"],
- default_scopes=["read:mock"],
- ),
- )
- mcp = FastMCP("Mock Linear Dynamic OAuth MCP", auth=auth)
-
- @mcp.tool
- def linear_issue_summary(
- issue_key: str,
- token: AccessToken = CurrentAccessToken(),
- ) -> str:
- """Return a deterministic mock Linear issue summary."""
-
- scopes = ",".join(token.scopes)
- return (
- "linear_fixture_success "
- f"client={token.client_id} scopes={scopes} issue={issue_key}"
- )
-
- return mcp
-
-
-def build_server(kind: str, base_url: str) -> FastMCP:
- if kind == "weather":
- return build_weather_server()
- if kind == "elevenlabs":
- return build_elevenlabs_server()
- if kind == "datadog":
- return build_datadog_server()
- if kind == "notion":
- return build_static_oauth_server(base_url)
- if kind == "linear":
- return build_dynamic_oauth_server(base_url)
- raise ValueError(f"Unsupported fixture kind: {kind}")
-
-
-def main() -> None:
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "kind",
- choices=["weather", "elevenlabs", "datadog", "notion", "linear"],
- )
- parser.add_argument("--host", default="127.0.0.1")
- parser.add_argument("--base-url")
- parser.add_argument("--port", type=int, required=True)
- parser.add_argument("--path", default="/mcp")
- args = parser.parse_args()
-
- base_url = args.base_url or f"http://{args.host}:{args.port}"
- server = build_server(args.kind, base_url)
- server.run(
- transport="http",
- host=args.host,
- port=args.port,
- path=args.path,
- stateless_http=True,
- show_banner=False,
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/.pr/mcp-fixtures/public_proxy.py b/.pr/mcp-fixtures/public_proxy.py
deleted file mode 100644
index a155a7ff54..0000000000
--- a/.pr/mcp-fixtures/public_proxy.py
+++ /dev/null
@@ -1,215 +0,0 @@
-#!/usr/bin/env python3
-"""Path-routing proxy for public MCP fixture capture.
-
-One ngrok tunnel points at this proxy. Paths are routed by prefix:
-
-- /weather/* -> weather fixture
-- /elevenlabs/* -> bearer-token fixture
-- /datadog/* -> header-auth fixture
-- /notion/* -> static OAuth fixture
-- /linear/* -> dynamic OAuth fixture
-- /mock-llm/* -> scripted mock LLM
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import os
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from urllib.parse import parse_qs, urlsplit, urlunsplit
-
-import requests
-
-
-HOP_BY_HOP_HEADERS = {
- "connection",
- "keep-alive",
- "proxy-authenticate",
- "proxy-authorization",
- "te",
- "trailer",
- "transfer-encoding",
- "upgrade",
-}
-
-
-def _target_map() -> dict[str, str]:
- return {
- "weather": os.environ.get("MCP_WEATHER_TARGET", "http://127.0.0.1:19200"),
- "elevenlabs": os.environ.get(
- "MCP_ELEVENLABS_TARGET", "http://127.0.0.1:19201"
- ),
- "datadog": os.environ.get("MCP_DATADOG_TARGET", "http://127.0.0.1:19202"),
- "notion": os.environ.get("MCP_NOTION_TARGET", "http://127.0.0.1:19203"),
- "linear": os.environ.get("MCP_LINEAR_TARGET", "http://127.0.0.1:19204"),
- "mock-llm": os.environ.get("MOCK_LLM_TARGET", "http://127.0.0.1:19999"),
- }
-
-
-class ProxyHandler(BaseHTTPRequestHandler):
- protocol_version = "HTTP/1.1"
-
- def do_GET(self) -> None:
- self._proxy()
-
- def do_POST(self) -> None:
- self._proxy()
-
- def do_PUT(self) -> None:
- self._proxy()
-
- def do_PATCH(self) -> None:
- self._proxy()
-
- def do_DELETE(self) -> None:
- self._proxy()
-
- def do_OPTIONS(self) -> None:
- self._proxy()
-
- def log_message(self, fmt: str, *args: object) -> None:
- print(f"{self.client_address[0]} - {fmt % args}", flush=True)
-
- def _proxy(self) -> None:
- split = urlsplit(self.path)
- parts = [part for part in split.path.split("/") if part]
- if not parts:
- self._send_text(200, "fixture proxy ok\n")
- return
-
- prefix = parts[0]
- targets = _target_map()
- if (
- len(parts) >= 4
- and prefix == ".well-known"
- and parts[1] == "oauth-protected-resource"
- and parts[2] in targets
- ):
- self._send_oauth_resource_metadata(parts[2])
- return
-
- upstream_path: str | None = None
- if (
- len(parts) >= 3
- and prefix == ".well-known"
- and parts[1] in {"oauth-authorization-server", "openid-configuration"}
- and parts[2] in targets
- ):
- prefix = parts[2]
- upstream_path = "/" + "/".join(parts[:2])
-
- if prefix in {"authorize", "token", "register"}:
- oauth_prefix = self._oauth_prefix_from_resource(split.query)
- if oauth_prefix in targets:
- prefix = oauth_prefix
- upstream_path = split.path
-
- target_base = targets.get(prefix)
- if not target_base:
- self._send_text(404, f"unknown fixture prefix: {prefix}\n")
- return
-
- if upstream_path is None:
- upstream_path = "/" + "/".join(parts[1:])
- if upstream_path == "/":
- upstream_path = "/"
- target = urlunsplit(
- (
- urlsplit(target_base).scheme,
- urlsplit(target_base).netloc,
- upstream_path,
- split.query,
- "",
- )
- )
-
- body = None
- content_length = self.headers.get("Content-Length")
- if content_length:
- body = self.rfile.read(int(content_length))
-
- request_headers = {
- key: value
- for key, value in self.headers.items()
- if key.lower() not in HOP_BY_HOP_HEADERS and key.lower() != "host"
- }
-
- try:
- with requests.request(
- self.command,
- target,
- headers=request_headers,
- data=body,
- allow_redirects=False,
- stream=True,
- timeout=(10, 300),
- ) as response:
- self.send_response(response.status_code)
- for key, value in response.headers.items():
- if key.lower() in HOP_BY_HOP_HEADERS:
- continue
- self.send_header(key, value)
- self.end_headers()
- for chunk in response.iter_content(chunk_size=64 * 1024):
- if chunk:
- self.wfile.write(chunk)
- except requests.RequestException as exc:
- self._send_text(502, f"upstream request failed: {exc}\n")
-
- def _send_text(self, status: int, text: str) -> None:
- data = text.encode("utf-8")
- self.send_response(status)
- self.send_header("Content-Type", "text/plain; charset=utf-8")
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
-
- def _public_origin(self) -> str:
- host = self.headers.get("X-Forwarded-Host") or self.headers.get("Host")
- proto = self.headers.get("X-Forwarded-Proto")
- if not proto:
- proto = "https" if host and "ngrok-free.app" in host else "http"
- return f"{proto}://{host}"
-
- def _send_json(self, status: int, value: object) -> None:
- data = json.dumps(value).encode("utf-8")
- self.send_response(status)
- self.send_header("Content-Type", "application/json")
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
-
- def _send_oauth_resource_metadata(self, kind: str) -> None:
- origin = self._public_origin()
- self._send_json(
- 200,
- {
- "resource": f"{origin}/{kind}/mcp",
- "authorization_servers": [f"{origin}/{kind}"],
- },
- )
-
- @staticmethod
- def _oauth_prefix_from_resource(query: str) -> str | None:
- resources = parse_qs(query).get("resource", [])
- for resource in resources:
- parts = [part for part in urlsplit(resource).path.split("/") if part]
- if len(parts) >= 2 and parts[-1] == "mcp":
- return parts[-2]
- return None
-
-
-def main() -> None:
- parser = argparse.ArgumentParser()
- parser.add_argument("--host", default="127.0.0.1")
- parser.add_argument("--port", type=int, default=19300)
- args = parser.parse_args()
-
- server = ThreadingHTTPServer((args.host, args.port), ProxyHandler)
- print(f"fixture proxy listening on http://{args.host}:{args.port}", flush=True)
- server.serve_forever()
-
-
-if __name__ == "__main__":
- main()
diff --git a/.pr/screenshots/command-output-collapsed.png b/.pr/screenshots/command-output-collapsed.png
deleted file mode 100644
index b92c3fb8ec..0000000000
Binary files a/.pr/screenshots/command-output-collapsed.png and /dev/null differ
diff --git a/.pr/screenshots/command-output-expanded.png b/.pr/screenshots/command-output-expanded.png
deleted file mode 100644
index 2d89328b28..0000000000
Binary files a/.pr/screenshots/command-output-expanded.png and /dev/null differ
diff --git a/__tests__/components/features/sidebar/sidebar-email-verification.test.tsx b/__tests__/components/features/sidebar/sidebar-email-verification.test.tsx
new file mode 100644
index 0000000000..59242d4026
--- /dev/null
+++ b/__tests__/components/features/sidebar/sidebar-email-verification.test.tsx
@@ -0,0 +1,161 @@
+import { render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { Sidebar } from "#/components/features/sidebar/sidebar";
+import {
+ NavigationProvider,
+ type NavigationContextValue,
+} from "#/context/navigation-context";
+import { SidebarMobileNavProvider } from "#/components/features/sidebar/sidebar-mobile-nav-context";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import {
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { useSidebarStore } from "#/stores/sidebar-store";
+import { useSettings } from "#/hooks/query/use-settings";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import OptionService from "#/api/option-service/option-service.api";
+import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
+import type { Settings } from "#/types/settings";
+import type { WebClientConfig } from "#/api/option-service/option.types";
+import type { Backend } from "#/api/backend-registry/types";
+
+// Isolate the sidebar down to its top-level navigation. These are peripheral to
+// email-verification gating: the conversation list and backend selector fetch
+// their own data, the command menu is a search launcher, and the logo is
+// decorative. Mocking the *components* (not the settings/backend hooks under
+// test) keeps the render deterministic.
+vi.mock("#/components/features/sidebar/sidebar-conversation-list", () => ({
+ SidebarConversationList: () => (
+ <div data-testid="sidebar-conversation-list" />
+ ),
+}));
+vi.mock("#/components/features/backends/backend-selector", () => ({
+ BackendSelector: () => <div data-testid="backend-selector" />,
+}));
+vi.mock("#/components/features/command-menu/command-menu-trigger", () => ({
+ CommandMenuTrigger: () => <div data-testid="command-menu-trigger" />,
+}));
+vi.mock("#/components/shared/buttons/openhands-logo-button", () => ({
+ OpenHandsLogoButton: () => <div data-testid="logo-button" />,
+}));
+
+// The backend-health hook polls each backend over the network to drive a status
+// dot shown only in the collapsed rail β€” unrelated to the behavior under test.
+// Stub it so no probe fires (service-level mocking isn't practical here: the
+// probe instantiates SDK clients inline).
+vi.mock("#/hooks/query/use-backends-health", () => ({
+ useBackendsHealth: () => ({}),
+}));
+
+const TEST_BACKEND: Backend = {
+ id: "test-local",
+ name: "Local",
+ host: "http://localhost:3000",
+ apiKey: "test-key",
+ kind: "local",
+};
+
+function buildSettings(overrides: Partial<Settings> = {}): Settings {
+ return {
+ ...MOCK_DEFAULT_USER_SETTINGS,
+ ...overrides,
+ agent_settings:
+ overrides.agent_settings ?? MOCK_DEFAULT_USER_SETTINGS.agent_settings,
+ };
+}
+
+function buildConfig(): WebClientConfig {
+ return {
+ posthog_client_key: null,
+ feature_flags: { hide_llm_settings: false, hide_users_page: true },
+ providers_configured: [],
+ maintenance_start_time: null,
+ recaptcha_site_key: null,
+ faulty_models: [],
+ error_message: null,
+ updated_at: "2026-01-01T00:00:00.000Z",
+ };
+}
+
+// Renders the sidebar next to a probe that flips a marker once the settings
+// query settles with an unverified email. Waiting on the marker means the
+// assertions observe the resolved `email_verified: false` state β€” the exact
+// condition that used to disable the links β€” rather than the loading frame.
+function ProbedSidebar() {
+ const settings = useSettings();
+ return (
+ <>
+ <Sidebar />
+ {settings.isFetched && settings.data?.email_verified === false ? (
+ <div data-testid="settings-loaded" />
+ ) : null}
+ </>
+ );
+}
+
+function renderSidebar() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const navigation: NavigationContextValue = {
+ currentPath: "/",
+ conversationId: null,
+ isNavigating: false,
+ navigate: vi.fn(),
+ };
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <NavigationProvider value={navigation}>
+ <SidebarMobileNavProvider>
+ <ProbedSidebar />
+ </SidebarMobileNavProvider>
+ </NavigationProvider>
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+}
+
+describe("Sidebar email verification", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ useSidebarStore.setState({ collapsed: false });
+ // A resolved local backend is required; otherwise `useSettings`
+ // short-circuits to defaults and never calls the mocked service.
+ setRegisteredBackends([TEST_BACKEND]);
+ setActiveSelection({ backendId: TEST_BACKEND.id, orgId: null });
+ vi.spyOn(OptionService, "getConfig").mockResolvedValue(buildConfig());
+ });
+
+ afterEach(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ });
+
+ it("keeps primary navigation enabled when the user's email is unverified", async () => {
+ // Arrange: the OAuth-changed-email state β€” the backend stays permissive but
+ // reports the address as unverified.
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({ email_verified: false }),
+ );
+
+ // Act
+ renderSidebar();
+ await screen.findByTestId("settings-loaded");
+
+ // Assert: New Chat, Customize/Extensions, and Automations stay actionable
+ // (a disabled link would carry aria-disabled="true").
+ for (const testId of [
+ "sidebar-conversations-link",
+ "sidebar-skills-link",
+ "sidebar-automations-link",
+ ]) {
+ expect(screen.getByTestId(testId)).not.toHaveAttribute("aria-disabled");
+ }
+ });
+});
diff --git a/src/components/features/sidebar/sidebar-rail-body.tsx b/src/components/features/sidebar/sidebar-rail-body.tsx
index 36e2936ef4..ef4993717c 100644
--- a/src/components/features/sidebar/sidebar-rail-body.tsx
+++ b/src/components/features/sidebar/sidebar-rail-body.tsx
@@ -39,7 +39,6 @@ export interface SidebarRailBodyProps {
showCollapseToggle: boolean;
showMobileCloseButton?: boolean;
onCloseMobile?: () => void;
- linkDisabled: boolean;
collapseToggleLabel: string;
onCollapse: () => void;
onExpand: () => void;
@@ -62,7 +61,6 @@ export function SidebarRailBody({
showCollapseToggle,
showMobileCloseButton = false,
onCloseMobile,
- linkDisabled,
collapseToggleLabel,
onCollapse,
onExpand,
@@ -163,7 +161,6 @@ export function SidebarRailBody({
end
label={t(I18nKey.SIDEBAR$NEW_CHAT)}
testId="sidebar-conversations-link"
- disabled={linkDisabled}
collapsed={collapsed}
icon={<Plus width={ICON_SIZE} height={ICON_SIZE} />}
/>
@@ -171,7 +168,6 @@ export function SidebarRailBody({
to="/customize"
label={t(I18nKey.NAV$CUSTOMIZE)}
testId="sidebar-skills-link"
- disabled={linkDisabled}
collapsed={collapsed}
forceActive={isExtensionsActive}
icon={
@@ -206,7 +202,6 @@ export function SidebarRailBody({
to="/automations"
label={t(I18nKey.SIDEBAR$AUTOMATIONS)}
testId="sidebar-automations-link"
- disabled={linkDisabled}
collapsed={collapsed}
icon={<AutomationsIcon width={ICON_SIZE} height={ICON_SIZE} />}
/>
diff --git a/src/components/features/sidebar/sidebar.tsx b/src/components/features/sidebar/sidebar.tsx
index fa053b5f2e..102357f474 100644
--- a/src/components/features/sidebar/sidebar.tsx
+++ b/src/components/features/sidebar/sidebar.tsx
@@ -136,8 +136,6 @@ export function Sidebar() {
t,
]);
- const linkDisabled = settings?.email_verified === false;
-
const collapseToggleLabel = t(
collapsed ? I18nKey.SIDEBAR$EXPAND : I18nKey.SIDEBAR$COLLAPSE,
);
@@ -186,7 +184,6 @@ export function Sidebar() {
currentPath === "/mcp";
const railBodyProps = {
- linkDisabled,
collapseToggleLabel,
onCollapse: handleCollapse,
onExpand: () => setCollapsed(false),