Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
perf(server): acquire browser attachments only for consuming connectors (#201)
Leo1b09cfa94bba
diff --git a/apps/server/src/provider/AkeruSessionResources.test.ts b/apps/server/src/provider/AkeruSessionResources.test.tsindex 6e886fdfe..b330ef7ac 100644--- a/apps/server/src/provider/AkeruSessionResources.test.ts+++ b/apps/server/src/provider/AkeruSessionResources.test.ts@@ -9,6 +9,7 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";import { AkeruSessionResources } from "./AkeruSessionResources.ts";import { CODEX_COMPUTER_USE_SERVER_ID } from "./CodexComputerUse.ts";+import { createBotBrowser } from "./botBrowser.ts";import {type AkeruBotWorkspace,type AkeruRemoteSession,@@ -134,6 +135,90 @@ describe("AkeruSessionResources", () => {expect(sharedBrowser.close).toHaveBeenCalledOnce();});+ it.each(["local", "vercel", "e2b", "daytona", "upstash"] as const)(+ "acquires only usable connector browser attachments in %s workspaces",+ async (botSandbox) => {+ for (const transport of ["stdio", "url"] as const) {+ for (const id of ["builtin-executor", "builtin-tinyfish", "builtin-exa", "raw-mcp"]) {+ const botBrowser = browser();+ const attachment = {+ browserUrl: "https://sandbox.example/browser",+ mcpSessionId: "session",+ requestHeaders: {},+ localRequestHeaders: {},+ availableToHostedPlugins: botSandbox !== "local",+ };+ const acquireAttachment = vi.fn(async () => attachment);+ const manager = mcpManager({ connected: true, toolCount: 1 });+ const toMcpServerConfigs = vi.fn(() => ({}));+ const resources = new AkeruSessionResources({+ stateDir: stateDir(),+ makeRemoteWorkspace: async () => workspace(),+ makeBotBrowser: () => ({ ...botBrowser, attachment: acquireAttachment }),+ makeMcpManager: () => manager as never,+ toMcpServerConfigs,+ });+ const server = {+ ...exaServer,+ id: McpServerId.make(id),+ transport,+ command: "connector",+ };+ try {+ await resources.acquire({+ ...remoteInput,+ botSandbox,+ threadId: "connector",+ mcpServers: [server, exaServer],+ });+ const requiresBrowser =+ (id === "builtin-executor" || id === "builtin-tinyfish") &&+ (transport === "stdio" || botSandbox !== "local");+ expect(acquireAttachment).toHaveBeenCalledTimes(requiresBrowser ? 1 : 0);+ expect(toMcpServerConfigs).toHaveBeenCalledWith(+ [server, exaServer],+ requiresBrowser ? attachment : undefined,+ );+ expect(manager.init).toHaveBeenCalledOnce();+ } finally {+ await resources.shutdown();+ }+ }+ }+ },+ );++ it("does no browser work for unrelated MCP startup and retains on-demand browser tools", async () => {+ const attachment = vi.fn(async () => undefined);+ const call = vi.fn(async () => "page tree");+ const close = vi.fn(async () => undefined);+ const resources = new AkeruSessionResources({+ stateDir: stateDir(),+ makeRemoteWorkspace: async () => workspace(),+ makeBotBrowser: (input) =>+ createBotBrowser({+ ...input,+ makeRpc: () => ({ attachment, call, close, reconnect: async () => undefined }),+ }),+ makeMcpManager: () => mcpManager({ connected: true, toolCount: 1 }) as never,+ toMcpServerConfigs: () => ({}),+ });+ try {+ await resources.acquire({ ...remoteInput, threadId: "lazy", mcpServers: [exaServer] });+ expect(attachment).not.toHaveBeenCalled();+ expect(call).not.toHaveBeenCalled();+ const tool = resources.getConnectorTools("lazy").browser_snapshot as {+ execute: (input: Record<string, unknown>) => Promise<unknown>;+ };+ await tool.execute({});+ expect(call).toHaveBeenCalledExactlyOnceWith("tree", {});+ expect(attachment).not.toHaveBeenCalled();+ } finally {+ await resources.shutdown();+ }+ expect(close).toHaveBeenCalledOnce();+ });+it("coalesces concurrent acquisition for the same thread", async () => {const remote = workspace();const stop = vi.spyOn(remote, "stop");@@ -474,13 +559,14 @@ describe("AkeruSessionResources", () => {await resources.shutdown();});- it("allows one Computer Use controller and releases it on stop", async () => {+ it("allows one Computer Use controller and releases it on stop without a browser attachment", async () => {const manager = mcpManager({ connected: true, toolCount: 1 });+ const botBrowser = browser();const resources = new AkeruSessionResources({stateDir: stateDir(),hostPlatform: "darwin",makeRemoteWorkspace: async () => workspace(),- makeBotBrowser: () => browser(),+ makeBotBrowser: () => botBrowser,makeMcpManager: () => manager as never,resolveComputerUseServer: async () => ({command: "/local/launcher",@@ -499,6 +585,7 @@ describe("AkeruSessionResources", () => {);await resources.release("controller");await resources.acquire({ ...input, threadId: "replacement" });+ expect(botBrowser.attachment).not.toHaveBeenCalled();await resources.shutdown();});@@ -535,7 +622,7 @@ describe("AkeruSessionResources", () => {await resources.shutdown();});- it("creates and attaches a browser for remote workspaces", async () => {+ it("keeps remote browser tools lazy for a connector without browser dependencies", async () => {const browserEndpoint = vi.fn(async () => ({url: "https://browser.example",requestHeaders: { authorization: "Bearer token" },@@ -587,7 +674,7 @@ describe("AkeruSessionResources", () => {expect(makeBotBrowser).toHaveBeenCalledWith(expect.objectContaining({ browserEndpoint, workspace: remote.workspace }),);- expect(remoteBrowser.attachment).toHaveBeenCalledOnce();+ expect(remoteBrowser.attachment).not.toHaveBeenCalled();expect(toMcpServerConfigs).toHaveBeenCalledWith(expect.any(Array), undefined);expect(resources.getConnectorTools("remote-mcp")).toEqual({ exa_search: {} });await resources.shutdown();diff --git a/apps/server/src/provider/AkeruSessionResources.ts b/apps/server/src/provider/AkeruSessionResources.tsindex 449faa41d..35c800efa 100644--- a/apps/server/src/provider/AkeruSessionResources.ts+++ b/apps/server/src/provider/AkeruSessionResources.ts@@ -24,6 +24,7 @@ import {type CreateRemoteBotWorkspaceInput,} from "./botWorkspace.ts";import { BotWorkspacePool, type BotWorkspaceLease } from "./botWorkspacePool.ts";+import { mcpServerNeedsBrowserAttachment } from "./McpServerConfig.ts";import {CODEX_COMPUTER_USE_SERVER_ID,isCodexComputerUseServer,@@ -213,7 +214,11 @@ export class AkeruSessionResources {const previewMcpServerConfig = this.options.getPreviewMcpServerConfig?.(key);if (input.mcpServers.length > 0 || previewMcpServerConfig) {- const attachment = input.mcpServers.length > 0 ? await browser.attachment() : undefined;+ const attachment = input.mcpServers.some((server) =>+ mcpServerNeedsBrowserAttachment(server, remote),+ )+ ? await browser.attachment()+ : undefined;const configs = this.options.toMcpServerConfigs(input.mcpServers, attachment);if (previewMcpServerConfig) {configs[T3_CODE_PREVIEW_MCP_SERVER_NAME] = previewMcpServerConfig;diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.tsindex dcc143344..c0056c628 100644--- a/apps/server/src/provider/Layers/AgentController.test.ts+++ b/apps/server/src/provider/Layers/AgentController.test.ts@@ -365,6 +365,7 @@ function makeLayer(| "memoryCandidateRepository"| "issueMcpCredential"| "revokeMcpCredential"+ | "makeBotBrowser">,delegationRuntime?: AgentControllerLiveOptions["delegationRuntime"],) {@@ -373,13 +374,14 @@ function makeLayer(...(makeMcpManager ? { makeMcpManager } : {}),...overrides,...(delegationRuntime ? { delegationRuntime } : {}),- makeBotBrowser: () =>- ({+ makeBotBrowser:+ overrides?.makeBotBrowser ??+ (() => ({tools: {},attachment: async () => undefined,reconnect: async () => undefined,close: async () => undefined,- }) as never,+ })),}).pipe(Layer.provide(Layer.mergeAll(@@ -410,6 +412,7 @@ function provideController<A, E>(| "memoryCandidateRepository"| "issueMcpCredential"| "revokeMcpCredential"+ | "makeBotBrowser">,) {return effect.pipe(@@ -468,6 +471,52 @@ describe("toMcpServerConfigs", () => {});});+ it("attaches browser metadata only to dependent connectors and preserves authentication", () => {+ const server = withMcpRuntimeHeaders(+ {+ id: McpServerId.make("builtin-tinyfish"),+ name: "TinyFish",+ transport: "url" as const,+ url: "https://example.com/mcp",+ enabled: true,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ },+ { Authorization: "Bearer fixture" },+ );+ const browser = {+ browserUrl: "https://sandbox.example/browser",+ mcpSessionId: "session",+ requestHeaders: { "sandbox-key": "remote" },+ localRequestHeaders: { "sandbox-key": "local" },+ availableToHostedPlugins: true,+ };+ const local = { ...server, transport: "stdio" as const, command: "executor" };+ expect(toMcpServerConfigs([server], browser)[server.id]).toEqual({+ url: server.url,+ headers: {+ Authorization: "Bearer fixture",+ "x-akeru-browser-mcp-url": browser.browserUrl,+ "x-akeru-browser-mcp-session-id": "session",+ "x-akeru-browser-mcp-headers": JSON.stringify(browser.requestHeaders),+ },+ });+ expect(toMcpServerConfigs([local], browser)[server.id]).toMatchObject({+ env: { AKERU_BROWSER_MCP_HEADERS: JSON.stringify(browser.localRequestHeaders) },+ });+ expect(+ toMcpServerConfigs([server], { ...browser, availableToHostedPlugins: false })[server.id],+ ).toEqual({+ url: server.url,+ headers: { Authorization: "Bearer fixture" },+ });+ const unrelated = { ...local, id: McpServerId.make("builtin-exa") };+ expect(toMcpServerConfigs([unrelated], browser)[unrelated.id]).not.toHaveProperty("env");+ expect(+ toMcpServerConfigs([{ ...server, enabled: false }], browser)[server.id],+ ).not.toHaveProperty("headers");+ });+it("forwards transient MCP headers without adding them to the server record", () => {const server = withMcpRuntimeHeaders({@@ -617,6 +666,79 @@ describe("provider access health", () => {});describe("AgentControllerLive", () => {+ for (const provider of [+ "codex",+ "kimi",+ "opencodeGo",+ "claudeAgent",+ "grok",+ "opencode",+ ] as const) {+ it.effect(`keeps unrelated connector browser acquisition lazy for ${provider}`, () => {+ const bridge = makeBridge();+ const mastra = makeMastraHarness();+ const attachment = vi.fn(async () => undefined);+ const manager = {+ init: vi.fn(async () => undefined),+ disconnect: vi.fn(async () => undefined),+ getTools: () => ({}),+ getServerStatuses: () => [],+ };+ return provideController(+ Effect.gen(function* () {+ const controller = yield* AgentController;+ const threadId = ThreadId.make(`lazy-${provider}`);+ const instanceId = ProviderInstanceId.make(provider);+ const selection = { instanceId, model: "fixture-model" };+ yield* controller.resolveEngine({+ threadId,+ engine: null,+ fallback: selection,+ mode: "default",+ botConversation: true,+ });+ yield* controller.startSession(threadId, {+ threadId,+ provider: ProviderDriverKind.make(provider),+ providerInstanceId: instanceId,+ modelSelection: selection,+ runtimeMode: "full-access",+ mcpServers: [+ {+ id: McpServerId.make("builtin-exa"),+ name: "Exa",+ transport: "url",+ url: "https://mcp.exa.ai/mcp",+ enabled: true,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ });+ expect(attachment).not.toHaveBeenCalled();+ expect(manager.init).toHaveBeenCalledOnce();+ expect(bridge.startSession).toHaveBeenCalledTimes(+ provider === "codex" || provider === "kimi" || provider === "opencodeGo" ? 0 : 1,+ );+ yield* controller.stopSession({ threadId });+ }),+ bridge.service,+ mastra.factory,+ () => manager as never,+ undefined,+ undefined,+ {+ makeBotBrowser: () => ({+ tools: {},+ attachment,+ reconnect: async () => undefined,+ close: async () => undefined,+ }),+ },+ );+ });+ }+it("bills delegated usage receipts to the child bot", () => {const childBotId = BotId.make("bot-child");const childThreadId = ThreadId.make("thread-child");diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 5360711e4..c2cc2fc41 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -103,7 +103,11 @@ import {createAkeruPluginRuntime,type AkeruPluginRuntimeOptions,} from "../AkeruCatalogToolHandlers.ts";-import { getMcpRuntimeHeaders, sameMcpServerConfigurations } from "../McpServerConfig.ts";+import {+ getMcpRuntimeHeaders,+ mcpServerNeedsBrowserAttachment,+ sameMcpServerConfigurations,+} from "../McpServerConfig.ts";import {createAkeruToolRuntime,isMemoryToolId,@@ -318,8 +322,6 @@ function mastraModeId(mode: "default" | "plan"): string {return mode === "plan" ? PLAN_MODE_ID : DEFAULT_MODE_ID;}-const BROWSER_AWARE_MCP_SERVER_IDS = new Set(["builtin-executor", "builtin-tinyfish"]);-export function toMcpServerConfigs(servers: readonly McpServer[],browser?: BotBrowserAttachment,@@ -342,9 +344,10 @@ export function toMcpServerConfigs(? { headers: getMcpRuntimeHeaders(server) }: {}),...(browser?.availableToHostedPlugins &&- BROWSER_AWARE_MCP_SERVER_IDS.has(String(server.id))+ mcpServerNeedsBrowserAttachment(server, browser.availableToHostedPlugins)? {headers: {+ ...getMcpRuntimeHeaders(server),"x-akeru-browser-mcp-url": browser.browserUrl,"x-akeru-browser-mcp-session-id": browser.mcpSessionId,"x-akeru-browser-mcp-headers": browserRequestHeaders!,@@ -355,7 +358,9 @@ export function toMcpServerConfigs(: {command: server.command,...(server.args ? { args: [...server.args] } : {}),- ...(browserEnvironment && BROWSER_AWARE_MCP_SERVER_IDS.has(String(server.id))+ ...(browserEnvironment &&+ browser &&+ mcpServerNeedsBrowserAttachment(server, browser.availableToHostedPlugins)? { env: browserEnvironment }: {}),},diff --git a/apps/server/src/provider/McpServerConfig.test.ts b/apps/server/src/provider/McpServerConfig.test.tsindex 9d4233c98..f033ea7de 100644--- a/apps/server/src/provider/McpServerConfig.test.ts+++ b/apps/server/src/provider/McpServerConfig.test.ts@@ -2,6 +2,7 @@ import { McpServerId, type McpServer } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import {+ mcpServerNeedsBrowserAttachment,sameMcpServerConfigurations,toAcpMcpServers,toClaudeMcpServers,@@ -31,6 +32,27 @@ const servers: readonly McpServer[] = [];describe("provider MCP configuration", () => {+ it("declares browser attachment dependencies independently of connector count", () => {+ for (const transport of ["stdio", "url"] as const) {+ for (const hosted of [false, true]) {+ const base = servers.find((server) => server.transport === transport)!;+ for (const id of ["builtin-executor", "builtin-tinyfish"]) {+ const server = { ...base, id: McpServerId.make(id) };+ expect(mcpServerNeedsBrowserAttachment(server, hosted)).toBe(+ transport === "stdio" || hosted,+ );+ expect(mcpServerNeedsBrowserAttachment({ ...server, enabled: false }, hosted)).toBe(+ false,+ );+ }+ for (const id of ["builtin-exa", "composio-session", "raw-mcp", "builtin-computer-use"]) {+ expect(+ mcpServerNeedsBrowserAttachment({ ...base, id: McpServerId.make(id) }, hosted),+ ).toBe(false);+ }+ }+ }+ });it("converts filtered servers for ACP adapters", () => {expect(toAcpMcpServers(servers)).toEqual([{ type: "http", name: "Search", url: "https://mcp.example.com", headers: [] },diff --git a/apps/server/src/provider/McpServerConfig.ts b/apps/server/src/provider/McpServerConfig.tsindex a9743b3c4..63b56d74f 100644--- a/apps/server/src/provider/McpServerConfig.ts+++ b/apps/server/src/provider/McpServerConfig.ts@@ -2,6 +2,21 @@ import type { McpServer } from "@t3tools/contracts";import type * as EffectAcpSchema from "effect-acp/schema";const runtimeHeaders = new WeakMap<McpServer, Readonly<Record<string, string>>>();+const BROWSER_ATTACHMENT_CONNECTORS: ReadonlySet<string> = new Set([+ "builtin-executor",+ "builtin-tinyfish",+]);++export function mcpServerNeedsBrowserAttachment(+ server: McpServer,+ availableToHostedPlugins: boolean,+): boolean {+ return (+ server.enabled &&+ BROWSER_ATTACHMENT_CONNECTORS.has(String(server.id)) &&+ (server.transport === "stdio" || availableToHostedPlugins)+ );+}export function withMcpRuntimeHeaders<T extends McpServer>(server: T,diff --git a/apps/server/src/provider/botBrowser.test.ts b/apps/server/src/provider/botBrowser.test.tsindex 072d5487e..c05a67cd0 100644--- a/apps/server/src/provider/botBrowser.test.ts+++ b/apps/server/src/provider/botBrowser.test.ts@@ -202,6 +202,11 @@ describe("sandbox bot browser", () => {});try {+ expect(executeCommand).not.toHaveBeenCalled();+ expect(browserEndpoint).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ await executeTool(browser.tools.browser_snapshot, {});+ expect(executeCommand.mock.calls.filter(([command]) => command === "sh")).toHaveLength(1);await expect(browser.attachment()).resolves.toMatchObject({browserUrl: "https://9223-e2b.example",requestHeaders: { "e2b-traffic-access-token": "traffic-token" },