Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

74.7 KB
Raw Blame
import { createServer, type Server } from "node:http";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";

import type { AppConfig } from "./config.ts";
import {
  CURATED_SLUGS,
  applyManagedBrokerMessage,
  authorizeService,
  connectedServiceSlugs,
  serviceSlugsReadSettled,
  verifiedConnectedServiceSlugs,
  connectedServices,
  connectedServicesInventory,
  connectionMode,
  connectionStatus,
  listConnectorTools,
  listToolkits,
  toolkitCategories,
  mcpIntegration,
  normalizeAccountAlias,
  prepareProjectSession,
  removeAccount,
  removeService,
  relayMcp,
  setManagedBrokerAccess,
  trustedSessionMcpUrl,
  validateConnectorGrants,
} from "./composio.ts";
import { forgetProjectAuthConfigs } from "./composio-project.ts";
import {
  CONNECTOR_ALLOWED_TOOLS_ENV,
  CONNECTOR_SERVICE_SLUGS_ENV,
  parseConnectorServiceSlugsEnv,
} from "./connector-advertisement.ts";
import type { ConnectorToolGrant } from "../shared/wire.ts";
import { CURATED_CONNECTOR_SLUGS } from "../shared/connector-curated.ts";
import { EMAIL_READ_TOOL_NAMES, EMAIL_SLUG } from "../shared/email.ts";

let api: Server;
it("lists exactly the curated apps product analytics may name, in the same order", () => {
  expect(CURATED_SLUGS).toEqual([...CURATED_CONNECTOR_SLUGS]);
});

it("only sends Session MCP credentials over HTTPS or loopback HTTP", () => {
  const old = process.env.OMB_COMPOSIO_API;
  try {
    process.env.OMB_COMPOSIO_API = "http://remote.example.test/api";
    expect(trustedSessionMcpUrl("http://remote.example.test/mcp")).toBe(false);
    process.env.OMB_COMPOSIO_API = "ftp://remote.example.test/api";
    expect(trustedSessionMcpUrl("ftp://remote.example.test/mcp")).toBe(false);
    process.env.OMB_COMPOSIO_API = "http://127.0.0.1:9876/api";
    expect(trustedSessionMcpUrl("http://127.0.0.1:9876/mcp")).toBe(true);
    expect(trustedSessionMcpUrl("https://app.composio.dev/mcp")).toBe(true);
  } finally {
    if (old === undefined) delete process.env.OMB_COMPOSIO_API;
    else process.env.OMB_COMPOSIO_API = old;
  }
});
let origin = "";
let base = "";
const calls: Array<{
  method: string;
  path: string;
  query: string;
  body: any;
  apiKey: string;
  transportSessionId: string;
}> = [];
let malformedConnectedAccounts = false;
let connectedAccountsUnavailable = false;
let emptyConnectedAccounts = false;
let connectedAccountsOverride: Array<{ id: string; alias?: string; status?: string; toolkit: { slug: string } }> | null = null;
// The grant editor's tools/list fixture: null keeps the legacy one-frame
// {source:"broker"} answer the relayMcp tests assert on.
let brokerMcpTools: Array<{ name: string; description?: string; annotations?: Record<string, unknown> }> | null = null;
let brokerToolsListFail = false;
// What /broker/v1/connectors/connected serves; null falls back to github
// only, the state the existing validation tests were written against.
let brokerConnectedServicesBody: { complete?: boolean; services: Record<string, { connected: boolean; status: string }> } | null = null;
let brokerConnectedServicesFail = false;
// What /broker/v1/catalog serves; null falls back to github only.
let brokerCatalogBody: { items: Array<{ slug: string; name: string }> } | null = null;
// The project's own auth configs, and those the stub Session was created with: a Session knows only the configs named at creation.
let customAuthConfigs: Array<Record<string, unknown>> = [];
let sessionAuthConfigs: Record<string, string> = {};
// The cap the stub Session echoes: 10 for one made now, 5 for one made before the cap was raised.
let sessionAccountCap = 10;

beforeAll(async () => {
  api = createServer(async (req, res) => {
    const url = new URL(req.url ?? "/", "http://stub");
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const body = raw ? JSON.parse(raw) : null;
    calls.push({
      method: req.method ?? "GET",
      path: url.pathname,
      query: url.search,
      body,
      apiKey: String(req.headers["x-api-key"] ?? ""),
      transportSessionId: String(req.headers["mcp-session-id"] ?? ""),
    });

    if (url.pathname.startsWith("/broker/")) {
      // c/d/e/f/8/9 back the cache-identity tests; b stays invalid so a token
      // switch can be made to fail on purpose.
      if (!/^[acdef89]{64}$/.test(String(req.headers.authorization ?? "").replace(/^Bearer /, ""))) {
        res.writeHead(401, { "content-type": "application/json" });
        return res.end(JSON.stringify({ error: "invalid broker token" }));
      }
      if (req.method === "GET" && url.pathname === "/broker/v1/connectors") {
        const services = Object.fromEntries(
          (url.searchParams.get("services") ?? "").split(",").filter(Boolean).map((slug) => [
            slug,
            { connected: slug === "github", status: slug === "github" ? "ACTIVE" : "not_connected" },
          ]),
        );
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({ services }));
      }
      if (req.method === "GET" && url.pathname === "/broker/v1/connectors/connected") {
        if (brokerConnectedServicesFail) {
          res.writeHead(503, { "content-type": "application/json" });
          return res.end(JSON.stringify({ error: "unavailable" }));
        }
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify(
          brokerConnectedServicesBody ?? { services: { github: { connected: true, status: "ACTIVE" } } },
        ));
      }
      if (req.method === "POST" && url.pathname.endsWith("/authorize")) {
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({ url: "https://connect.composio.dev/managed" }));
      }
      if (req.method === "DELETE" && url.pathname.startsWith("/broker/v1/connectors/")) {
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({ removed: 1 }));
      }
      if (req.method === "GET" && url.pathname === "/broker/v1/catalog") {
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify(brokerCatalogBody ?? { items: [{ slug: "github", name: "GitHub" }] }));
      }
      if (req.method === "POST" && url.pathname === "/broker/v1/mcp") {
        if (brokerMcpTools !== null && body?.method === "initialize") {
          res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "mcp_grants" });
          return res.end(JSON.stringify({
            jsonrpc: "2.0",
            id: body.id,
            result: {
              protocolVersion: "2025-03-26",
              capabilities: {},
              serverInfo: { name: "composio-stub", version: "1" },
            },
          }));
        }
        if (brokerMcpTools !== null && body?.method === "tools/list") {
          if (brokerToolsListFail) {
            res.writeHead(500, { "content-type": "application/json" });
            return res.end(JSON.stringify({ error: { message: "tools list unavailable" } }));
          }
          res.writeHead(200, { "content-type": "application/json" });
          return res.end(JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { tools: brokerMcpTools } }));
        }
        res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "mcp_broker" });
        return res.end(JSON.stringify({ source: "broker" }));
      }
      res.writeHead(404, { "content-type": "application/json" });
      return res.end(JSON.stringify({ error: "unknown broker route" }));
    }

    const apiKey = String(req.headers["x-api-key"] ?? "");
    if (!["ak_test", "ak_catalog_a", "ak_catalog_b", "ak_catalog_pages", "ak_catalog_partial", "ak_catalog_stuck",
        "ak_catalog_page_stuck", "ak_catalog_exhausted", "ak_catalog_stalled_total", "ak_catalog_end_short",
        "ak_catalog_http_no_total"].includes(apiKey)) {
      res.writeHead(401, { "content-type": "application/json" });
      return res.end(JSON.stringify({ error: { message: "invalid project key" } }));
    }

    if (req.method === "POST" && url.pathname === "/api/v3.1/tool_router/session") {
      sessionAuthConfigs = body.auth_configs ?? {};
      res.writeHead(201, { "content-type": "application/json" });
      return res.end(JSON.stringify({
        session_id: "trs_test",
        mcp: { type: "http", url: "https://app.composio.dev/tool_router/v3/trs_test/mcp" },
        config: { user_id: body.user_id, multi_account: body.multi_account, auth_configs: sessionAuthConfigs },
      }));
    }
    if (
      req.method === "GET" && url.pathname === "/api/v3/toolkits"
      && (
        apiKey === "ak_catalog_pages"
        || apiKey === "ak_catalog_partial"
        || apiKey === "ak_catalog_stuck"
        || apiKey === "ak_catalog_page_stuck"
        || apiKey === "ak_catalog_exhausted"
        || apiKey === "ak_catalog_stalled_total"
        || apiKey === "ak_catalog_end_short"
        || apiKey === "ak_catalog_http_no_total"
      )
    ) {
      if (apiKey === "ak_catalog_stuck") {
        // A broker deployed before cursor support ignores the cursor and replays page one.
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({ items: [{ slug: "gmail", name: "Gmail" }], next_cursor: "catalog-page-2" }));
      }
      if (apiKey === "ak_catalog_page_stuck") {
        // Replays page one while minting a fresh cursor every time, so only current_page exposes the loop.
        const pageNumber = Number((url.searchParams.get("cursor") ?? "catalog-page-1").split("-").pop());
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({
          items: [{ slug: "gmail", name: "Gmail" }],
          next_cursor: "catalog-page-" + (pageNumber + 1),
          current_page: 1,
          total_pages: 4,
        }));
      }
      if (apiKey === "ak_catalog_exhausted") {
        // The last page still offers a cursor; total_pages must end the walk.
        res.writeHead(200, { "content-type": "application/json" });
        if (url.searchParams.get("cursor") === "catalog-page-2") {
          return res.end(JSON.stringify({
            items: [{ slug: "deepgram", name: "Deepgram" }],
            next_cursor: "catalog-page-3",
            current_page: 2,
            total_pages: 2,
          }));
        }
        return res.end(JSON.stringify({
          items: [{ slug: "gmail", name: "Gmail" }],
          next_cursor: "catalog-page-2",
          current_page: 1,
          total_pages: 2,
        }));
      }
      if (apiKey === "ak_catalog_stalled_total") {
        // Upstream reports the full count but stops offering cursors after the first page.
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({
          items: [{ slug: "gmail", name: "Gmail" }],
          current_page: 1,
          total_pages: 4,
          total_items: 1540,
        }));
      }
      if (apiKey === "ak_catalog_end_short") {
        // Page counts say more pages exist, but no cursor and no total_items arrive.
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({
          items: [{ slug: "gmail", name: "Gmail" }],
          current_page: 1,
          total_pages: 4,
        }));
      }
      if (apiKey === "ak_catalog_http_no_total") {
        // Reports neither totals nor page counts, so a lost second page is caught only by walk completion.
        if (url.searchParams.get("cursor") === "catalog-page-2") {
          res.writeHead(502, { "content-type": "application/json" });
          return res.end(JSON.stringify({ error: "catalog page unavailable" }));
        }
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({
          items: [
            { slug: "gmail", name: "Gmail" },
            { slug: "bland_ai", name: "Bland AI" },
            { slug: "currencyscoop", name: "CurrencyScoop" },
          ],
          next_cursor: "catalog-page-2",
        }));
      }
      // Like the real marketplace: a usage-sorted head, then an alphabetical tail only page two reaches; ak_catalog_partial loses it.
      if (url.searchParams.get("cursor") === "catalog-page-2") {
        if (apiKey === "ak_catalog_partial") {
          res.writeHead(502, { "content-type": "application/json" });
          return res.end(JSON.stringify({ error: "catalog page unavailable" }));
        }
        res.writeHead(200, { "content-type": "application/json" });
        return res.end(JSON.stringify({
          items: [{ slug: "deepgram", name: "Deepgram" }, { slug: "zoom", name: "Zoom" }],
          current_page: 2,
          total_pages: 2,
          total_items: 5,
        }));
      }
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify({
        items: [
          { slug: "gmail", name: "Gmail" },
          { slug: "bland_ai", name: "Bland AI" },
          { slug: "currencyscoop", name: "CurrencyScoop" },
        ],
        next_cursor: "catalog-page-2",
        current_page: 1,
        total_pages: 2,
        total_items: 5,
      }));
    }
    if (req.method === "GET" && url.pathname === "/api/v3/toolkits") {
      res.writeHead(200, { "content-type": "application/json" });
      if (apiKey === "ak_catalog_a") {
        return res.end(JSON.stringify({ items: [{ slug: "notion", name: "Catalog A", meta: { categories: [{ id: "productivity", name: "Productivity" }, { id: "documents", name: " Documents " }, { id: "productivity", name: "Productivity" }] } }] }));
      }
      if (apiKey === "ak_catalog_b") {
        return res.end(JSON.stringify({ items: [{ slug: "linear", name: "Catalog B" }] }));
      }
      return res.end(JSON.stringify({ items: [{ slug: "x", name: "X (Twitter)" }, { slug: "github", name: "GitHub" }] }));
    }
    if (req.method === "GET" && url.pathname === "/api/v3.1/tool_router/session/trs_test") {
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify({
        session_id: "trs_test",
        mcp: { type: "http", url: "https://app.composio.dev/tool_router/v3/trs_test/mcp" },
        config: {
          user_id: "openmausbot_existing",
          multi_account: {
            enable: true,
            max_accounts_per_toolkit: sessionAccountCap,
            require_explicit_selection: true,
          },
          auth_configs: sessionAuthConfigs,
        },
      }));
    }
    if (req.method === "PATCH" && url.pathname === "/api/v3.1/tool_router/session/trs_test" && body?.multi_account) {
      sessionAccountCap = body.multi_account.max_accounts_per_toolkit;
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify({ session_id: "trs_test" }));
    }
    if (req.method === "GET" && url.pathname === "/api/v3.1/auth_configs") {
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify({ items: customAuthConfigs }));
    }
    if (req.method === "GET" && url.pathname === "/api/v3.1/tool_router/session/trs_legacy") {
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify({
        session_id: "trs_legacy",
        mcp: { type: "http", url: "https://app.composio.dev/tool_router/v3/trs_legacy/mcp" },
        config: { user_id: "openmausbot_legacy" },
      }));
    }
    if (req.method === "GET" && url.pathname.endsWith("/toolkits")) {
      res.writeHead(200, { "content-type": "application/json" });
      if (url.searchParams.get("cursor") === "toolkits-page-2") {
        return res.end(JSON.stringify({
          items: [
            { slug: "publicsearch", is_no_auth: true },
            { slug: "selectedonly", connected_account: { id: "ca_session_only", status: "ACTIVE" } },
          ],
        }));
      }
      const page = {
        items: [
          { slug: "github", connected_account: { id: "ca_github", status: "ACTIVE" } },
          { slug: "gmail", is_no_auth: true },
          ...(url.searchParams.has("toolkits") ? [
            { slug: "slack" },
            { slug: "unconnected", connected_account: null },
          ] : []),
        ],
        next_cursor: url.searchParams.has("toolkits") ? undefined : "toolkits-page-2",
      };
      return res.end(JSON.stringify(page));
    }
    if (req.method === "GET" && url.pathname === "/api/v3.1/connected_accounts") {
      if (connectedAccountsUnavailable) {
        res.writeHead(403, { "content-type": "application/json" });
        return res.end(JSON.stringify({ error: "connected-account read not granted" }));
      }
      res.writeHead(200, { "content-type": "application/json" });
      if (malformedConnectedAccounts) return res.end(JSON.stringify({ items: {} }));
      if (emptyConnectedAccounts) return res.end(JSON.stringify({ items: [] }));
      if (connectedAccountsOverride) return res.end(JSON.stringify({ items: connectedAccountsOverride }));
      if (url.searchParams.get("cursor") === "accounts-page-2") {
        return res.end(JSON.stringify({
          items: [
            { id: "ca_toolkit_41", alias: "overflow", toolkit: { slug: "toolkit_41" }, status: "ACTIVE", updated_at: "2026-08-17T10:00:00Z" },
          ],
        }));
      }
      return res.end(JSON.stringify({
        items: [
          { id: "ca_github_work", alias: "work", toolkit: { slug: "github" }, status: "ACTIVE", updated_at: "2026-08-17T08:00:00Z" },
          { id: "ca_github_personal", alias: "personal", toolkit: { slug: "github" }, status: "ACTIVE", updated_at: "2026-08-17T09:00:00Z" },
          { id: "ca_notion", alias: "team", toolkit: { slug: "notion" }, status: "INITIATED", updated_at: "2026-08-17T08:01:00Z" },
          { id: "ca_linear", toolkit: { slug: "linear" }, status: "EXPIRED", updated_at: "2026-08-17T08:02:00Z" },
        ],
        next_cursor: "accounts-page-2",
      }));
    }
    if (req.method === "POST" && url.pathname.endsWith("/link")) {
      // twitter has no Composio-managed auth: the link only works when the
      // Session was created with the project's own config for it
      if (body.toolkit === "twitter" && !sessionAuthConfigs.twitter) {
        res.writeHead(400, { "content-type": "application/json" });
        return res.end(JSON.stringify({
          error: {
            message:
              "Composio does not manage auth for toolkit twitter and no auth config without required fields is available. "
              + "Please create an auth config manually or specify one in auth_config_override.",
          },
        }));
      }
      res.writeHead(201, { "content-type": "application/json" });
      return res.end(JSON.stringify({ redirect_url: `https://connect.composio.dev/link/${body.toolkit}` }));
    }
    if (req.method === "DELETE" && url.pathname.startsWith("/api/v3.1/connected_accounts/ca_")) {
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify({ success: true }));
    }
    res.writeHead(404, { "content-type": "application/json" });
    res.end(JSON.stringify({ error: "not found" }));
  });
  await new Promise<void>((resolve) => api.listen(0, "127.0.0.1", resolve));
  origin = `http://127.0.0.1:${(api.address() as { port: number }).port}`;
  base = `${origin}/api/v3.1`;
  process.env.OMB_COMPOSIO_API = base;
  process.env.OMB_COMPOSIO_TOOLKITS_API = `${origin}/api/v3`;
});

afterAll(async () => {
  await serviceSlugsReadSettled();
  setManagedBrokerAccess(null);
  delete process.env.OMB_COMPOSIO_API;
  delete process.env.OMB_COMPOSIO_TOOLKITS_API;
  await new Promise<void>((resolve) => api.close(() => resolve()));
});

describe.sequential("Composio Sessions", () => {
  // Fixtures change the project's auth configs from test to test; production reads them at most once a minute.
  beforeEach(() => forgetProjectAuthConfigs());

  it("rejects broker URL components and invalid tokens from the environment", () => {
    process.env.OMB_COMPOSIO_BROKER_TOKEN = "a".repeat(64);
    try {
      for (const url of [
        "https://user:[email protected]/root",
        "https://broker.example/root?redirect=evil",
        "https://broker.example/root#fragment",
      ]) {
        process.env.OMB_COMPOSIO_BROKER_URL = url;
        expect(() => connectionMode({})).toThrow(/must not include/);
      }
      process.env.OMB_COMPOSIO_BROKER_URL = "http://[::1]:3210/root/";
      expect(connectionMode({})).toBe("managed");
      process.env.OMB_COMPOSIO_BROKER_TOKEN = "short";
      expect(() => connectionMode({})).toThrow(/token is invalid/);
    } finally {
      delete process.env.OMB_COMPOSIO_BROKER_URL;
      delete process.env.OMB_COMPOSIO_BROKER_TOKEN;
    }
  });
  it("accepts a private desktop credential update and rejects unsafe broker URLs", () => {
    setManagedBrokerAccess({ url: "http://127.0.0.1:3210/", token: "a".repeat(64) });
    expect(connectionMode({})).toBe("managed");
    setManagedBrokerAccess({ url: "http://[::1]:3210/", token: "a".repeat(64) });
    expect(connectionMode({})).toBe("managed");
    expect(() =>
      setManagedBrokerAccess({ url: "http://broker.example", token: "a".repeat(64) }),
    ).toThrow(/HTTPS/);
    for (const url of [
      "https://user:[email protected]/root",
      "https://broker.example/root?redirect=evil",
      "https://broker.example/root#fragment",
    ]) {
      expect(() => setManagedBrokerAccess({ url, token: "a".repeat(64) })).toThrow(/must not include/);
    }
    expect(() => setManagedBrokerAccess({ url: "https://broker.example", token: "short" })).toThrow();
    setManagedBrokerAccess(null);
  });
  it("ignores credential sync without access and clears only on explicit null", () => {
    const messageType = "openmausbot:managed-composio";
    setManagedBrokerAccess({ url: "http://127.0.0.1:3210/", token: "a".repeat(64) });

    expect(applyManagedBrokerMessage({ type: messageType })).toBe(false);
    expect(connectionMode({})).toBe("managed");

    expect(applyManagedBrokerMessage({ type: messageType, access: null })).toBe(true);
    expect(connectionMode({})).toBe("unavailable");
  });

  it("does not reuse a self-hosted catalog after the project key changes", async () => {
    const before = calls.length;
    const first = await listToolkits({ composio: { apiKey: "ak_catalog_a" } });
    const second = await listToolkits({ composio: { apiKey: "ak_catalog_b" } });

    expect(first.cards).toEqual([expect.objectContaining({ slug: "notion", label: "Catalog A" })]);
    expect(first.cards[0]?.categories).toEqual(["Productivity", "Documents"]);
    expect(second.cards[0]).not.toHaveProperty("categories");
    expect(second.cards).toEqual([expect.objectContaining({ slug: "linear", label: "Catalog B" })]);
    expect(calls.slice(before).filter((call) => call.path === "/api/v3/toolkits").map((call) => call.apiKey)).toEqual([
      "ak_catalog_a",
      "ak_catalog_b",
    ]);
  });

  it("pages the marketplace catalog past the first page", async () => {
    const before = calls.length;
    const { cards, pagination } = await listToolkits({ composio: { apiKey: "ak_catalog_pages" } });

    expect(cards.map((card) => card.slug)).toEqual(["gmail", "bland_ai", "currencyscoop", "deepgram", "zoom"]);
    expect(pagination).toEqual({ items: 5, totalItems: 5, stalled: false, complete: true });
    const pages = calls.slice(before).filter((call) => call.path === "/api/v3/toolkits");
    expect(pages).toHaveLength(2);
    expect(pages[0]?.query).not.toContain("cursor=");
    expect(pages[1]?.query).toContain("cursor=catalog-page-2");
  });

  it("keeps the catalog pages already read when a later page fails", async () => {
    await expect(listToolkits({ composio: { apiKey: "ak_catalog_partial" } })).resolves.toMatchObject({
      source: "api",
      cards: [{ slug: "gmail" }, { slug: "bland_ai" }, { slug: "currencyscoop" }],
    });
  });

  it("stops paging a catalog endpoint that replays the same cursor", async () => {
    const before = calls.length;
    const { cards } = await listToolkits({ composio: { apiKey: "ak_catalog_stuck" } });

    expect(cards).toEqual([expect.objectContaining({ slug: "gmail" })]);
    expect(calls.slice(before).filter((call) => call.path === "/api/v3/toolkits")).toHaveLength(2);
  });

  it("stops cleanly when replayed pages hide behind rotating cursors", async () => {
    const before = calls.length;
    const { cards, pagination } = await listToolkits({ composio: { apiKey: "ak_catalog_page_stuck" } });

    expect(cards).toEqual([expect.objectContaining({ slug: "gmail" })]);
    expect(pagination).toEqual({ items: 1, stalled: true, complete: false, reason: "page-stuck" });
    expect(calls.slice(before).filter((call) => call.path === "/api/v3/toolkits")).toHaveLength(2);
  });

  it("reports a partial catalog when upstream stops offering cursors before its own total", async () => {
    const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
    try {
      const { pagination } = await listToolkits({ composio: { apiKey: "ak_catalog_stalled_total" } });
      expect(pagination).toEqual({ items: 1, totalItems: 1540, stalled: true, complete: false, reason: "end" });
      expect(warn).toHaveBeenCalledWith(expect.stringContaining("partial marketplace"));
    } finally {
      warn.mockRestore();
    }
  });

  it("flags a partial catalog that ends early with only page counts to reveal it", async () => {
    const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
    try {
      const { pagination } = await listToolkits({ composio: { apiKey: "ak_catalog_end_short" } });
        expect(pagination).toEqual({ items: 1, stalled: true, complete: false, reason: "end" });
        expect(warn).toHaveBeenCalledWith(expect.stringContaining("partial marketplace"));
    } finally {
      warn.mockRestore();
    }
  });

  it("flags a catalog that loses a later page mid-walk", async () => {
    const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
    try {
      const { pagination } = await listToolkits({ composio: { apiKey: "ak_catalog_partial" } });
      expect(pagination).toEqual({ items: 3, totalItems: 5, stalled: true, complete: false, reason: "http-error" });
    } finally {
      warn.mockRestore();
    }
  });

  it("keeps pagination with the cached catalog", async () => {
    const first = await listToolkits({ composio: { apiKey: "ak_catalog_stalled_total" } });
    const before = calls.length;
    const second = await listToolkits({ composio: { apiKey: "ak_catalog_stalled_total" } });
    expect(second.pagination).toEqual(first.pagination);
    expect(calls.slice(before)).toHaveLength(0);
  });

  it("marks a catalog that lost a page incomplete even with no totals to compare", async () => {
    const { pagination } = await listToolkits({ composio: { apiKey: "ak_catalog_http_no_total" } });
    expect(pagination).toEqual({ items: 3, stalled: false, complete: false });
  });

  it("stops at the reported last page even when a cursor is still offered", async () => {
    const before = calls.length;
    const { cards } = await listToolkits({ composio: { apiKey: "ak_catalog_exhausted" } });

    expect(cards.map((card) => card.slug)).toEqual(["gmail", "deepgram"]);
    expect(calls.slice(before).filter((call) => call.path === "/api/v3/toolkits")).toHaveLength(2);
  });

  it("drops a managed MCP session when routing switches to a user project", async () => {
    setManagedBrokerAccess({ url: `${origin}/broker`, token: "a".repeat(64) });
    const projectSessions: string[] = [];
    const realFetch = globalThis.fetch;
    const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
      const url = typeof input === "string" || input instanceof URL ? String(input) : input.url;
      if (url.startsWith("https://app.composio.dev/tool_router/")) {
        projectSessions.push(new Headers(init?.headers).get("mcp-session-id") ?? "");
        return new Response(JSON.stringify({ source: "project" }), {
          status: 200,
          headers: { "content-type": "application/json", "mcp-session-id": "mcp_project_after_managed" },
        });
      }
      return realFetch(input, init);
    });
    try {
      const managed = await relayMcp({}, { jsonrpc: "2.0", id: 101, method: "tools/list" });
      expect(managed.transportSessionId).toBe("mcp_broker");
      await relayMcp(
        {},
        { jsonrpc: "2.0", id: 105, method: "tools/list" },
        managed.transportSessionId,
      );
      expect(calls.findLast((call) => call.path === "/broker/v1/mcp" && call.body?.id === 105)?.transportSessionId)
        .toBe("mcp_broker");
      const project = await relayMcp(
        { composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" } },
        { jsonrpc: "2.0", id: 102, method: "tools/list" },
        managed.transportSessionId,
      );
      expect(project.transportSessionId).toBe("mcp_project_after_managed");
      expect(projectSessions).toEqual([""]);
    } finally {
      fetchSpy.mockRestore();
      setManagedBrokerAccess(null);
    }
  });

  it("drops a project MCP session when routing switches to the managed broker", async () => {
    setManagedBrokerAccess({ url: `${origin}/broker`, token: "a".repeat(64) });
    const realFetch = globalThis.fetch;
    const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
      const url = typeof input === "string" || input instanceof URL ? String(input) : input.url;
      if (url.startsWith("https://app.composio.dev/tool_router/")) {
        return new Response(JSON.stringify({ source: "project" }), {
          status: 200,
          headers: { "content-type": "application/json", "mcp-session-id": "mcp_project_before_managed" },
        });
      }
      return realFetch(input, init);
    });
    try {
      const project = await relayMcp(
        { composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" } },
        { jsonrpc: "2.0", id: 103, method: "tools/list" },
      );
      expect(project.transportSessionId).toBe("mcp_project_before_managed");
      await relayMcp(
        {},
        { jsonrpc: "2.0", id: 104, method: "tools/list" },
        project.transportSessionId,
      );
      expect(calls.findLast((call) => call.path === "/broker/v1/mcp" && call.body?.id === 104)?.transportSessionId).toBe("");
    } finally {
      fetchSpy.mockRestore();
      setManagedBrokerAccess(null);
    }
  });

  it("uses a user-owned project for every connector operation even when the managed broker is available", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    setManagedBrokerAccess({ url: `${origin}/broker`, token: "a".repeat(64) });
    const before = calls.length;
    const realFetch = globalThis.fetch;
    const mcpRequests: Array<{ url: string; apiKey: string | null }> = [];
    const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
      const url = typeof input === "string" || input instanceof URL ? String(input) : input.url;
      if (url.startsWith("https://app.composio.dev/tool_router/")) {
        mcpRequests.push({ url, apiKey: new Headers(init?.headers).get("x-api-key") });
        return new Response(JSON.stringify({ source: "project" }), {
          status: 200,
          headers: { "content-type": "application/json", "mcp-session-id": "mcp_project" },
        });
      }
      return realFetch(input, init);
    });

    try {
      expect(connectionMode(cfg)).toBe("self-hosted");
      await expect(listToolkits(cfg)).resolves.toMatchObject({
        source: "api",
        cards: [{ slug: "twitter" }, { slug: "github" }],
      });
      await expect(connectedServices(cfg)).resolves.toHaveProperty("github.connected", true);
      await expect(connectionStatus(cfg, ["slack"])).resolves.toHaveProperty("slack.connected", false);
      await expect(authorizeService(cfg, "slack")).resolves.toEqual({
        url: "https://connect.composio.dev/link/slack",
      });
      await expect(removeAccount(cfg, "github", "ca_github_personal")).resolves.toEqual({ removed: 1 });
      await expect(removeService(cfg, "github")).resolves.toEqual({ removed: 1 });
      const relayed = await relayMcp(cfg, { jsonrpc: "2.0", id: 1, method: "tools/list" });
      expect(JSON.parse(new TextDecoder().decode(relayed.bytes))).toEqual({ source: "project" });
      expect(relayed.transportSessionId).toBe("mcp_project");

      expect(mcpRequests).toEqual([{
        url: "https://app.composio.dev/tool_router/v3/trs_test/mcp",
        apiKey: "ak_test",
      }]);
      const since = calls.slice(before);
      expect(since.some((call) => call.path === "/api/v3.1/tool_router/session/trs_test")).toBe(true);
      expect(since.some((call) => call.path.startsWith("/broker/"))).toBe(false);
    } finally {
      fetchSpy.mockRestore();
      setManagedBrokerAccess(null);
    }
  });

  it("accepts the legacy x alias but authorizes Composio's twitter toolkit", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    sessionAuthConfigs = { twitter: "ac_twitter" };
    setManagedBrokerAccess({ url: `${origin}/broker`, token: "a".repeat(64) });
    const before = calls.length;
    try {
      await expect(authorizeService(cfg, "x")).resolves.toEqual({
        url: "https://connect.composio.dev/link/twitter",
      });
      await expect(connectionStatus(cfg, ["x"])).resolves.toHaveProperty("x.connected", false);
      await expect(removeService(cfg, "x")).resolves.toEqual({ removed: 0 });
      const catalog = await listToolkits(cfg);
      expect(catalog.cards).toContainEqual(expect.objectContaining({ slug: "twitter" }));

      const since = calls.slice(before);
      expect(since.filter((call) => call.method === "POST" && call.path.endsWith("/link")).at(-1)?.body).toEqual({
        toolkit: "twitter",
      });
      expect(since.some((call) => call.query.includes("toolkits=twitter"))).toBe(true);
      expect(since.some((call) => call.path.startsWith("/broker/"))).toBe(false);
    } finally {
      sessionAuthConfigs = {};
      setManagedBrokerAccess(null);
    }
  });

  it("falls back to the managed broker immediately after the project key is cleared", async () => {
    const cfg: AppConfig = { composio: { apiKey: "" } };
    setManagedBrokerAccess({ url: `${origin}/broker`, token: "a".repeat(64) });
    const before = calls.length;
    try {
      expect(connectionMode(cfg)).toBe("managed");
      await expect(connectionStatus(cfg, ["github"])).resolves.toHaveProperty("github.connected", true);
      await expect(authorizeService(cfg, "github")).resolves.toEqual({
        url: "https://connect.composio.dev/managed",
      });
      await expect(listToolkits(cfg)).resolves.toMatchObject({ source: "api", cards: [{ slug: "github" }] });
      const relayed = await relayMcp(cfg, { jsonrpc: "2.0", id: 2, method: "tools/list" });
      expect(JSON.parse(new TextDecoder().decode(relayed.bytes))).toEqual({ source: "broker" });

      const brokerCalls = calls.slice(before).filter((call) => call.path.startsWith("/broker/"));
      expect(brokerCalls.map((call) => `${call.method} ${call.path}`)).toEqual([
        "GET /broker/v1/connectors",
        "POST /broker/v1/connectors/github/authorize",
        "GET /broker/v1/catalog",
        "POST /broker/v1/mcp",
      ]);
    } finally {
      setManagedBrokerAccess(null);
    }
  });

  it("accepts only project API keys", async () => {
    await expect(prepareProjectSession("old_key")).rejects.toThrow(/start with ak_/i);
    await expect(prepareProjectSession("ak_wrong")).rejects.toThrow(/invalid project key/i);
  });

  it("creates one stable per-installation session and reuses it", async () => {
    const created = await prepareProjectSession("ak_test", { userId: "openmausbot_existing" });
    expect(created).toEqual({
      apiKey: "ak_test",
      userId: "openmausbot_existing",
      sessionId: "trs_test",
    });
    expect(calls.filter((call) => call.method === "POST" && call.path.endsWith("/session")).at(-1)?.body).toEqual({
      user_id: "openmausbot_existing",
      manage_connections: {
        enable: true,
        enable_wait_for_connections: true,
        enable_connection_removal: true,
      },
      multi_account: {
        enable: true,
        max_accounts_per_toolkit: 10,
        require_explicit_selection: true,
      },
    });

    const reused = await prepareProjectSession("ak_test", created);
    expect(reused).toEqual({
      apiKey: "ak_test",
      userId: "openmausbot_existing",
      sessionId: "trs_test",
    });
  });

  it("recreates a legacy Session with the same Composio user ID", async () => {
    const upgraded = await prepareProjectSession("ak_test", {
      apiKey: "ak_test",
      userId: "stale-local-user-id",
      sessionId: "trs_legacy",
    });
    expect(upgraded).toEqual({
      apiKey: "ak_test",
      userId: "openmausbot_legacy",
      sessionId: "trs_test",
    });
    expect(calls.filter((call) => call.method === "POST" && call.path.endsWith("/session")).at(-1)?.body).toMatchObject({
      user_id: "openmausbot_legacy",
      multi_account: {
        enable: true,
        max_accounts_per_toolkit: 10,
        require_explicit_selection: true,
      },
    });
  });

  it("names the project's own auth configs at creation and rebuilds a Session that predates them", async () => {
    customAuthConfigs = [
      { id: "ac_twitter_old", toolkit: { slug: "twitter" }, is_composio_managed: false, status: "ENABLED", is_enabled_for_tool_router: true, last_updated_at: "2026-08-20T00:00:00Z" },
      // newest wins, and the slug is matched case-insensitively
      { id: "ac_twitter", toolkit: { slug: "TWITTER" }, is_composio_managed: false, status: "ENABLED", is_enabled_for_tool_router: true, last_updated_at: "2026-08-25T00:00:00Z" },
      // Composio-managed and disabled configs are not the person's; one off for Tool Router waits until its app connects
      { id: "ac_github_managed", toolkit: { slug: "github" }, is_composio_managed: true, status: "ENABLED" },
      { id: "ac_slack_disabled", toolkit: { slug: "slack" }, is_composio_managed: false, status: "DISABLED" },
      { id: "ac_notion_off", toolkit: { slug: "notion" }, is_composio_managed: false, is_enabled_for_tool_router: false },
    ];
    sessionAuthConfigs = {};
    try {
      const current = { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" };
      const before = calls.length;
      await expect(prepareProjectSession("ak_test", current)).resolves.toEqual({ ...current });
      const creates = calls.slice(before).filter((call) => call.method === "POST" && call.path.endsWith("/session"));
      expect(creates).toHaveLength(1);
      expect(creates[0].body).toMatchObject({ user_id: "openmausbot_existing", auth_configs: { twitter: "ac_twitter" } });
      const after = calls.length;
      await prepareProjectSession("ak_test", current);
      expect(calls.slice(after).some((call) => call.method === "POST" && call.path.endsWith("/session"))).toBe(false);
    } finally {
      customAuthConfigs = [];
      sessionAuthConfigs = {};
    }
  });

  it("rebuilds the Session and retries when a toolkit needs an auth config made since the last lookup", async () => {
    sessionAuthConfigs = {};
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "stale-local-user", sessionId: "trs_test" },
    };
    try {
      await prepareProjectSession("ak_test", { userId: "openmausbot_existing" });
      customAuthConfigs = [{ id: "ac_twitter_new", toolkit: { slug: "twitter" }, is_composio_managed: false, status: "ENABLED", is_enabled_for_tool_router: true }];
      const before = calls.length;
      await expect(authorizeService(cfg, "twitter")).resolves.toEqual({ url: "https://connect.composio.dev/link/twitter" });
      const since = calls.slice(before);
      expect(since.filter((call) => call.method === "POST" && call.path.endsWith("/link"))).toHaveLength(2);
      expect(since.filter((call) => call.method === "POST" && call.path.endsWith("/session")).at(-1)?.body).toMatchObject({
        user_id: "openmausbot_existing",
        auth_configs: { twitter: "ac_twitter_new" },
      });
      expect(cfg.composio).toMatchObject({ userId: "openmausbot_existing", sessionId: "trs_test" });
    } finally {
      customAuthConfigs = [];
      sessionAuthConfigs = {};
    }
  });

  it("says what to create when the project has no auth config for the toolkit", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    const before = calls.length;
    await expect(authorizeService(cfg, "twitter")).rejects.toThrow(/create an auth config for "twitter"/i);
    expect(calls.slice(before).some((call) => call.method === "POST" && call.path.endsWith("/session"))).toBe(false);
    expect(cfg.composio).toMatchObject({ userId: "openmausbot_existing", sessionId: "trs_test" });
    await expect(authorizeService(cfg, "github", "personal-three")).resolves.toEqual({
      url: "https://connect.composio.dev/link/github",
    });
  });

  it("does not offer Twitter through the official managed broker without an owned OAuth app", async () => {
    setManagedBrokerAccess({
      url: "https://broker.openmausbot.test",
      token: "a".repeat(64),
    });
    try {
      await expect(authorizeService({} as AppConfig, "twitter")).rejects.toThrow(/X Developer app/i);
      await expect(authorizeService({} as AppConfig, "x")).rejects.toThrow(/self-hosted connected apps/i);
    } finally {
      setManagedBrokerAccess(null);
    }
  });

  it("validates account aliases before sending them upstream", () => {
    expect(normalizeAccountAlias("  personal gmail  ")).toBe("personal gmail");
    expect(() => normalizeAccountAlias("bad\nalias")).toThrow(/printable/i);
    expect(() => normalizeAccountAlias("x".repeat(65))).toThrow(/1-64/i);
  });

  it("mounts the Session MCP endpoint with the project key header", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    const integration = await mcpIntegration(cfg, {
      harnessUrl: "http://127.0.0.1:8799",
      commsToken: "secret",
      botId: "bot-1",
      threadId: "thread-1",
    });
    expect(integration).toMatchObject({
      command: process.execPath,
      args: [expect.stringContaining("connector-proxy")],
      env: {
        OMB_CONNECTOR_UPSTREAM_URL: "http://127.0.0.1:8799/api/internal/connectors/mcp",
        OMB_CONNECTOR_UPSTREAM_HEADERS: JSON.stringify({ authorization: "Bearer secret" }),
        OMB_HARNESS_URL: "http://127.0.0.1:8799",
        OMB_CONNECTOR_TOKEN: "secret",
        OMB_BOT_ID: "bot-1",
        OMB_THREAD_ID: "thread-1",
      },
    });
  });

  it("passes a bot's connector grants to the bridge as an env allowlist", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    const grants: Record<string, ConnectorToolGrant> = { gmail: { tools: ["GMAIL_SEND_EMAIL"] }, slack: { tools: "*" } };
    const integration = await mcpIntegration(cfg, {
      harnessUrl: "http://127.0.0.1:8799",
      commsToken: "secret",
      botId: "bot-1",
      threadId: "thread-1",
      connectorTools: grants,
    });
    expect(integration?.env[CONNECTOR_ALLOWED_TOOLS_ENV]).toBe(JSON.stringify(grants));
  });

  it("omits the allowlist for legacy bots and for oversized grants, warning once", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
    try {
      const legacy = await mcpIntegration(cfg, {
        harnessUrl: "http://127.0.0.1:8799",
        commsToken: "secret",
        botId: "bot-1",
        threadId: "thread-1",
      });
      expect(legacy?.env[CONNECTOR_ALLOWED_TOOLS_ENV]).toBeUndefined();
      expect(warn).not.toHaveBeenCalled();

      const names = Array.from({ length: 500 }, (_, index) => "GMAIL_TOOL_" + String(index).padStart(3, "0") + "_WITH_" + "A_LONG_DESCRIPTOR_".repeat(6));
      const oversized = await mcpIntegration(cfg, {
        harnessUrl: "http://127.0.0.1:8799",
        commsToken: "secret",
        botId: "bot-1",
        threadId: "thread-1",
        connectorTools: { gmail: { tools: names } },
      });
      expect(oversized?.args[0]).toContain("connector-proxy");
      expect(oversized?.env[CONNECTOR_ALLOWED_TOOLS_ENV]).toBeUndefined();
      expect(warn).toHaveBeenCalledTimes(1);
      expect(String(warn.mock.calls[0])).toContain("exceeds 32768 bytes");
    } finally {
      warn.mockRestore();
    }
  });

  it("passes the connected-service slugs to the bridge alongside the allowlist", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "f".repeat(64) });
    brokerConnectedServicesBody = {
      services: {
        bland_ai: { connected: true, status: "ACTIVE" },
        bland: { connected: true, status: "ACTIVE" },
        github: { connected: true, status: "ACTIVE" },
      },
    };
    try {
      const integration = await mcpIntegration({}, {
        harnessUrl: "http://127.0.0.1:8799",
        commsToken: "secret",
        botId: "bot-1",
        threadId: "thread-1",
        connectorTools: { bland: { tools: "*" } },
      });
      const slugs = parseConnectorServiceSlugsEnv(integration?.env[CONNECTOR_SERVICE_SLUGS_ENV]);
      expect(slugs).toContain("bland_ai");
      expect(slugs).toContain("bland");
    } finally {
      brokerConnectedServicesBody = null;
      setManagedBrokerAccess(null);
    }
  });

  it("reads an unreachable connection inventory as no service slugs", async () => {
    await expect(connectedServiceSlugs({})).resolves.toEqual([]);
  });

  it("rejects an unreachable connection inventory instead of reporting no service slugs", async () => {
    await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/unavailable/);
  });

  it("does not cache a failed inventory and retries discovery on the same backend", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "9".repeat(64) });
    const broken = vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("synthetic inventory timeout"));
    try {
      await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/synthetic inventory timeout/);
      await expect(connectedServiceSlugs({})).resolves.toEqual(["github"]);
    } finally {
      broken.mockRestore();
      setManagedBrokerAccess(null);
    }
  });

  it("rejects incomplete account discovery without caching its partial service slugs", async () => {
    vi.useFakeTimers({ toFake: ["Date"] });
    vi.setSystemTime(Date.now() + 61_000);
    const cfg: AppConfig = { composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" } };
    connectedAccountsUnavailable = true;
    try {
      await expect(verifiedConnectedServiceSlugs(cfg)).rejects.toThrow(/inventory.*incomplete/i);
      connectedAccountsUnavailable = false;
      await expect(connectedServiceSlugs(cfg)).resolves.toContain("toolkit_41");
    } finally {
      connectedAccountsUnavailable = false;
      vi.useRealTimers();
    }
  });

  it("rejects a broker response without an inventory instead of caching an empty one", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "b".repeat(64) });
    const broken = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(Response.json({}));
    try {
      await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/services/);
    } finally {
      broken.mockRestore();
      setManagedBrokerAccess(null);
    }
  });

  it("reads a broker that sends no complete field as complete, and an explicit false as incomplete", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "a".repeat(64) });
    try {
      brokerConnectedServicesBody = { services: { gmail: { connected: true, status: "ACTIVE" } } };
      await expect(connectedServicesInventory({})).resolves.toMatchObject({ complete: true });
      await expect(verifiedConnectedServiceSlugs({})).resolves.toEqual(["gmail"]);
      brokerConnectedServicesBody = { complete: false, services: { gmail: { connected: true, status: "ACTIVE" } } };
      await expect(connectedServicesInventory({})).resolves.toMatchObject({ complete: false });
      await expect(verifiedConnectedServiceSlugs({})).rejects.toThrow(/inventory.*incomplete/i);
    } finally {
      brokerConnectedServicesBody = null;
      setManagedBrokerAccess(null);
    }
  });

  it("keeps the last service slugs when a later read fails, so the bridge's tools stay as they were", async () => {
    const access = { url: origin + "/broker", token: "e".repeat(64) };
    brokerConnectedServicesBody = { services: { bland_ai: { connected: true, status: "ACTIVE" } } };
    const start = Date.now();
    const now = vi.spyOn(Date, "now");
    try {
      await expect(connectedServiceSlugs({}, access)).resolves.toEqual(["bland_ai"]);
      brokerConnectedServicesFail = true;
      now.mockReturnValue(start + 61_000);
      await expect(connectedServiceSlugs({}, access)).resolves.toEqual(["bland_ai"]);
      await expect(connectedServiceSlugs({}, { ...access, token: "d".repeat(64) })).resolves.toEqual([]);
    } finally {
      now.mockRestore();
      brokerConnectedServicesFail = false;
      brokerConnectedServicesBody = null;
    }
  });

  it("validates grant patches against connected services and the catalog", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    // github and gmail are connected (session toolkits page 1); slack is not.
    // The ak_test catalog serves x and github.
    await expect(validateConnectorGrants(cfg, { github: { tools: ["GITHUB_CREATE_ISSUE"] } })).resolves.toBeNull();
    await expect(validateConnectorGrants(cfg, { github: { tools: "*" } })).resolves.toBeNull();
    await expect(validateConnectorGrants(cfg, { slack: { tools: ["SLACK_POST_MESSAGE"] } })).resolves.toMatch(/not connected: slack/);
    await expect(validateConnectorGrants(cfg, { gmail: { tools: ["SLACK_POST_MESSAGE"] } })).resolves.toMatch(/another service: SLACK_POST_MESSAGE/);
    // gmail is connected (no-auth toolkit) but absent from the live catalog.
    await expect(validateConnectorGrants(cfg, { gmail: { tools: ["GMAIL_SEND_EMAIL"] } })).resolves.toMatch(/missing from the connected-apps catalog: gmail/);
  });

  it("accepts the built-in Email app's grant, which is never in the connected-apps inventory", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    const email = { tools: [...EMAIL_READ_TOOL_NAMES] };
    const before = calls.length;
    await expect(validateConnectorGrants(cfg, { [EMAIL_SLUG]: email })).resolves.toBeNull();
    // An Email-only grant never waits on the connected-apps catalog.
    expect(calls.slice(before).filter((call) => call.path === "/api/v3/toolkits")).toHaveLength(0);
    await expect(validateConnectorGrants(cfg, { [EMAIL_SLUG]: { tools: "*" }, github: { tools: "*" } })).resolves.toBeNull();
    // Other services are still checked next to it.
    await expect(validateConnectorGrants(cfg, { [EMAIL_SLUG]: email, slack: { tools: ["SLACK_POST_MESSAGE"] } })).resolves.toMatch(/not connected: slack$/);
    await expect(validateConnectorGrants(cfg, { [EMAIL_SLUG]: { tools: ["GITHUB_CREATE_ISSUE"] } })).resolves.toMatch(/another service: GITHUB_CREATE_ISSUE/);
  });

  it("never blocks a grant patch when the connection inventory is unreachable, but still checks prefixes", async () => {
    await expect(validateConnectorGrants({}, { anything: { tools: ["ANYTHING_DO_IT"] } })).resolves.toBeNull();
    await expect(validateConnectorGrants({}, { gmail: { tools: ["SLACK_POST_MESSAGE"] } })).resolves.toMatch(/another service/);
    setManagedBrokerAccess({ url: origin + "/broker", token: "a".repeat(64) });
    try {
      // The broker serves github as connected and its catalog lists github.
      await expect(validateConnectorGrants({}, { github: { tools: ["GITHUB_CREATE_ISSUE"] } })).resolves.toBeNull();
      await expect(validateConnectorGrants({}, { gmail: { tools: ["GMAIL_SEND_EMAIL"] } })).resolves.toMatch(/not connected: gmail/);
    } finally {
      setManagedBrokerAccess(null);
    }
  });

  it("accepts an underscored service's own tool names in its grant", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "f".repeat(64) });
    brokerConnectedServicesBody = {
      services: {
        bland_ai: { connected: true, status: "ACTIVE" },
        bland: { connected: true, status: "ACTIVE" },
        github: { connected: true, status: "ACTIVE" },
      },
    };
    brokerCatalogBody = { items: [{ slug: "github", name: "GitHub" }, { slug: "bland_ai", name: "Bland AI" }, { slug: "bland", name: "Bland" }] };
    try {
      await expect(validateConnectorGrants({}, { bland_ai: { tools: ["BLAND_AI_MAKE_CALL"] } })).resolves.toBeNull();
      await expect(validateConnectorGrants({}, { bland: { tools: ["BLAND_AI_MAKE_CALL"] } }))
        .resolves.toMatch(/another service: BLAND_AI_MAKE_CALL/);
    } finally {
      brokerConnectedServicesBody = null;
      brokerCatalogBody = null;
      setManagedBrokerAccess(null);
    }
  });

  it("does not reject grants against a catalog walk that never finished", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_catalog_http_no_total", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    await expect(validateConnectorGrants(cfg, { github: { tools: ["GITHUB_CREATE_ISSUE"] } })).resolves.toBeNull();
  });

  it("reports connection state, creates auth links and revokes disconnects", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    await expect(connectionStatus(cfg, ["github", "gmail", "slack", "notion", "linear"])).resolves.toEqual({
      github: {
        connected: true,
        pending: false,
        status: "ACTIVE",
        accounts: [
          { id: "ca_github_personal", alias: "personal", status: "ACTIVE" },
          { id: "ca_github_work", alias: "work", status: "ACTIVE" },
          { id: "ca_github", status: "ACTIVE" },
        ],
      },
      gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [] },
      slack: { connected: false, pending: false, status: "not_connected", accounts: [] },
      notion: {
        connected: false,
        pending: true,
        status: "INITIATED",
        accounts: [{ id: "ca_notion", alias: "team", status: "INITIATED" }],
      },
      linear: {
        connected: false,
        pending: false,
        status: "EXPIRED",
        accounts: [{ id: "ca_linear", status: "EXPIRED" }],
      },
    });
    await expect(authorizeService(cfg, "github")).rejects.toThrow(/alias.*not replaced/i);
    await expect(authorizeService(cfg, "github", "work")).rejects.toThrow(/already in use/i);
    await expect(authorizeService(cfg, "github", "personal-two")).resolves.toEqual({
      url: "https://connect.composio.dev/link/github",
    });
    expect(calls.filter((call) => call.method === "POST" && call.path.endsWith("/link")).at(-1)?.body).toEqual({
      toolkit: "github",
      alias: "personal-two",
    });
    await expect(removeAccount(cfg, "github", "ca_github_personal")).resolves.toEqual({ removed: 1 });
    await expect(removeAccount(cfg, "github", "ca_other_user")).resolves.toEqual({ removed: 0 });
    await expect(removeAccount(cfg, "github", "../other")).rejects.toThrow(/invalid connected-account ID/i);
    await expect(removeService(cfg, "github")).resolves.toEqual({ removed: 1 });
    expect(calls.some(
      (call) => call.method === "DELETE"
        && call.path.endsWith("/connected_accounts/ca_github")
        && call.query === "?revoke_on_delete=true",
    )).toBe(true);
  });

  it("enumerates connected services independently of catalog position", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    const callCount = calls.length;

    await expect(connectedServices(cfg)).resolves.toMatchObject({
      toolkit_41: {
        connected: true,
        pending: false,
        status: "ACTIVE",
        accounts: [{ id: "ca_toolkit_41", alias: "overflow", status: "ACTIVE" }],
      },
      github: {
        accounts: [
          { id: "ca_github_personal", alias: "personal", status: "ACTIVE" },
          { id: "ca_github_work", alias: "work", status: "ACTIVE" },
          { id: "ca_github", status: "ACTIVE" },
        ],
      },
      publicsearch: {
        connected: true,
        pending: false,
        status: "ACTIVE",
        accounts: [],
      },
      selectedonly: {
        connected: true,
        pending: false,
        status: "ACTIVE",
        accounts: [{ id: "ca_session_only", status: "ACTIVE" }],
      },
    });

    const inventoryCalls = calls.slice(callCount).filter((call) => call.path.endsWith("/connected_accounts"));
    expect(inventoryCalls).toHaveLength(2);
    expect(inventoryCalls[0]?.query).not.toContain("toolkit_slugs=");
    expect(inventoryCalls[1]?.query).toContain("cursor=accounts-page-2");
    const toolkitCalls = calls.slice(callCount).filter((call) => call.path.endsWith("/toolkits"));
    expect(toolkitCalls).toHaveLength(2);
    expect(toolkitCalls[0]?.query).toContain("is_connected=true");
    expect(toolkitCalls[1]?.query).toContain("cursor=toolkits-page-2");
  });

  it("falls back to complete Session toolkit state without connected-account read permission", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    connectedAccountsUnavailable = true;
    try {
      const inventory = await connectedServicesInventory(cfg);
      expect(inventory.complete).toBe(false);
      expect(inventory.services).toMatchObject({
        github: {
          connected: true,
          status: "ACTIVE",
          accounts: [{ id: "ca_github", status: "ACTIVE" }],
        },
        gmail: { connected: true, status: "ACTIVE", accounts: [] },
        publicsearch: { connected: true, status: "ACTIVE", accounts: [] },
        selectedonly: {
          connected: true,
          status: "ACTIVE",
          accounts: [{ id: "ca_session_only", status: "ACTIVE" }],
        },
      });
    } finally {
      connectedAccountsUnavailable = false;
    }
  });

  it("falls back to session toolkit state when connected-account items is malformed", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    malformedConnectedAccounts = true;
    try {
      await expect(connectionStatus(cfg, ["github", "slack"])).resolves.toEqual({
        github: { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "ca_github", status: "ACTIVE" }] },
        slack: { connected: false, pending: false, status: "not_connected", accounts: [] },
      });
    } finally {
      malformedConnectedAccounts = false;
    }
  });

  it("uses the provided alias for the first account authorization", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    emptyConnectedAccounts = true;
    try {
      await expect(connectionStatus(cfg, ["slack"])).resolves.toMatchObject({
        slack: { connected: false, pending: false, accounts: [] },
      });
      const before = calls.length;
      await expect(authorizeService(cfg, "slack", "team")).resolves.toEqual({
        url: "https://connect.composio.dev/link/slack",
      });
      const linkCalls = calls.slice(before).filter((call) => call.method === "POST" && call.path.endsWith("/link"));
      expect(linkCalls).toHaveLength(1);
      expect(linkCalls[0].body).toEqual({ toolkit: "slack", alias: "team" });
    } finally {
      emptyConnectedAccounts = false;
    }
  });

  it("retries unfinished or expired flows with fresh aliases without replacing or deleting accounts", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "stale-local-user", sessionId: "trs_test" },
    };
    try {
      for (const status of ["INITIALIZING", "INITIATED", "EXPIRED"]) {
        connectedAccountsOverride = [
          { id: "ca_unfinished", alias: "personal", status, toolkit: { slug: "slack" } },
          { id: "ca_expired", status: "expired", toolkit: { slug: "SLACK" } },
          { id: "ca_other_toolkit", status: "ACTIVE", toolkit: { slug: "github" } },
        ];
        const before = calls.length;
        await expect(authorizeService(cfg, "SLACK")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
        await expect(authorizeService(cfg, "slack")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
        const since = calls.slice(before);
        const links = since.filter((call) => call.method === "POST" && call.path.endsWith("/link"));
        expect(links).toHaveLength(2);
        for (const link of links) expect(link.body).toEqual({ toolkit: "slack", alias: expect.stringMatching(/^omb-retry-[0-9a-f-]{36}$/) });
        expect(links[0].body.alias).not.toBe(links[1].body.alias);
        expect(since.filter((call) => call.path.endsWith("/connected_accounts")).every((call) =>
          new URLSearchParams(call.query).get("user_ids") === "openmausbot_existing"
        )).toBe(true);
        expect(since.some((call) => call.method === "DELETE" || call.method === "PATCH")).toBe(false);
        expect(connectedAccountsOverride[0].alias).toBe("personal");
      }
    } finally {
      connectedAccountsOverride = null;
    }
  });

  it("requires a label only beside an account that may be working, and keeps that account's label", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    try {
      for (const status of ["ACTIVE", undefined]) {
        connectedAccountsOverride = [
          { id: "ca_existing", alias: "Personal", status, toolkit: { slug: "slack" } },
        ];
        const before = calls.length;
        await expect(authorizeService(cfg, "slack")).rejects.toThrow(/alias.*not replaced/i);
        connectedAccountsOverride.push({ id: "ca_unfinished", status: "INITIALIZING", toolkit: { slug: "slack" } });
        await expect(authorizeService(cfg, "slack")).rejects.toThrow(/alias.*not replaced/i);
        await expect(authorizeService(cfg, "slack", "personal")).rejects.toThrow(/already in use/i);
        const since = calls.slice(before);
        expect(since.some((call) => call.method === "POST" && call.path.endsWith("/link"))).toBe(false);
        expect(since.some((call) => call.method === "DELETE")).toBe(false);
      }
      await expect(authorizeService(cfg, "slack", "  team  ")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
      expect(calls.filter((call) => call.method === "POST" && call.path.endsWith("/link")).at(-1)?.body).toEqual({
        toolkit: "slack", alias: "team",
      });
    } finally {
      connectedAccountsOverride = null;
    }
  });

  it("links a toolkit whose only account failed to sign in", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    try {
      for (const status of ["FAILED", "INACTIVE", "EXPIRED"]) {
        connectedAccountsOverride = [{ id: "ca_dead", status, toolkit: { slug: "slack" } }];
        const before = calls.length;
        await expect(authorizeService(cfg, "slack")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
        const since = calls.slice(before);
        expect(since.filter((call) => call.method === "POST" && call.path.endsWith("/link"))).toHaveLength(1);
        expect(since.some((call) => call.method === "DELETE")).toBe(false);
      }
    } finally {
      connectedAccountsOverride = null;
    }
  });

  it("replaces an account that is not active when its label is asked for again", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    try {
      for (const status of ["INITIATED", "INITIALIZING", "FAILED", "EXPIRED", "INACTIVE"]) {
        connectedAccountsOverride = [
          { id: "ca_old_work", alias: "Work", status, toolkit: { slug: "slack" } },
          { id: "ca_personal", alias: "personal", status: "ACTIVE", toolkit: { slug: "slack" } },
        ];
        const before = calls.length;
        await expect(authorizeService(cfg, "slack", "work")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
        const since = calls.slice(before).filter((call) => call.method === "DELETE" || call.path.endsWith("/link"));
        expect(since.map((call) => [call.method, call.path, call.query])).toEqual([
          ["DELETE", "/api/v3.1/connected_accounts/ca_old_work", "?revoke_on_delete=true"],
          ["POST", "/api/v3.1/tool_router/session/trs_test/link", ""],
        ]);
        expect(since[1]!.body).toEqual({ toolkit: "slack", alias: "work" });
      }
      connectedAccountsOverride = [{ id: "ca_work", alias: "work", status: "ACTIVE", toolkit: { slug: "slack" } }];
      const before = calls.length;
      await expect(authorizeService(cfg, "slack", "work")).rejects.toThrow(/already in use/i);
      expect(calls.slice(before).some((call) => call.method === "DELETE" || call.path.endsWith("/link"))).toBe(false);
    } finally {
      connectedAccountsOverride = null;
    }
  });

  it("does not bypass the account cap when retrying pending connections", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    connectedAccountsOverride = Array.from({ length: 10 }, (_, index) => ({
      id: `ca_pending_${index}`, status: "INITIALIZING", toolkit: { slug: "slack" },
    }));
    const before = calls.length;
    try {
      await expect(authorizeService(cfg, "slack")).rejects.toThrow(/maximum of 10 accounts/i);
      await expect(authorizeService(cfg, "slack", "team")).rejects.toThrow(/maximum of 10 accounts/i);
      expect(calls.slice(before).some((call) => call.method === "POST" && call.path.endsWith("/link"))).toBe(false);
    } finally {
      connectedAccountsOverride = null;
    }
  });

  it("still links when the request to raise the old cap cannot reach Composio, and tries again next time", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    sessionAccountCap = 5;
    connectedAccountsOverride = [{ id: "ca_sub_0", alias: "sub-0", status: "ACTIVE", toolkit: { slug: "slack" } }];
    const realFetch = globalThis.fetch;
    const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
      if (init?.method === "PATCH") throw new TypeError("fetch failed");
      return realFetch(input, init);
    });
    const before = calls.length;
    try {
      await expect(authorizeService(cfg, "slack", "sub-1")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
      expect(calls.slice(before).some((call) => call.method === "POST" && call.path.endsWith("/link"))).toBe(true);
      expect(fetchSpy.mock.calls.some(([, init]) => init?.method === "PATCH")).toBe(true);
    } finally {
      fetchSpy.mockRestore();
      sessionAccountCap = 10;
      connectedAccountsOverride = null;
    }
  });

  it("links a sixth account, raising a Session made under the old cap of 5 in place first", async () => {
    const cfg: AppConfig = {
      composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
    };
    sessionAccountCap = 5;
    connectedAccountsOverride = Array.from({ length: 5 }, (_, index) => ({
      id: `ca_sub_${index}`, alias: `sub-${index}`, status: "ACTIVE", toolkit: { slug: "slack" },
    }));
    const before = calls.length;
    try {
      await expect(authorizeService(cfg, "slack", "sub-5")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
      const since = calls.slice(before).filter((call) => call.method === "PATCH" || call.path.endsWith("/link"));
      expect(since.map((call) => [call.method, call.path])).toEqual([
        ["PATCH", "/api/v3.1/tool_router/session/trs_test"],
        ["POST", "/api/v3.1/tool_router/session/trs_test/link"],
      ]);
      expect(since[0]!.body).toEqual({
        multi_account: { enable: true, max_accounts_per_toolkit: 10, require_explicit_selection: true },
      });
      expect(cfg.composio?.sessionId).toBe("trs_test");

      // Raised once: the next sign-in link goes straight through.
      const again = calls.length;
      await expect(authorizeService(cfg, "slack", "sub-6")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
      expect(calls.slice(again).some((call) => call.method === "PATCH")).toBe(false);
    } finally {
      sessionAccountCap = 10;
      connectedAccountsOverride = null;
    }
  });
});

describe("a connector tools/list that fails", () => {
  const list = async (id: number) => {
    const relayed = await relayMcp({}, { jsonrpc: "2.0", id, method: "tools/list" });
    return { status: relayed.status, body: JSON.parse(new TextDecoder().decode(relayed.bytes)) };
  };

  it("answers with the same backend's last good list", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "9".repeat(64) });
    brokerMcpTools = [{ name: "GMAIL_SEND_EMAIL" }, { name: "COMPOSIO_MANAGE_CONNECTIONS" }];
    const realFetch = globalThis.fetch;
    let offline = false;
    const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
      if (offline) throw new TypeError("fetch failed");
      return realFetch(input, init);
    });
    try {
      expect((await list(1)).status).toBe(200);
      brokerToolsListFail = true;
      await expect(list(2)).resolves.toEqual({
        status: 200,
        body: { jsonrpc: "2.0", id: 2, result: { tools: [{ name: "GMAIL_SEND_EMAIL" }, { name: "COMPOSIO_MANAGE_CONNECTIONS" }] } },
      });
      offline = true;
      expect((await list(3)).body.id).toBe(3);
      offline = false;

      setManagedBrokerAccess({ url: origin + "/broker", token: "8".repeat(64) });
      expect((await list(4)).status).toBe(500);
    } finally {
      fetchSpy.mockRestore();
      brokerToolsListFail = false;
      brokerMcpTools = null;
      setManagedBrokerAccess(null);
    }
  });
});

describe("connector tool inventory", () => {
  const initializeCalls = () =>
    calls.filter((call) => call.path.endsWith("/v1/mcp") && call.body?.method === "initialize");

  it("groups tools using the cached service inventory after a failed refresh", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "8".repeat(64) });
    brokerConnectedServicesBody = { services: { bland_ai: { connected: true, status: "ACTIVE" } } };
    brokerMcpTools = [{ name: "BLAND_AI_MAKE_CALL" }];
    await expect(connectedServiceSlugs({})).resolves.toEqual(["bland_ai"]);
    const now = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 61_000);
    const broken = vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("synthetic inventory timeout"));
    try {
      await expect(listConnectorTools({})).resolves.toEqual({ bland_ai: [{ name: "BLAND_AI_MAKE_CALL" }] });
    } finally {
      broken.mockRestore();
      now.mockRestore();
      brokerMcpTools = null;
      brokerConnectedServicesBody = null;
      setManagedBrokerAccess(null);
    }
  });

  it("groups an underscored service under its own slug using the connected services", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "c".repeat(64) });
    brokerConnectedServicesBody = {
      services: { bland_ai: { connected: true, status: "ACTIVE" }, github: { connected: true, status: "ACTIVE" } },
    };
    brokerMcpTools = [
      { name: "BLAND_AI_MAKE_CALL", description: "place a call" },
      { name: "GITHUB_CREATE_ISSUE", description: "open an issue" },
    ];
    try {
      await expect(listConnectorTools({})).resolves.toEqual({
        bland_ai: [{ name: "BLAND_AI_MAKE_CALL", description: "place a call" }],
        github: [{ name: "GITHUB_CREATE_ISSUE", description: "open an issue" }],
      });
    } finally {
      brokerMcpTools = null;
      brokerConnectedServicesBody = null;
      setManagedBrokerAccess(null);
    }
  });

  it("marks a tool read-only only when its own listing says it reads and does not destroy", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "f".repeat(64) });
    brokerConnectedServicesBody = { services: { gmail: { connected: true, status: "ACTIVE" } } };
    brokerMcpTools = [
      { name: "GMAIL_SEND_EMAIL", annotations: { readOnlyHint: true } },
      { name: "GMAIL_FETCH_EMAILS" },
      { name: "GMAIL_LIST_LABELS", annotations: { readOnlyHint: true, destructiveHint: true } },
      { name: "GMAIL_GET_PROFILE", annotations: { readOnlyHint: "yes" } },
    ];
    try {
      await expect(listConnectorTools({})).resolves.toEqual({ gmail: [
        { name: "GMAIL_FETCH_EMAILS" }, { name: "GMAIL_GET_PROFILE" }, { name: "GMAIL_LIST_LABELS" }, { name: "GMAIL_SEND_EMAIL", readOnly: true },
      ] });
    } finally {
      brokerMcpTools = null;
      brokerConnectedServicesBody = null;
      setManagedBrokerAccess(null);
    }
  });

  it("re-walks after a backend switch instead of serving the cached inventory", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "d".repeat(64) });
    brokerMcpTools = [{ name: "GITHUB_CREATE_ISSUE" }];
    try {
      await expect(listConnectorTools({})).resolves.toEqual({ github: [{ name: "GITHUB_CREATE_ISSUE" }] });

      // A different broker token is a different backend: within the 60s
      // cache window the switch must still serve the new backend's walk.
      setManagedBrokerAccess({ url: origin + "/broker", token: "e".repeat(64) });
      brokerMcpTools = [{ name: "SLACK_POST_MESSAGE" }];
      const before = initializeCalls().length;
      await expect(listConnectorTools({})).resolves.toEqual({ slack: [{ name: "SLACK_POST_MESSAGE" }] });
      expect(initializeCalls().length).toBe(before + 1);
    } finally {
      brokerMcpTools = null;
      setManagedBrokerAccess(null);
    }
  });

  it("shares one in-flight walk between concurrent callers", async () => {
    setManagedBrokerAccess({ url: origin + "/broker", token: "a".repeat(64) });
    brokerMcpTools = [{ name: "GITHUB_CREATE_ISSUE" }, { name: "GITHUB_LIST_REPOS" }];
    try {
      const before = initializeCalls().length;
      const [first, second] = await Promise.all([listConnectorTools({}), listConnectorTools({})]);
      expect(second).toEqual(first);
      expect(initializeCalls().length).toBe(before + 1);
    } finally {
      brokerMcpTools = null;
      setManagedBrokerAccess(null);
    }
  });
});

describe("toolkitCategories", () => {
  it("reads named objects and plain strings, and drops anything else", () => {
    expect(toolkitCategories([{ id: "crm", name: "CRM" }, "Sales", { id: "x" }, 7, null, "  "])).toEqual(["CRM", "Sales"]);
    expect(toolkitCategories(undefined)).toBeUndefined();
    expect(toolkitCategories("CRM")).toBeUndefined();
    expect(toolkitCategories([])).toBeUndefined();
    expect(toolkitCategories(["a", "b", "c", "d", "e"])).toHaveLength(4);
  });
});