Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(composio): gate MCP apps behind feature flag (#4876)
LinYushencb68669c7393
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.tsindex f0f6aa613f..596ad82346 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -12,6 +12,7 @@import { z } from "zod";import type {Agent,+ AgentInvocationTarget,AgentTask,Attachment,ChatMessage,@@ -546,6 +547,18 @@ export const MemberWithUserSchema: z.ZodType<MemberWithUser> = z.object({export const MemberListSchema = z.array(MemberWithUserSchema).default([]);export const EMPTY_MEMBER_LIST: MemberWithUser[] = [];+const AgentInvocationTargetSchema: z.ZodType<AgentInvocationTarget> = z+ .object({+ target_type: z.enum(["workspace", "member", "team"]).catch("team"),+ target_id: z+ .string()+ .nullable()+ .optional()+ .catch(null)+ .transform((v) => v ?? null),+ })+ .loose();+// Agent schema is loose on every enum / structural field — the agent table is// where new modes/visibilities/statuses get added most often. We need only id,// name, avatar_url, and a couple of flags for the assignee picker + chat@@ -572,6 +585,8 @@ export const AgentSchema: z.ZodType<Agent> = z.object({visibility: z.string().catch("workspace") as unknown as z.ZodType<Agent["visibility"]>,+ permission_mode: z.enum(["private", "public_to"]).catch("private"),+ invocation_targets: z.array(AgentInvocationTargetSchema).default([]),status: z.string().catch("active") as unknown as z.ZodType<Agent["status"]>,max_concurrent_tasks: z.number().default(1),model: z.string().default(""),diff --git a/apps/mobile/lib/agent-schema.test.ts b/apps/mobile/lib/agent-schema.test.tsnew file mode 100644index 0000000000..fe1970ee78--- /dev/null+++ b/apps/mobile/lib/agent-schema.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { AgentSchema } from "../data/schemas";++describe("AgentSchema invocation permissions", () => {+ it("defaults missing invocation permissions to private access", () => {+ const parsed = AgentSchema.parse({ id: "agent-1" });++ expect(parsed.permission_mode).toBe("private");+ expect(parsed.invocation_targets).toEqual([]);+ });++ it("parses public invocation grants", () => {+ const parsed = AgentSchema.parse({+ id: "agent-1",+ permission_mode: "public_to",+ invocation_targets: [+ { target_type: "workspace" },+ { target_type: "member", target_id: "member-1" },+ ],+ });++ expect(parsed.permission_mode).toBe("public_to");+ expect(parsed.invocation_targets).toEqual([+ { target_type: "workspace", target_id: null },+ { target_type: "member", target_id: "member-1" },+ ]);+ });++ it("fails closed for unknown permission values", () => {+ const parsed = AgentSchema.parse({+ id: "agent-1",+ permission_mode: "future_mode",+ invocation_targets: [{ target_type: "future_target", target_id: 123 }],+ });++ expect(parsed.permission_mode).toBe("private");+ expect(parsed.invocation_targets).toEqual([+ { target_type: "team", target_id: null },+ ]);+ });+});diff --git a/apps/web/test/helpers.tsx b/apps/web/test/helpers.tsxindex 8ce70d4b54..d1358ea4ba 100644--- a/apps/web/test/helpers.tsx+++ b/apps/web/test/helpers.tsx@@ -65,6 +65,8 @@ export const mockAgents: Agent[] = [runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],max_concurrent_tasks: 3,model: "",owner_id: null,diff --git a/e2e/agent-mcp.spec.ts b/e2e/agent-mcp.spec.tsnew file mode 100644index 0000000000..75171f3a72--- /dev/null+++ b/e2e/agent-mcp.spec.ts@@ -0,0 +1,193 @@+import { test, expect, type Page } from "@playwright/test";+import { TestApiClient } from "./fixtures";+import { waitForPageText } from "./helpers";++// Stage 3.2 (MUL-3870): the creator-only MCP tab on the agent detail page.+//+// Auth + workspace bootstrap go through the real backend (same as every other+// spec), but the agent list and the Composio connection/catalog endpoints are+// mocked at the network boundary so the test runs without a configured+// COMPOSIO_API_KEY or a live runtime to bind an agent to. The PUT /api/agents+// write is intercepted so we can assert the exact allowlist body the toggle+// produces — the heart of the data contract — instead of depending on the+// backend persisting it.++const E2E_WORKER =+ process.env.TEST_PARALLEL_INDEX ?? process.env.TEST_WORKER_INDEX ?? "0";+const E2E_RUN_ID =+ process.env.E2E_RUN_ID ?? `${Date.now().toString(36)}-${process.pid.toString(36)}`;+const EMAIL = `e2e-mcp-${E2E_WORKER}-${E2E_RUN_ID}@multica.ai`;+const NAME = "E2E MCP User";++const AGENT_ID = "11111111-1111-4111-8111-111111111111";+const OTHER_USER_ID = "99999999-9999-4999-8999-999999999999";++interface SetupResult {+ slug: string;+ userId: string;+}++/** Log in via the real API, capture the authed user id, inject the token, and+ * return the workspace slug + user id so the test can mock an agent owned+ * (or not) by this exact user. */+async function loginCapturingUser(page: Page): Promise<SetupResult> {+ const api = new TestApiClient();+ const data = await api.login(EMAIL, NAME);+ const userId: string | undefined = data?.user?.id;+ if (!userId) throw new Error("login did not return a user id");+ const workspace = await api.ensureWorkspace(+ `E2E MCP WS ${E2E_WORKER}`,+ `e2e-mcp-${E2E_WORKER}-${E2E_RUN_ID}`,+ );+ await api.markUserOnboarded();+ const token = api.getToken();+ if (!token) throw new Error("login did not return a token");+ await page.addInitScript((t) => {+ localStorage.setItem("multica_token", t);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, token);+ return { slug: workspace.slug, userId };+}++function mockAgent(ownerId: string, workspaceId: string) {+ return {+ id: AGENT_ID,+ workspace_id: workspaceId,+ runtime_id: "22222222-2222-4222-8222-222222222222",+ name: "MCP Test Agent",+ description: "",+ instructions: "",+ avatar_url: null,+ runtime_mode: "local",+ runtime_config: {},+ custom_args: [],+ visibility: "workspace",+ status: "idle",+ max_concurrent_tasks: 1,+ model: "",+ owner_id: ownerId,+ skills: [],+ created_at: "2026-06-30T00:00:00Z",+ updated_at: "2026-06-30T00:00:00Z",+ archived_at: null,+ archived_by: null,+ composio_toolkit_allowlist: [],+ };+}++/** Mock the Composio catalog + the current user's active connections (Notion ++ * Slack), the agent list (owned by `ownerId`), and capture any PUT+ * /api/agents/<id> body. Returns a getter for the last captured allowlist. */+async function mockApis(page: Page, ownerId: string) {+ const captured: { allowlist?: unknown } = {};++ await page.route("**/api/integrations/composio/toolkits", (route) =>+ route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([+ { slug: "notion", name: "Notion", connectable: true },+ { slug: "slack", name: "Slack", connectable: true },+ ]),+ }),+ );++ await page.route("**/api/integrations/composio/connections", (route) =>+ route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([+ {+ id: "conn-notion",+ toolkit_slug: "notion",+ status: "active",+ connected_at: "2026-06-30T00:00:00Z",+ last_used_at: null,+ },+ {+ id: "conn-slack",+ toolkit_slug: "slack",+ status: "active",+ connected_at: "2026-06-30T00:00:00Z",+ last_used_at: null,+ },+ ]),+ }),+ );++ // One handler for both the list (GET, query string) and the write+ // (PUT /api/agents/<id>). Other agent sub-routes fall through.+ await page.route("**/api/agents**", (route) => {+ const req = route.request();+ const url = new URL(req.url());+ const workspaceId = url.searchParams.get("workspace_id") ?? "ws-mock";++ if (req.method() === "PUT" && url.pathname.endsWith(`/api/agents/${AGENT_ID}`)) {+ const body = req.postDataJSON?.() ?? {};+ captured.allowlist = body.composio_toolkit_allowlist;+ return route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ ...mockAgent(ownerId, workspaceId),+ composio_toolkit_allowlist: body.composio_toolkit_allowlist ?? [],+ }),+ });+ }++ if (req.method() === "GET" && url.pathname.endsWith("/api/agents")) {+ return route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([mockAgent(ownerId, workspaceId)]),+ });+ }++ return route.fallback();+ });++ return () => captured.allowlist;+}++test.describe("Agent MCP tab (creator-only)", () => {+ test("creator sees the MCP Apps tab and toggling a toolkit writes the allowlist", async ({+ page,+ }) => {+ const { slug, userId } = await loginCapturingUser(page);+ const getAllowlist = await mockApis(page, userId);++ await page.goto(`/${slug}/agents/${AGENT_ID}`, {+ waitUntil: "domcontentloaded",+ });+ await waitForPageText(page, "MCP Test Agent");++ // The creator-only tab entry is present and opens the connection list.+ const tab = page.getByRole("button", { name: "MCP Apps" });+ await expect(tab).toBeVisible({ timeout: 15000 });+ await tab.click();++ await expect(page.getByText("Notion")).toBeVisible();+ await expect(page.getByText("Slack")).toBeVisible();++ // Allow Notion → the PUT body carries exactly ["notion"].+ await page.getByLabel(/Allow Notion for this agent/i).click();+ await expect.poll(() => getAllowlist()).toEqual(["notion"]);+ });++ test("a non-creator viewer does not see the MCP Apps tab", async ({ page }) => {+ const { slug } = await loginCapturingUser(page);+ // Agent owned by someone else → the creator gate hides the tab entry.+ await mockApis(page, OTHER_USER_ID);++ await page.goto(`/${slug}/agents/${AGENT_ID}`, {+ waitUntil: "domcontentloaded",+ });+ await waitForPageText(page, "MCP Test Agent");++ // Other tabs render, but the creator-only MCP Apps entry must not.+ await expect(page.getByRole("button", { name: "Activity" })).toBeVisible({+ timeout: 15000,+ });+ await expect(page.getByRole("button", { name: "MCP Apps" })).toHaveCount(0);+ });+});diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.tsindex fc5535ab80..4bd8e233b8 100644--- a/e2e/settings.spec.ts+++ b/e2e/settings.spec.ts@@ -37,4 +37,83 @@ test.describe("Settings", () => {await expect(page.getByText("Workspace settings saved").first()).toBeVisible({ timeout: 5000 });await expect(page.getByRole("button", { name: new RegExp(originalName) }).first()).toBeVisible();});++ // Composio connect flow, fully mocked at the network boundary so it runs+ // without a configured COMPOSIO_API_KEY or a live Composio project. The+ // backend redirect is simulated by pointing the init endpoint's redirect_url+ // straight back at the settings page with ?connected=<slug> — exercising the+ // frontend's callback toast + connections refresh (MUL-3718) end to end.+ test("connecting a Composio toolkit shows a toast and refreshes the list", async ({+ page,+ }) => {+ const workspaceSlug = await loginAsDefault(page);+ const settingsUrl = `/${workspaceSlug}/settings?tab=integrations`;++ // Stateful: connections is empty until the (mocked) connect flow lands.+ let connected = false;++ await page.route("**/api/integrations/composio/toolkits", (route) =>+ route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([+ { slug: "notion", name: "Notion", connectable: true },+ ]),+ }),+ );++ await page.route("**/api/integrations/composio/connections", (route) => {+ if (route.request().method() !== "GET") return route.fallback();+ return route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify(+ connected+ ? [+ {+ id: "conn-notion-1",+ toolkit_slug: "notion",+ status: "active",+ connected_at: new Date().toISOString(),+ last_used_at: null,+ },+ ]+ : [],+ ),+ });+ });++ await page.route("**/api/integrations/composio/connect/init", (route) => {+ // Composio would 302 through its hosted consent and back to our callback,+ // which emits CallbackRedirect's slug-less shape:+ // `/settings?tab=integrations&connected=<slug>`. The web proxy's+ // legacy-route redirect then prepends the last workspace slug, landing on+ // the real settings route. Mock that exact backend shape (NOT the final+ // slugged URL) so the test exercises the same redirect path real users hit.+ connected = true;+ return route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ redirect_url: `/settings?tab=integrations&connected=notion`,+ }),+ });+ });++ await page.goto(settingsUrl, { waitUntil: "domcontentloaded" });+ await waitForPageText(page, "Composio");++ // Notion starts disconnected → click Connect.+ await page.getByRole("button", { name: /^Connect$/ }).first().click();++ // Success toast from the simulated callback redirect.+ await expect(page.getByText("Connected").first()).toBeVisible({ timeout: 10000 });++ // List refreshed without a manual reload: the Notion card now offers+ // Disconnect, and the one-shot ?connected param has been stripped.+ await expect(+ page.getByRole("button", { name: /Disconnect/ }).first(),+ ).toBeVisible({ timeout: 10000 });+ await expect(page).not.toHaveURL(/connected=notion/);+ });});diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.tsindex 2bec6ea7a3..ae85ac6ee7 100644--- a/packages/core/agents/derive-presence.test.ts+++ b/packages/core/agents/derive-presence.test.ts@@ -21,6 +21,8 @@ function makeAgent(overrides: Partial<Agent> = {}): Agent {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 6,model: "",diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.tsindex dccc9520a9..74044f66c0 100644--- a/packages/core/agents/index.ts+++ b/packages/core/agents/index.ts@@ -2,6 +2,7 @@ export * from "./types";export * from "./derive-presence";export * from "./queries";export * from "./use-agent-presence";+export * from "./use-update-agent-allowlist";export * from "./use-agent-activity";export * from "./use-workspace-presence-prefetch";export * from "./constants";diff --git a/packages/core/agents/use-agent-activity.test.ts b/packages/core/agents/use-agent-activity.test.tsindex 02a1cc2d12..acacaf3867 100644--- a/packages/core/agents/use-agent-activity.test.ts+++ b/packages/core/agents/use-agent-activity.test.ts@@ -40,6 +40,8 @@ const fullHistoryAgent: Agent = {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "",diff --git a/packages/core/agents/use-update-agent-allowlist.ts b/packages/core/agents/use-update-agent-allowlist.tsnew file mode 100644index 0000000000..be4ce9de1c--- /dev/null+++ b/packages/core/agents/use-update-agent-allowlist.ts@@ -0,0 +1,53 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import { useWorkspaceId } from "../hooks";+import type { Agent } from "../types";+import { workspaceKeys } from "../workspace/queries";++/**+ * Mutation hook for the creator-only MCP tab: writes an agent's Composio+ * toolkit allowlist via `PUT /api/agents/:id` ({ composio_toolkit_allowlist })+ * — no dedicated endpoint, the existing agent PATCH path carries it (MUL-3870).+ *+ * The hook is optimistic: it patches the matching agent in the cached+ * workspace list before the round-trip so the checkbox flips instantly, then+ * rolls back to the captured snapshot on error and always invalidates on+ * settle so the cache reconverges with the server's normalised slugs+ * (lowercase / trimmed / deduped). The server silently drops the write for+ * non-owners, which is why this is only wired into the owner-gated tab.+ *+ * Accepts the full desired allowlist (`string[]`) — callers compute the next+ * array (add / remove a slug) and pass it wholesale, matching the backend's+ * replace semantics. Pass `[]` to clear every toolkit.+ */+export function useUpdateAgentAllowlist(agentId: string) {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();++ return useMutation<Agent, Error, string[], { previous?: Agent[] }>({+ mutationFn: (allowlist) =>+ api.updateAgent(agentId, { composio_toolkit_allowlist: allowlist }),+ onMutate: async (allowlist) => {+ const queryKey = workspaceKeys.agents(wsId);+ // Cancel in-flight refetches so they can't clobber the optimistic write.+ await qc.cancelQueries({ queryKey });+ const previous = qc.getQueryData<Agent[]>(queryKey);+ qc.setQueryData<Agent[]>(queryKey, (old) =>+ old?.map((a) =>+ a.id === agentId+ ? ({ ...a, composio_toolkit_allowlist: allowlist } as Agent)+ : a,+ ),+ );+ return { previous };+ },+ onError: (_error, _allowlist, context) => {+ if (context?.previous) {+ qc.setQueryData(workspaceKeys.agents(wsId), context.previous);+ }+ },+ onSettled: () => {+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });+ },+ });+}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 4cac2ce370..b77c3f26dc 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -113,6 +113,9 @@ import type {BeginLarkInstallResponse,LarkInstallStatusResponse,RedeemLarkBindingTokenResponse,+ ComposioToolkit,+ ComposioConnection,+ ComposioConnectInitResponse,SlackInstallation,ListSlackInstallationsResponse,RegisterSlackBYORequest,@@ -2300,6 +2303,36 @@ export class ApiClient {});}+ // Composio integration (MUL-3720). All routes are user-scoped (a connection+ // belongs to a user, not a workspace), so none take a workspaceId.++ /** Full Composio toolkit catalog, each annotated with `connectable`+ * (whether the project has an enabled auth config for it). */+ async listComposioToolkits(): Promise<ComposioToolkit[]> {+ return this.fetch(`/api/integrations/composio/toolkits`);+ }++ /** The caller's active Composio connections. */+ async listComposioConnections(): Promise<ComposioConnection[]> {+ return this.fetch(`/api/integrations/composio/connections`);+ }++ /** Starts a hosted Composio connect flow for a toolkit and returns the+ * redirect URL the browser should be sent to. */+ async beginComposioConnect(toolkitSlug: string): Promise<ComposioConnectInitResponse> {+ return this.fetch(`/api/integrations/composio/connect/init`, {+ method: "POST",+ body: JSON.stringify({ toolkit_slug: toolkitSlug }),+ });+ }++ /** Disconnects a Composio connection the caller owns. */+ async deleteComposioConnection(connectionId: string): Promise<void> {+ await this.fetch(`/api/integrations/composio/connections/${connectionId}`, {+ method: "DELETE",+ });+ }+// Slack integration (MUL-3666)async listSlackInstallations(workspaceId: string): Promise<ListSlackInstallationsResponse> {return this.fetch(`/api/workspaces/${workspaceId}/slack/installations`);diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 0850502cda..213a99ec6f 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -178,6 +178,7 @@ describe("ApiClient schema fallback", () => {daemon_server_url: { wrong: "shape" },daemon_app_url: 123,workspace_creation_disabled: false,+ feature_flags: { composio_mcp_apps: true },});const client = new ApiClient("https://api.example.test");const config = await client.getConfig();@@ -185,6 +186,7 @@ describe("ApiClient schema fallback", () => {expect(config.allow_signup).toBe(true);expect(config.daemon_server_url).toBeUndefined();expect(config.daemon_app_url).toBeUndefined();+ expect(config.feature_flags?.composio_mcp_apps).toBe(true);});});diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex c7ac0dc932..12d275a381 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -450,6 +450,24 @@ describe("AppConfigSchema cdn_signed drift", () => {const parsed = AppConfigSchema.parse({ cdn_signed: true });expect(parsed.cdn_signed).toBe(true);});++ it("parses frontend feature flag decisions", () => {+ const parsed = AppConfigSchema.parse({+ feature_flags: {+ composio_mcp_apps: true,+ malformed_future_flag: "yes",+ },+ });+ expect(parsed.feature_flags).toEqual({+ composio_mcp_apps: true,+ malformed_future_flag: false,+ });+ });++ it("defaults malformed feature_flags to an empty object", () => {+ const parsed = AppConfigSchema.parse({ feature_flags: ["not", "an", "object"] });+ expect(parsed.feature_flags).toEqual({});+ });});describe("InboxUnreadSummarySchema", () => {diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 6792626363..3932adcc3d 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -43,6 +43,7 @@ export interface AppConfigResponse {daemon_server_url?: string;daemon_app_url?: string;workspace_creation_disabled?: boolean;+ feature_flags?: Record<string, boolean>;}// ---------------------------------------------------------------------------@@ -172,6 +173,14 @@ const BooleanWithDefaultSchema = (fallback: boolean) =>z.boolean().default(fallback),);+const FeatureFlagsSchema = z.preprocess(+ (value) =>+ value && typeof value === "object" && !Array.isArray(value)+ ? value+ : undefined,+ z.record(z.string(), BooleanWithDefaultSchema(false)).default({}),+);+export const AppConfigSchema = z.object({cdn_domain: z.string().default(""),cdn_signed: BooleanWithDefaultSchema(false),@@ -183,6 +192,7 @@ export const AppConfigSchema = z.object({daemon_server_url: OptionalStringSchema,daemon_app_url: OptionalStringSchema,workspace_creation_disabled: BooleanWithDefaultSchema(false).optional(),+ feature_flags: FeatureFlagsSchema,}).loose();export const EMPTY_APP_CONFIG: AppConfigResponse = {@@ -193,6 +203,7 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {daemon_server_url: "",daemon_app_url: "",workspace_creation_disabled: false,+ feature_flags: {},};export const CreateFeedbackResponseSchema = z.object({@@ -636,13 +647,45 @@ export const EMPTY_AGENT_TEMPLATE_DETAIL: AgentTemplate = {instructions: "",};+// ---------------------------------------------------------------------------+// Agent invocation permissions (MUL-3963)+//+// Full agent request/response payloads are NOT zod-validated today — the API+// client returns them typed directly (see client.ts `listAgents` /+// `getAgent` / `createAgent`), so there is no `AgentSchema` /+// `CreateAgentRequestSchema` / `UpdateAgentRequestSchema` to extend here.+// These lenient, exported fragments encode the new permission fields so any+// future agent schema — and the from-template minimal agent below — can reuse+// them. Per this file's convention the enum stays lenient (a future+// server-side value degrades to the strict default rather than failing the+// parse), and the target array defaults to `[]`.+// ---------------------------------------------------------------------------++export const AgentPermissionModeSchema = z+ .enum(["private", "public_to"])+ .catch("private");++export const AgentInvocationTargetSchema = z+ .object({+ target_type: z.string(),+ target_id: z.string().nullable().optional().transform((v) => v ?? null),+ })+ .loose();++export const AgentInvocationTargetsSchema = z+ .array(AgentInvocationTargetSchema)+ .default([]);+// `agent` is a full Agent record — schematising every field would duplicate// a 50-field interface and bit-rot fast. We keep it loose and require only// `id`, the one field the create-from-template flow consumes (used to// navigate to the new agent's detail page). Downstream code already-// optional-chains the rest.+// optional-chains the rest. The permission fields are parsed leniently when+// present so the from-template response carries a well-formed access shape.const MinimalAgentSchema = z.object({id: z.string(),+ permission_mode: AgentPermissionModeSchema.optional(),+ invocation_targets: AgentInvocationTargetsSchema.optional(),}).loose();export const CreateAgentFromTemplateResponseSchema = z.object({diff --git a/packages/core/composio/index.ts b/packages/core/composio/index.tsnew file mode 100644index 0000000000..85e675530e--- /dev/null+++ b/packages/core/composio/index.ts@@ -0,0 +1 @@+export { composioKeys, composioToolkitsOptions, composioConnectionsOptions } from "./queries";diff --git a/packages/core/composio/queries.ts b/packages/core/composio/queries.tsnew file mode 100644index 0000000000..f5ffea0fd8--- /dev/null+++ b/packages/core/composio/queries.ts@@ -0,0 +1,26 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";++/** Query-key namespace for Composio integration data. */+export const composioKeys = {+ all: ["composio"] as const,+ toolkits: () => [...composioKeys.all, "toolkits"] as const,+ connections: () => [...composioKeys.all, "connections"] as const,+};++/** The full Composio toolkit catalog (with per-toolkit `connectable`). The+ * catalog changes rarely, so a long staleTime avoids refetching it every time+ * the Settings tab mounts. */+export const composioToolkitsOptions = () =>+ queryOptions({+ queryKey: composioKeys.toolkits(),+ queryFn: () => api.listComposioToolkits(),+ staleTime: 5 * 60 * 1000,+ });++/** The current user's active Composio connections. */+export const composioConnectionsOptions = () =>+ queryOptions({+ queryKey: composioKeys.connections(),+ queryFn: () => api.listComposioConnections(),+ });diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsindex 005f3cbfa1..84427cb272 100644--- a/packages/core/config/index.ts+++ b/packages/core/config/index.ts@@ -15,6 +15,7 @@ interface ConfigState {// must be hidden. Defaults to false so unknown / older servers behave like// the managed-cloud case.workspaceCreationDisabled: boolean;+ featureFlags: Record<string, boolean>;setCdnConfig: (config: { cdnDomain: string; cdnSigned?: boolean }) => void;setAuthConfig: (config: {allowSignup: boolean;@@ -25,6 +26,7 @@ interface ConfigState {daemonServerUrl?: string;daemonAppUrl?: string;}) => void;+ setFeatureFlags: (flags?: Record<string, boolean>) => void;}export const configStore = createStore<ConfigState>((set) => ({@@ -35,11 +37,13 @@ export const configStore = createStore<ConfigState>((set) => ({daemonServerUrl: "",daemonAppUrl: "",workspaceCreationDisabled: false,+ featureFlags: {},setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),setAuthConfig: ({ allowSignup, googleClientId = "", workspaceCreationDisabled = false }) =>set({ allowSignup, googleClientId, workspaceCreationDisabled }),setDaemonConfig: ({ daemonServerUrl = "", daemonAppUrl = "" }) =>set({ daemonServerUrl, daemonAppUrl }),+ setFeatureFlags: (flags = {}) => set({ featureFlags: { ...flags } }),}));export function useConfigStore(): ConfigState;@@ -47,3 +51,17 @@ export function useConfigStore<T>(selector: (state: ConfigState) => T): T;export function useConfigStore<T>(selector?: (state: ConfigState) => T) {return useStore(configStore, selector as (state: ConfigState) => T);}++export function featureFlagEnabled(+ flags: Readonly<Record<string, boolean>> | undefined,+ key: string,+ defaultValue = false,+): boolean {+ return flags?.[key] ?? defaultValue;+}++export function useFeatureEnabled(key: string, defaultValue = false): boolean {+ return useConfigStore((state) =>+ featureFlagEnabled(state.featureFlags, key, defaultValue),+ );+}diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.tsindex a33576fe57..ac24ac189c 100644--- a/packages/core/feature-flags/index.ts+++ b/packages/core/feature-flags/index.ts@@ -17,6 +17,7 @@ export type {export { FeatureFlagService } from "./service";export { StaticProvider } from "./static-provider";export { ChainProvider } from "./chain-provider";+export { COMPOSIO_MCP_APPS_FLAG } from "./keys";export {FeatureFlagsProvider,useFeatureFlagService,diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.tsnew file mode 100644index 0000000000..1212264ec1--- /dev/null+++ b/packages/core/feature-flags/keys.ts@@ -0,0 +1 @@+export const COMPOSIO_MCP_APPS_FLAG = "composio_mcp_apps";diff --git a/packages/core/package.json b/packages/core/package.jsonindex 6b369b9dfc..714e7aca68 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -86,6 +86,8 @@"./github/queries": "./github/queries.ts","./lark": "./lark/index.ts","./lark/queries": "./lark/queries.ts",+ "./composio": "./composio/index.ts",+ "./composio/queries": "./composio/queries.ts","./slack": "./slack/index.ts","./slack/queries": "./slack/queries.ts","./feedback": "./feedback/index.ts",diff --git a/packages/core/permissions/rules.test.ts b/packages/core/permissions/rules.test.tsindex c6e8d3c8f9..8cd3c58aeb 100644--- a/packages/core/permissions/rules.test.ts+++ b/packages/core/permissions/rules.test.ts@@ -30,6 +30,8 @@ function makeAgent(overrides: Partial<Agent> = {}): Agent {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "default",@@ -141,38 +143,118 @@ describe("canEditAgent", () => {});describe("canAssignAgentToIssue", () => {- it("allows any member to assign workspace-visibility agents", () => {- const a = makeAgent({ visibility: "workspace", owner_id: ALICE });+ const workspaceTargets = [+ { target_type: "workspace" as const, target_id: null },+ ];++ it("allows any member to assign a public_to-workspace agent", () => {+ const a = makeAgent({+ visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: workspaceTargets,+ owner_id: ALICE,+ });expect(canAssignAgentToIssue(a, { userId: BOB, role: "member" }).allowed,).toBe(true);});- it("denies non-members from assigning workspace agents", () => {- const a = makeAgent({ visibility: "workspace", owner_id: ALICE });++ it("denies non-members from assigning a public_to-workspace agent", () => {+ const a = makeAgent({+ visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: workspaceTargets,+ owner_id: ALICE,+ });const d = canAssignAgentToIssue(a, { userId: BOB, role: null });expect(d.allowed).toBe(false);expect(d.reason).toBe("not_member");});+it("allows the owner to assign their private agent", () => {- const a = makeAgent({ visibility: "private", owner_id: ALICE });+ const a = makeAgent({+ visibility: "private",+ permission_mode: "private",+ invocation_targets: [],+ owner_id: ALICE,+ });expect(canAssignAgentToIssue(a, { userId: ALICE, role: "member" }).allowed,).toBe(true);});- it("allows workspace admin to assign someone else's private agent", () => {- const a = makeAgent({ visibility: "private", owner_id: ALICE });- expect(- canAssignAgentToIssue(a, { userId: BOB, role: "admin" }).allowed,- ).toBe(true);++ it("denies a workspace admin from assigning someone else's private agent (MUL-3963: admins no longer bypass)", () => {+ const a = makeAgent({+ visibility: "private",+ permission_mode: "private",+ invocation_targets: [],+ owner_id: ALICE,+ });+ const d = canAssignAgentToIssue(a, { userId: BOB, role: "admin" });+ expect(d.allowed).toBe(false);+ expect(d.reason).toBe("private_visibility");});+it("denies a plain member from assigning someone else's private agent", () => {- const a = makeAgent({ visibility: "private", owner_id: ALICE });+ const a = makeAgent({+ visibility: "private",+ permission_mode: "private",+ invocation_targets: [],+ owner_id: ALICE,+ });const d = canAssignAgentToIssue(a, { userId: BOB, role: "member" });expect(d.allowed).toBe(false);expect(d.reason).toBe("private_visibility");});++ it("allows a targeted member to assign a public_to-member agent", () => {+ const a = makeAgent({+ visibility: "private",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "member", target_id: BOB }],+ owner_id: ALICE,+ });+ expect(+ canAssignAgentToIssue(a, { userId: BOB, role: "member" }).allowed,+ ).toBe(true);+ });++ it("denies a non-targeted member from assigning a public_to-member agent", () => {+ const CAROL = "user-carol";+ const a = makeAgent({+ visibility: "private",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "member", target_id: BOB }],+ owner_id: ALICE,+ });+ const d = canAssignAgentToIssue(a, { userId: CAROL, role: "member" });+ expect(d.allowed).toBe(false);+ expect(d.reason).toBe("private_visibility");+ });++ it("treats a team target as inert — it never grants (v1 reserved)", () => {+ const a = makeAgent({+ visibility: "private",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "team", target_id: "team-1" }],+ owner_id: ALICE,+ });+ // Even an admin who belongs to the team gets no invocation grant.+ const d = canAssignAgentToIssue(a, { userId: BOB, role: "admin" });+ expect(d.allowed).toBe(false);+ expect(d.reason).toBe("private_visibility");+ // The owner still passes (owner always may invoke).+ expect(+ canAssignAgentToIssue(a, { userId: ALICE, role: "member" }).allowed,+ ).toBe(true);+ });+it("denies logged-out users", () => {- const a = makeAgent({ visibility: "workspace" });+ const a = makeAgent({+ visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: workspaceTargets,+ });const d = canAssignAgentToIssue(a, { userId: null, role: null });expect(d.allowed).toBe(false);expect(d.reason).toBe("not_authenticated");diff --git a/packages/core/permissions/rules.ts b/packages/core/permissions/rules.tsindex 68183ac2b3..55989efb00 100644--- a/packages/core/permissions/rules.ts+++ b/packages/core/permissions/rules.ts@@ -42,9 +42,17 @@ export function canEditAgent(agent: Agent, ctx: PermissionContext): Decision {}/**- * Assign an agent to an issue. Workspace-visibility agents are assignable by- * any workspace member; private agents are restricted to their owner plus- * workspace admins/owners. Mirrors `issue.go:1471-1490`.+ * Invoke an agent — assign it to an issue, @mention it, chat with it, or+ * otherwise trigger a run. Mirrors the MUL-3963 backend invocation gate,+ * which reads `permission_mode` + `invocation_targets` (NOT the derived+ * `visibility` field):+ *+ * - owner: always+ * - permission_mode "private": ONLY the owner. This is the key behavior+ * change — workspace admins NO LONGER bypass a private agent.+ * - permission_mode "public_to" + workspace target: any workspace member+ * - permission_mode "public_to" + member target: only the matching user+ * - team target: reserved, INERT in v1 (never grants)*/export function canAssignAgentToIssue(agent: Agent,@@ -53,18 +61,42 @@ export function canAssignAgentToIssue(if (ctx.userId === null) {return deny("not_authenticated", "Sign in to assign agents.");}- if (agent.visibility === "workspace") {++ // The owner may always invoke their own agent, regardless of mode.+ if (agent.owner_id !== null && agent.owner_id === ctx.userId) {+ return ALLOW;+ }++ if (agent.permission_mode === "private") {+ return deny(+ "private_visibility",+ "Personal agent — only the owner can assign work.",+ );+ }++ // permission_mode === "public_to": resolve the invocation grants. A+ // workspace grant opens invocation to any workspace member.+ const targets = agent.invocation_targets;+ if (targets.some((t) => t.target_type === "workspace")) {if (ctx.role === null) {return deny("not_member", "Join this workspace to assign agents.");}return ALLOW;}- // visibility === "private"- if (isAdminLike(ctx.role)) return ALLOW;- if (agent.owner_id !== null && agent.owner_id === ctx.userId) return ALLOW;++ // A member grant opens invocation to exactly the targeted user. Team+ // targets are reserved and INERT in v1 — they never grant.+ if (+ targets.some(+ (t) => t.target_type === "member" && t.target_id === ctx.userId,+ )+ ) {+ return ALLOW;+ }+return deny("private_visibility",- "Personal agent — only the owner and workspace admins can assign work.",+ "Restricted agent — you don't have access to assign work to it.",);}diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex 4269a7f673..e02ae93fac 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -67,6 +67,7 @@ export function AuthInitializer({daemonServerUrl: cfg.daemon_server_url,daemonAppUrl: cfg.daemon_app_url,});+ configStore.getState().setFeatureFlags(cfg.feature_flags);if (cfg.posthog_key) {initAnalytics({key: cfg.posthog_key,diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex adb1bf2f27..4d0b5f2eab 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -4,6 +4,47 @@ export type AgentRuntimeMode = "local" | "cloud";export type AgentVisibility = "workspace" | "private";+// ---------------------------------------------------------------------------+// Agent invocation permissions (MUL-3963)+//+// `permission_mode` + `invocation_targets` are the AUTHORITATIVE gate for who+// may TRIGGER / assign / @mention / chat an agent. The legacy `visibility`+// field REMAINS but is now DERIVED on the backend from these two: a+// `public_to` agent WITH a workspace target maps to `visibility: "workspace"`;+// everything else (private, or public_to scoped only to member/team targets)+// maps to `visibility: "private"`.+//+// Invocation semantics:+// - owner: always+// - permission_mode "private": ONLY the owner (workspace admins no longer+// bypass — the key behavior change vs the old visibility model)+// - permission_mode "public_to" + workspace target: any workspace member+// - permission_mode "public_to" + member target: only the matching user+// - team target: reserved, INERT in v1 (never grants)+// ---------------------------------------------------------------------------++export type AgentPermissionMode = "private" | "public_to";++/**+ * A single invocation grant on an agent. `target_id` is `null` for the+ * workspace target (the grant covers every workspace member); it carries the+ * member / team id for the scoped grants.+ */+export interface AgentInvocationTarget {+ target_type: "workspace" | "member" | "team";+ target_id: string | null;+}++/**+ * Wire shape for invocation targets on CREATE / UPDATE requests. For a+ * workspace target the client may omit `target_id` (the backend fills the+ * workspace id); member / team targets REQUIRE it.+ */+export interface AgentInvocationTargetInput {+ target_type: "workspace" | "member" | "team";+ target_id?: string;+}+// Runtime visibility is a separate axis from agent visibility — different// vocabulary because it gates a different action. "private" (default) means// only the runtime owner and workspace admins can bind agents to it;@@ -281,7 +322,36 @@ export interface Agent {* Older backends omit this field; treat `undefined` as false.*/mcp_config_redacted?: boolean;+ /**+ * The subset of Composio toolkit slugs this agent is allowed to mount as+ * MCP servers at task dispatch — but only when the run originator is the+ * agent owner (MUL-3869 / MUL-3721). `null`/`[]`/omitted all mean "no+ * overlay regardless of who triggers". Owner-only data: the server hands+ * it through verbatim to the owner and redacts it to `undefined` ++ * `composio_toolkit_allowlist_redacted=true` for everyone else (same+ * contract as `mcp_config`). Treat `undefined` as "unknown — assume none".+ */+ composio_toolkit_allowlist?: string[];+ /**+ * True when the server stripped `composio_toolkit_allowlist` from this+ * response because the caller is not the agent owner. The MCP tab is+ * creator-only so a redacted value should never reach the editor, but the+ * UI renders a "hidden" fallback defensively. Older backends omit this+ * field; treat `undefined` as false.+ */+ composio_toolkit_allowlist_redacted?: boolean;visibility: AgentVisibility;+ /**+ * Authoritative invocation permission mode (MUL-3963). The `visibility`+ * field above is DERIVED from this on the backend. The current backend+ * always returns this field.+ */+ permission_mode: AgentPermissionMode;+ /**+ * Invocation grants backing `permission_mode === "public_to"` (empty for a+ * private agent). See `AgentInvocationTarget`.+ */+ invocation_targets: AgentInvocationTarget[];status: AgentStatus;max_concurrent_tasks: number;model: string;@@ -327,6 +397,16 @@ export interface CreateAgentRequest {custom_env?: Record<string, string>;custom_args?: string[];visibility?: AgentVisibility;+ /**+ * Invocation permission mode (MUL-3963). When present it is authoritative;+ * when absent the backend maps the legacy `visibility` field+ * (private -> private, workspace -> public_to + workspace target). On+ * UPDATE, permission changes are OWNER-ONLY (the backend silently ignores+ * these fields from non-owner admins).+ */+ permission_mode?: AgentPermissionMode;+ /** Invocation grants — see `AgentInvocationTargetInput`. */+ invocation_targets?: AgentInvocationTargetInput[];max_concurrent_tasks?: number;model?: string;/** Optional runtime-native reasoning/effort token. See `Agent.thinking_level`. */@@ -377,6 +457,16 @@ export interface CreateAgentFromTemplateRequest {runtime_id: string;model?: string;visibility?: AgentVisibility;+ /**+ * Invocation permission mode (MUL-3963). When present it is authoritative;+ * when absent the backend maps the legacy `visibility` field+ * (private -> private, workspace -> public_to + workspace target). On+ * UPDATE, permission changes are OWNER-ONLY (the backend silently ignores+ * these fields from non-owner admins).+ */+ permission_mode?: AgentPermissionMode;+ /** Invocation grants — see `AgentInvocationTargetInput`. */+ invocation_targets?: AgentInvocationTargetInput[];max_concurrent_tasks?: number;/** Optional overrides applied to the template before creation. nil/omit* uses the template's own value. */@@ -432,7 +522,29 @@ export interface UpdateAgentRequest {* validate / translate it according to their own MCP integration*/mcp_config?: unknown | null;+ /**+ * Composio toolkit allowlist. Tri-state semantics, mirroring the backend+ * gate (MUL-3869):+ * - field omitted → no change+ * - `null` → clear the column (no MCP overlay for anyone)+ * - string[] → wholesale replace; the server lowercases / trims / dedupes+ * the slugs before persisting+ * Writes are silently dropped server-side unless the caller is the agent+ * owner, so the UI only ever exposes this field through the creator-only+ * MCP tab.+ */+ composio_toolkit_allowlist?: string[] | null;visibility?: AgentVisibility;+ /**+ * Invocation permission mode (MUL-3963). When present it is authoritative;+ * when absent the backend maps the legacy `visibility` field+ * (private -> private, workspace -> public_to + workspace target). On+ * UPDATE, permission changes are OWNER-ONLY (the backend silently ignores+ * these fields from non-owner admins).+ */+ permission_mode?: AgentPermissionMode;+ /** Invocation grants — see `AgentInvocationTargetInput`. */+ invocation_targets?: AgentInvocationTargetInput[];status?: AgentStatus;max_concurrent_tasks?: number;model?: string;diff --git a/packages/core/types/composio.ts b/packages/core/types/composio.tsnew file mode 100644index 0000000000..e9a63c355c--- /dev/null+++ b/packages/core/types/composio.ts@@ -0,0 +1,36 @@+/** A Composio toolkit as surfaced by GET /api/integrations/composio/toolkits.+ *+ * Wire shape mirrors `ComposioToolkitResponse` in+ * `server/internal/handler/integrations_composio.go`. New fields the backend+ * adds later MUST stay optional so older desktop builds keep parsing — see+ * CLAUDE.md → API Response Compatibility. */+export interface ComposioToolkit {+ slug: string;+ name: string;+ logo?: string;+ category?: string;+ /** Whether the project has an enabled auth config for this toolkit. When+ * false the UI must not offer a working Connect button — BeginConnect would+ * 400 with "toolkit not supported". */+ connectable: boolean;+}++/** A user's Composio connected account, as returned by+ * GET /api/integrations/composio/connections. Mirrors+ * `ComposioConnectionResponse` server-side. */+export interface ComposioConnection {+ id: string;+ toolkit_slug: string;+ /** Connection lifecycle state. `expired` surfaces a Reconnect affordance in+ * the UI; the backend only starts emitting it once Stage 4 webhook handling+ * lands (MUL-3719), but the client renders the branch ahead of that. */+ status: "active" | "expired" | "revoked" | string;+ connected_at: string;+ last_used_at?: string | null;+}++/** Response of POST /api/integrations/composio/connect/init — the hosted+ * Composio Connect Link the browser is redirected to. */+export interface ComposioConnectInitResponse {+ redirect_url: string;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 58d4aa6c04..1f19fd451e 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -4,6 +4,9 @@ export type {AgentStatus,AgentRuntimeMode,AgentVisibility,+ AgentPermissionMode,+ AgentInvocationTarget,+ AgentInvocationTargetInput,AgentTask,AgentActivityBucket,AgentRunCount,@@ -119,6 +122,11 @@ export type {LarkInstallStatusResponse,RedeemLarkBindingTokenResponse,} from "./lark";+export type {+ ComposioToolkit,+ ComposioConnection,+ ComposioConnectInitResponse,+} from "./composio";export type {SlackInstallation,ListSlackInstallationsResponse,diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsxindex 6655ba2eef..d7d4b06c0d 100644--- a/packages/views/agents/components/agent-detail-inspector.tsx+++ b/packages/views/agents/components/agent-detail-inspector.tsx@@ -45,7 +45,7 @@ import { ModelPicker } from "./inspector/model-picker";import { RuntimePicker } from "./inspector/runtime-picker";import { SkillAttach } from "./inspector/skill-attach";import { ThinkingPropRow } from "./inspector/thinking-prop-row";-import { VisibilityPicker } from "./inspector/visibility-picker";+import { AccessPicker } from "./inspector/access-picker";import { LarkAgentBindButton } from "../../settings/components/lark-tab";import { SlackAgentBindButton } from "../../settings/components/slack-tab";@@ -151,10 +151,22 @@ export function AgentDetailInspector({onChange={(v) => update({ thinking_level: v })}/><PropRow label={t(($) => $.inspector.prop_visibility)} interactive={false}>- <VisibilityPicker- value={agent.visibility}- canEdit={canEdit}- onChange={(v) => update({ visibility: v })}+ <AccessPicker+ permissionMode={agent.permission_mode}+ invocationTargets={agent.invocation_targets}+ visibility={agent.visibility}+ members={members}+ // Access is OWNER-ONLY (MUL-3963): a workspace admin can edit other+ // agent properties (canEdit) but NOT who may run the agent. Gate the+ // picker on ownership specifically so non-owners get the read-only+ // state instead of a control the backend would reject with 403.+ canEdit={+ currentUserId !== null && agent.owner_id === currentUserId+ }+ hasComposioAllowlist={+ (agent.composio_toolkit_allowlist ?? []).length > 0+ }+ onChange={(next) => update(next)}/></PropRow><PropRow label={t(($) => $.inspector.prop_concurrency)} interactive={false}>diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsxindex 86b2524226..934b8a0040 100644--- a/packages/views/agents/components/agent-detail-page.tsx+++ b/packages/views/agents/components/agent-detail-page.tsx@@ -301,6 +301,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {agent={agent}runtimes={runtimes}onUpdate={handleUpdate}+ currentUserId={currentUser?.id ?? null}navIntent={tabNavIntent}onNavIntentHandled={() => setTabNavIntent(null)}/>diff --git a/packages/views/agents/components/agent-overview-pane.test.tsx b/packages/views/agents/components/agent-overview-pane.test.tsxindex c72174bbe1..0a53497338 100644--- a/packages/views/agents/components/agent-overview-pane.test.tsx+++ b/packages/views/agents/components/agent-overview-pane.test.tsx@@ -78,6 +78,8 @@ const baseAgent: Agent = {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "",diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsxindex 14361028d0..06e8c93fca 100644--- a/packages/views/agents/components/agent-overview-pane.tsx+++ b/packages/views/agents/components/agent-overview-pane.tsx@@ -3,6 +3,7 @@import { useEffect, useMemo, useState } from "react";import {Activity,+ Blocks,BookOpenText,FileText,KeyRound,@@ -15,6 +16,8 @@ import {import { useQuery } from "@tanstack/react-query";import type { Agent, AgentRuntime } from "@multica/core/types";import { providerSupportsMcpConfig } from "@multica/core/agents";+import { useFeatureEnabled } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import { useWorkspaceId } from "@multica/core/hooks";import { larkInstallationsOptions } from "@multica/core/lark";import { slackInstallationsOptions } from "@multica/core/slack";@@ -34,6 +37,7 @@ import { SkillsTab } from "./tabs/skills-tab";import { EnvTab } from "./tabs/env-tab";import { CustomArgsTab } from "./tabs/custom-args-tab";import { McpConfigTab } from "./tabs/mcp-config-tab";+import { AgentMcpTab } from "./tabs/agent-mcp-tab";import { IntegrationsTab } from "./tabs/integrations-tab";import { RuntimeConfigTab } from "./tabs/runtime-config-tab";import { ActorIssuesPanel } from "../../common/actor-issues-panel";@@ -47,10 +51,11 @@ export type DetailTab =| "env"| "custom_args"| "mcp_config"+ | "composio_mcp"| "integrations"| "runtime_config";-const TAB_LABEL_KEY: Record<DetailTab, "activity" | "tasks" | "instructions" | "skills" | "environment" | "custom_args" | "mcp_config" | "integrations" | "runtime_config"> = {+const TAB_LABEL_KEY: Record<DetailTab, "activity" | "tasks" | "instructions" | "skills" | "environment" | "custom_args" | "mcp_config" | "composio_mcp" | "integrations" | "runtime_config"> = {activity: "activity",tasks: "tasks",instructions: "instructions",@@ -58,6 +63,7 @@ const TAB_LABEL_KEY: Record<DetailTab, "activity" | "tasks" | "instructions" | "env: "environment",custom_args: "custom_args",mcp_config: "mcp_config",+ composio_mcp: "composio_mcp",integrations: "integrations",runtime_config: "runtime_config",};@@ -73,6 +79,7 @@ const detailTabs: {{ id: "env", icon: KeyRound },{ id: "custom_args", icon: Terminal },{ id: "mcp_config", icon: Plug },+ { id: "composio_mcp", icon: Blocks },{ id: "integrations", icon: Webhook },{ id: "runtime_config", icon: Router },];@@ -81,6 +88,13 @@ interface AgentOverviewPaneProps {agent: Agent;runtimes: AgentRuntime[];onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;+ /**+ * The viewer's user id. Gates the creator-only MCP tab — the tab entry is+ * only rendered when the viewer is the agent owner (`agent.owner_id`),+ * matching the backend's owner-only read/write of the toolkit allowlist+ * (MUL-3870). `null` while auth is still loading hides the tab.+ */+ currentUserId?: string | null;/*** One-shot request from a sibling (the inspector's compact Lark status* row) to focus a specific tab. Routed through the same `requestTabChange`@@ -118,11 +132,13 @@ export function AgentOverviewPane({agent,runtimes,onUpdate,+ currentUserId,navIntent,onNavIntentHandled,}: AgentOverviewPaneProps) {const { t } = useT("agents");const wsId = useWorkspaceId();+ const composioMCPAppsEnabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);const [activeTab, setActiveTab] = useState<DetailTab>("activity");const [activeDirty, setActiveDirty] = useState(false);// Holds the destination when a tab change is intercepted by the dirty@@ -168,13 +184,23 @@ export function AgentOverviewPane({const visibleTabs = useMemo(() => {const showMcp = runtime ? providerSupportsMcpConfig(runtime.provider) : true;const showRuntimeConfig = runtime ? runtime.provider === "openclaw" : false;+ // The Composio MCP tab is creator-only: it edits the agent owner's own+ // toolkit allowlist, which the backend reads/writes for the owner alone+ // (redacted + write-dropped for everyone else — MUL-3870 / MUL-3869).+ // Hide the entry entirely for non-owners, and while auth is still loading.+ const showComposioMcp =+ composioMCPAppsEnabled &&+ !!currentUserId &&+ !!agent.owner_id &&+ agent.owner_id === currentUserId;return detailTabs.filter((tab) => {if (tab.id === "mcp_config") return showMcp;+ if (tab.id === "composio_mcp") return showComposioMcp;if (tab.id === "integrations") return integrationsConfigured;if (tab.id === "runtime_config") return showRuntimeConfig;return true;});- }, [runtime, integrationsConfigured]);+ }, [runtime, integrationsConfigured, composioMCPAppsEnabled, currentUserId, agent.owner_id]);// If the active tab disappears (e.g. user just switched the agent's// runtime to one that doesn't read mcp_config), fall back to Activity@@ -287,6 +313,11 @@ export function AgentOverviewPane({/></TabContent>)}+ {effectiveTab === "composio_mcp" && (+ <TabContent>+ <AgentMcpTab agent={agent} />+ </TabContent>+ )}{effectiveTab === "integrations" && (<TabContent><IntegrationsTab agent={agent} />diff --git a/packages/views/agents/components/create-agent-dialog.test.tsx b/packages/views/agents/components/create-agent-dialog.test.tsxindex 4117049063..8692a9d72c 100644--- a/packages/views/agents/components/create-agent-dialog.test.tsx+++ b/packages/views/agents/components/create-agent-dialog.test.tsx@@ -107,6 +107,8 @@ function makeTemplate(runtimeId: string): Agent {runtime_config: {},custom_args: [],visibility: "private",+ permission_mode: "private",+ invocation_targets: [],status: "idle",max_concurrent_tasks: 1,model: "",diff --git a/packages/views/agents/components/inspector/access-picker.test.tsx b/packages/views/agents/components/inspector/access-picker.test.tsxnew file mode 100644index 0000000000..f236f90db9--- /dev/null+++ b/packages/views/agents/components/inspector/access-picker.test.tsx@@ -0,0 +1,119 @@+// @vitest-environment jsdom++import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, cleanup } from "@testing-library/react";+import type {+ AgentInvocationTarget,+ MemberWithUser,+} from "@multica/core/types";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../../locales/en/common.json";+import enAgents from "../../../locales/en/agents.json";+import enIssues from "../../../locales/en/issues.json";++import { AccessPicker } from "./access-picker";++// ActorAvatar pulls workspace context (useWorkspaceId) that this unit test+// doesn't provide; stub it — the picker logic under test doesn't depend on it.+vi.mock("../../../common/actor-avatar", () => ({+ ActorAvatar: () => null,+}));++const TEST_RESOURCES = {+ en: { common: enCommon, agents: enAgents, issues: enIssues },+};++const MEMBERS = [+ { user_id: "u1", name: "Alice", role: "member" },+ { user_id: "u2", name: "Bob", role: "member" },+] as unknown as MemberWithUser[];++function renderPicker(+ props: Partial<React.ComponentProps<typeof AccessPicker>> = {},+) {+ const onChange = vi.fn();+ const utils = render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <AccessPicker+ permissionMode="private"+ invocationTargets={[]}+ visibility="private"+ members={MEMBERS}+ canEdit+ onChange={onChange}+ {...props}+ />+ </I18nProvider>,+ );+ return { ...utils, onChange };+}++describe("AccessPicker owner-only editing (MUL-3963)", () => {+ beforeEach(() => cleanup());+ afterEach(() => cleanup());++ it("renders a static, non-interactive read-only state for non-owners", () => {+ const targets: AgentInvocationTarget[] = [+ { target_type: "workspace", target_id: "ws-1" },+ ];+ renderPicker({+ canEdit: false,+ permissionMode: "public_to",+ invocationTargets: targets,+ visibility: "workspace",+ });++ // No clickable trigger — a non-owner can never open the picker.+ expect(screen.queryByRole("button")).toBeNull();+ // The current access is still shown…+ expect(screen.getByTestId("access-readonly")).toBeInTheDocument();+ expect(screen.getByText("Workspace")).toBeInTheDocument();+ // …with the owner-only explanation surfaced as the accessible label.+ expect(+ screen.getByLabelText(+ "Only the agent owner can change who can run this agent.",+ ),+ ).toBeInTheDocument();+ });++ it("renders an interactive trigger for the owner", () => {+ renderPicker({ canEdit: true });+ expect(screen.getByRole("button")).toBeInTheDocument();+ // Private is the default summary.+ expect(screen.getAllByText("Only me").length).toBeGreaterThan(0);+ });++ it("owner can pick a specific member, emitting a public_to member target", () => {+ const { onChange } = renderPicker({ canEdit: true });+ fireEvent.click(screen.getByRole("button"));+ // Checkbox order in the open popover: [0] workspace, [1] Alice, [2] Bob.+ const boxes = screen.getAllByRole("checkbox");+ fireEvent.click(boxes[1]!);+ expect(onChange).toHaveBeenCalledWith({+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "member", target_id: "u1" }],+ });+ });++ it("owner can stack workspace + a member (mixed, multi-select)", () => {+ // Start from a member target; toggling the workspace checkbox must ADD a+ // workspace target rather than replacing the member one.+ const { onChange } = renderPicker({+ canEdit: true,+ permissionMode: "public_to",+ invocationTargets: [{ target_type: "member", target_id: "u1" }],+ visibility: "private",+ });+ fireEvent.click(screen.getByRole("button"));+ const boxes = screen.getAllByRole("checkbox");+ // [0] is the "Everyone in workspace" toggle.+ fireEvent.click(boxes[0]!);+ expect(onChange).toHaveBeenCalledWith({+ permission_mode: "public_to",+ invocation_targets: [+ { target_type: "workspace" },+ { target_type: "member", target_id: "u1" },+ ],+ });+ });+});diff --git a/packages/views/agents/components/inspector/access-picker.tsx b/packages/views/agents/components/inspector/access-picker.tsxnew file mode 100644index 0000000000..48a465b9cf--- /dev/null+++ b/packages/views/agents/components/inspector/access-picker.tsx@@ -0,0 +1,320 @@+"use client";++import { useState } from "react";+import { Globe, Lock, Users, UsersRound } from "lucide-react";+import type {+ AgentInvocationTarget,+ AgentInvocationTargetInput,+ AgentPermissionMode,+ AgentVisibility,+ MemberWithUser,+} from "@multica/core/types";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import {+ Tooltip,+ TooltipTrigger,+ TooltipContent,+} from "@multica/ui/components/ui/tooltip";+import {+ PickerItem,+ PropertyPicker,+} from "../../../issues/components/pickers";+import { ActorAvatar } from "../../../common/actor-avatar";+import { useT } from "../../../i18n";+import { CHIP_CLASS } from "./chip";++/**+ * AccessPicker — the owner-facing control for MUL-3963 agent invocation+ * permissions. It reads/writes `permission_mode` + `invocation_targets`+ * (the authoritative gate) rather than the legacy derived `visibility` field.+ *+ * Access is EITHER Private (only me) OR Public with a STACKABLE, MIXED+ * allow-list: the owner can combine "Everyone in workspace" + any number of+ * specific members + (future) teams on the same agent. `canInvokeAgent` on+ * the backend admits an actor matching ANY target (OR), so the picker emits+ * the full union of every selected target and the whole set is replaced on+ * save.+ *+ * OWNER-ONLY (MUL-3963): access is the one agent property a workspace admin+ * may NOT change — only the agent owner decides who can run their agent, and+ * the backend rejects a non-owner permission change with 403. So `canEdit`+ * here must be passed as "is the viewer the agent owner", NOT the general+ * manage permission. When `canEdit` is false the control is a static,+ * non-interactive read-only display (current value + a lock affordance ++ * a tooltip explaining only the owner can change it), the same way GitHub /+ * Notion present a permission setting a viewer can see but not edit. There is+ * deliberately no clickable trigger in that state, so a non-owner can never+ * open a picker that the backend would only bounce back.+ */++export type AccessChange = {+ permission_mode: AgentPermissionMode;+ invocation_targets: AgentInvocationTargetInput[];+};++function hasWorkspaceTarget(targets: AgentInvocationTarget[]): boolean {+ return targets.some((t) => t.target_type === "workspace");+}++function selectedMemberIds(targets: AgentInvocationTarget[]): string[] {+ return targets+ .filter((t) => t.target_type === "member" && t.target_id !== null)+ .map((t) => t.target_id as string);+}++function selectedTeamIds(targets: AgentInvocationTarget[]): string[] {+ return targets+ .filter((t) => t.target_type === "team" && t.target_id !== null)+ .map((t) => t.target_id as string);+}++export function AccessPicker({+ permissionMode,+ invocationTargets,+ visibility: _visibility,+ members,+ canEdit = true,+ hasComposioAllowlist = false,+ onChange,+}: {+ permissionMode: AgentPermissionMode;+ invocationTargets: AgentInvocationTarget[];+ /**+ * Legacy derived visibility. No longer rendered directly (the read-only and+ * editable states both summarise permission_mode + targets), but kept in the+ * props so existing call sites compile unchanged.+ */+ visibility: AgentVisibility;+ members: MemberWithUser[];+ /**+ * True ONLY when the viewer is the agent owner (MUL-3963 access is+ * owner-only). When false, render the static read-only state.+ */+ canEdit?: boolean;+ /**+ * True when the agent already has a non-empty Composio toolkit allowlist.+ * Surfaces a one-time hint when the owner shares a previously-private agent,+ * since sharing widens who can drive those apps through the agent.+ */+ hasComposioAllowlist?: boolean;+ onChange: (next: AccessChange) => Promise<void> | void;+}) {+ const { t } = useT("agents");+ const [open, setOpen] = useState(false);+ const [showComposioHint, setShowComposioHint] = useState(false);++ // Display summary of the current access, shared by the read-only and+ // editable states so they never drift.+ const isPrivate = permissionMode === "private";+ const workspaceOn = !isPrivate && hasWorkspaceTarget(invocationTargets);+ const memberIds = selectedMemberIds(invocationTargets);+ // Team targets aren't editable in v1, but must be preserved across saves so+ // a batch-replace never silently drops them.+ const teamIds = selectedTeamIds(invocationTargets);+ const memberCount = memberIds.length;++ const SummaryIcon = isPrivate+ ? Lock+ : workspaceOn+ ? Globe+ : memberCount > 0+ ? Users+ : Globe;++ const summaryLabel = isPrivate+ ? t(($) => $.access.trigger_private)+ : workspaceOn+ ? t(($) => $.access.trigger_workspace)+ : memberCount > 0+ ? t(($) => $.access.trigger_members_count, { count: memberCount })+ : t(($) => $.access.trigger_members_empty);++ // Read-only state for non-owners: current value + lock + owner-only tooltip.+ // No interactive trigger is rendered, so the control can never be clicked+ // into a change the backend would reject.+ if (!canEdit) {+ const readOnlyMsg = t(($) => $.access.owner_only_readonly);+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <span+ className="inline-flex items-center gap-1 text-xs text-muted-foreground"+ aria-label={readOnlyMsg}+ data-testid="access-readonly"+ >+ <SummaryIcon className="h-3 w-3 shrink-0" />+ <span className="truncate">{summaryLabel}</span>+ <Lock className="h-3 w-3 shrink-0 opacity-60" />+ </span>+ }+ />+ <TooltipContent>{readOnlyMsg}</TooltipContent>+ </Tooltip>+ );+ }++ // Build the union of every selected target and emit it. An empty union+ // collapses to Private (owner-only), which is the intuitive "nothing shared"+ // state rather than a public_to with no grants.+ const emit = (next: {+ workspace: boolean;+ members: string[];+ teams: string[];+ }) => {+ const targets: AgentInvocationTargetInput[] = [];+ if (next.workspace) targets.push({ target_type: "workspace" });+ for (const id of next.members)+ targets.push({ target_type: "member", target_id: id });+ for (const id of next.teams)+ targets.push({ target_type: "team", target_id: id });+ if (targets.length === 0) {+ void onChange({ permission_mode: "private", invocation_targets: [] });+ return;+ }+ void onChange({+ permission_mode: "public_to",+ invocation_targets: targets,+ });+ };++ const maybeFlagComposio = (goingPublic: boolean) => {+ if (hasComposioAllowlist && isPrivate && goingPublic) {+ setShowComposioHint(true);+ }+ };++ const choosePrivate = () => {+ setShowComposioHint(false);+ void onChange({ permission_mode: "private", invocation_targets: [] });+ };++ const toggleWorkspace = (checked: boolean) => {+ maybeFlagComposio(checked);+ emit({ workspace: checked, members: memberIds, teams: teamIds });+ };++ const toggleMember = (userId: string, checked: boolean) => {+ maybeFlagComposio(checked);+ const next = new Set(memberIds);+ if (checked) next.add(userId);+ else next.delete(userId);+ emit({ workspace: workspaceOn, members: Array.from(next), teams: teamIds });+ };++ const tooltip = t(($) => $.access.tooltip);++ return (+ <PropertyPicker+ open={open}+ onOpenChange={(v) => {+ setOpen(v);+ if (v) setShowComposioHint(false);+ }}+ width="w-auto min-w-[15rem]"+ align="start"+ tooltip={tooltip}+ triggerRender={+ <button type="button" className={CHIP_CLASS} aria-label={tooltip} />+ }+ trigger={+ <>+ <SummaryIcon className="h-3 w-3 shrink-0 text-muted-foreground" />+ <span className="truncate">{summaryLabel}</span>+ </>+ }+ >+ {/* Private is the exclusive "not shared" choice: selecting it clears the+ whole allow-list. */}+ <PickerItem selected={isPrivate} onClick={choosePrivate}>+ <Lock className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <div className="text-left">+ <div className="font-medium">{t(($) => $.access.private_title)}</div>+ <div className="text-xs text-muted-foreground">+ {t(($) => $.access.private_desc)}+ </div>+ </div>+ </PickerItem>++ <div className="mt-1 border-t pt-1">+ <div className="px-2 pb-1 pt-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">+ {t(($) => $.access.public_group)}+ </div>++ {/* Everyone in workspace — stackable with member/team targets. */}+ <label className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-accent">+ <Checkbox+ checked={workspaceOn}+ onCheckedChange={(v) => toggleWorkspace(v === true)}+ aria-label={t(($) => $.access.workspace_title)}+ />+ <Globe className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1 text-left">+ <div className="font-medium">+ {t(($) => $.access.workspace_title)}+ </div>+ <div className="truncate text-xs text-muted-foreground">+ {t(($) => $.access.workspace_desc)}+ </div>+ </div>+ </label>+ </div>++ {/* Specific people — multi-select, stacks with the workspace toggle. */}+ <div className="mt-1 border-t pt-1">+ <div className="flex items-center gap-1.5 px-2 pb-1 pt-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">+ <Users className="h-3 w-3 shrink-0" />+ {t(($) => $.access.members_group)}+ </div>+ {members.length === 0 ? (+ <div className="px-2 py-2 text-xs text-muted-foreground">+ {t(($) => $.access.members_empty)}+ </div>+ ) : (+ <div className="max-h-48 overflow-y-auto">+ {members.map((m) => {+ const checked = memberIds.includes(m.user_id);+ return (+ <label+ key={m.user_id}+ className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-accent"+ >+ <Checkbox+ checked={checked}+ onCheckedChange={(v) => toggleMember(m.user_id, v === true)}+ aria-label={m.name}+ />+ <ActorAvatar+ actorType="member"+ actorId={m.user_id}+ size={18}+ />+ <span className="min-w-0 flex-1 truncate">{m.name}</span>+ </label>+ );+ })}+ </div>+ )}+ </div>++ {/* Team — reserved for a future release; shown disabled so the roadmap+ is visible without being actionable. The emit logic already carries+ team targets through so nothing is lost once teams ship. */}+ <div className="mt-1 border-t pt-1">+ <div className="flex items-center gap-1.5 px-2 py-1.5 text-sm text-muted-foreground opacity-60">+ <UsersRound className="h-3.5 w-3.5 shrink-0" />+ <span className="font-medium">{t(($) => $.access.team_title)}</span>+ <span className="rounded bg-muted px-1 py-0.5 text-[10px] font-medium">+ {t(($) => $.access.team_coming_soon)}+ </span>+ </div>+ </div>++ {showComposioHint && (+ <div className="mx-1 mt-1 rounded-md bg-amber-500/10 px-2 py-1.5 text-xs text-amber-700 dark:text-amber-400">+ {t(($) => $.access.composio_switch_hint)}+ </div>+ )}+ </PropertyPicker>+ );+}diff --git a/packages/views/agents/components/tabs/agent-mcp-tab.test.tsx b/packages/views/agents/components/tabs/agent-mcp-tab.test.tsxnew file mode 100644index 0000000000..a7ac875a4c--- /dev/null+++ b/packages/views/agents/components/tabs/agent-mcp-tab.test.tsx@@ -0,0 +1,237 @@+// @vitest-environment jsdom++import { describe, it, expect, vi, beforeEach } from "vitest";+import type { ReactNode } from "react";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import type { Agent } from "@multica/core/types";+import { configStore } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../../locales/en/common.json";+import enAgents from "../../../locales/en/agents.json";++// AgentMcpTab reads its connection list + toolkit catalog from two queries and+// writes through the useUpdateAgentAllowlist mutation. We stub all three at the+// module boundary so the tests assert the tab's own logic (which slugs are+// selectable, what the toggle computes, the empty/redacted branches) rather+// than the query/mutation plumbing, which is covered elsewhere.+const connectionsRef = vi.hoisted(() => ({+ current: [] as { toolkit_slug: string; status: string }[],+}));+const toolkitsRef = vi.hoisted(() => ({+ current: [] as { slug: string; name: string }[],+}));+const queryStateRef = vi.hoisted(() => ({+ isLoading: false,+ isError: false,+}));+const queryCallsRef = vi.hoisted(() => ({+ current: [] as { queryKey: unknown[]; enabled?: boolean }[],+}));+const mutateSpy = vi.hoisted(() => vi.fn());+const isPendingRef = vi.hoisted(() => ({ current: false }));++vi.mock("@tanstack/react-query", () => ({+ useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {+ queryCallsRef.current.push(opts);+ const key = JSON.stringify(opts.queryKey);+ if (queryStateRef.isLoading) return { data: undefined, isLoading: true, isError: false };+ if (queryStateRef.isError) return { data: undefined, isLoading: false, isError: true };+ if (key.includes("connections"))+ return { data: connectionsRef.current, isLoading: false, isError: false };+ if (key.includes("toolkits"))+ return { data: toolkitsRef.current, isLoading: false, isError: false };+ return { data: undefined, isLoading: false, isError: false };+ },+ queryOptions: <T,>(opts: T) => opts,+}));++vi.mock("@multica/core/composio", () => ({+ composioConnectionsOptions: () => ({ queryKey: ["composio", "connections"] }),+ composioToolkitsOptions: () => ({ queryKey: ["composio", "toolkits"] }),+}));++vi.mock("@multica/core/agents", () => ({+ useUpdateAgentAllowlist: () => ({+ mutate: mutateSpy,+ isPending: isPendingRef.current,+ }),+}));++vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ settings: () => "/ws/settings" }),+}));++vi.mock("../../../navigation", () => ({+ AppLink: ({ href, children }: { href: string; children: ReactNode }) => (+ <a href={href} data-testid="app-link">+ {children}+ </a>+ ),+}));++vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));++import { AgentMcpTab } from "./agent-mcp-tab";++const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };++const baseAgent: Agent = {+ id: "agent-1",+ workspace_id: "ws-1",+ runtime_id: "runtime-1",+ name: "Agent",+ description: "",+ instructions: "",+ avatar_url: null,+ runtime_mode: "local",+ runtime_config: {},+ custom_args: [],+ visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],+ status: "idle",+ max_concurrent_tasks: 1,+ model: "",+ owner_id: "user-1",+ skills: [],+ created_at: "2026-06-30T00:00:00Z",+ updated_at: "2026-06-30T00:00:00Z",+ archived_at: null,+ archived_by: null,+};++function renderTab(overrides: Partial<Agent> = {}) {+ const agent = { ...baseAgent, ...overrides };+ return render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <AgentMcpTab agent={agent} />+ </I18nProvider>,+ );+}++describe("AgentMcpTab", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ connectionsRef.current = [+ { toolkit_slug: "notion", status: "active" },+ { toolkit_slug: "slack", status: "active" },+ ];+ toolkitsRef.current = [+ { slug: "notion", name: "Notion" },+ { slug: "slack", name: "Slack" },+ ];+ queryStateRef.isLoading = false;+ queryStateRef.isError = false;+ isPendingRef.current = false;+ queryCallsRef.current = [];+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: true });+ });++ it("renders nothing and disables Composio queries when the feature flag is off", () => {+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: false });++ const { container } = renderTab({ composio_toolkit_allowlist: ["notion"] });++ expect(container.firstChild).toBeNull();+ expect(queryCallsRef.current).toHaveLength(2);+ expect(queryCallsRef.current.every((call) => call.enabled === false)).toBe(true);+ });++ it("lists active connections with checkbox state reflecting the allowlist", () => {+ renderTab({ composio_toolkit_allowlist: ["notion"] });++ const notion = screen.getByLabelText(/Allow Notion for this agent/i);+ const slack = screen.getByLabelText(/Allow Slack for this agent/i);+ expect(notion.getAttribute("aria-checked")).toBe("true");+ expect(slack.getAttribute("aria-checked")).toBe("false");+ });++ it("checking a toolkit writes the augmented allowlist via the mutation", async () => {+ const user = userEvent.setup();+ renderTab({ composio_toolkit_allowlist: [] });++ await user.click(screen.getByLabelText(/Allow Notion for this agent/i));++ expect(mutateSpy).toHaveBeenCalledTimes(1);+ expect(mutateSpy.mock.calls[0]?.[0]).toEqual(["notion"]);+ });++ it("unchecking a toolkit removes only that slug", async () => {+ const user = userEvent.setup();+ renderTab({ composio_toolkit_allowlist: ["notion", "slack"] });++ await user.click(screen.getByLabelText(/Allow Notion for this agent/i));++ expect(mutateSpy).toHaveBeenCalledTimes(1);+ expect(mutateSpy.mock.calls[0]?.[0]).toEqual(["slack"]);+ });++ it("only offers active connections — expired/revoked are not selectable", () => {+ connectionsRef.current = [+ { toolkit_slug: "notion", status: "active" },+ { toolkit_slug: "github", status: "expired" },+ ];+ renderTab({ composio_toolkit_allowlist: [] });++ expect(screen.getByLabelText(/Allow Notion for this agent/i)).toBeTruthy();+ expect(screen.queryByLabelText(/Allow github for this agent/i)).toBeNull();+ });++ it("shows an empty state with a Settings link when there are no active connections", () => {+ connectionsRef.current = [];+ renderTab({ composio_toolkit_allowlist: [] });++ expect(screen.getByText(/No connected apps yet/i)).toBeTruthy();+ const link = screen.getByTestId("app-link");+ expect(link.getAttribute("href")).toBe("/ws/settings?tab=integrations");+ });++ it("renders a defensive hidden state when the allowlist is redacted", () => {+ renderTab({ composio_toolkit_allowlist_redacted: true });++ expect(screen.getByText(/hidden from your view/i)).toBeTruthy();+ expect(screen.queryByLabelText(/Allow Notion for this agent/i)).toBeNull();+ });++ it("shows the strong workspace warning for a public_to-workspace agent", () => {+ renderTab({+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],+ composio_toolkit_allowlist: [],+ });++ expect(+ screen.getByText(/any workspace member may use these Composio apps/i),+ ).toBeTruthy();+ });++ it("shows the generic shared warning for a public_to-member agent", () => {+ renderTab({+ visibility: "private",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "member", target_id: "user-2" }],+ composio_toolkit_allowlist: [],+ });++ expect(screen.getByText(/This agent is shared\./i)).toBeTruthy();+ expect(+ screen.queryByText(/any workspace member may use these Composio apps/i),+ ).toBeNull();+ });++ it("shows no sharing warning for a private agent", () => {+ renderTab({+ visibility: "private",+ permission_mode: "private",+ invocation_targets: [],+ composio_toolkit_allowlist: ["notion"],+ });++ expect(screen.queryByText(/This agent is shared\./i)).toBeNull();+ expect(+ screen.queryByText(/any workspace member may use these Composio apps/i),+ ).toBeNull();+ });+});diff --git a/packages/views/agents/components/tabs/agent-mcp-tab.tsx b/packages/views/agents/components/tabs/agent-mcp-tab.tsxnew file mode 100644index 0000000000..ccb4622867--- /dev/null+++ b/packages/views/agents/components/tabs/agent-mcp-tab.tsx@@ -0,0 +1,210 @@+"use client";++import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";+import { AlertTriangle, Loader2, Lock, Plug } from "lucide-react";+import { toast } from "sonner";+import type { Agent, ComposioToolkit } from "@multica/core/types";+import { useUpdateAgentAllowlist } from "@multica/core/agents";+import { useFeatureEnabled } from "@multica/core/config";+import {+ composioConnectionsOptions,+ composioToolkitsOptions,+} from "@multica/core/composio";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";+import { useWorkspacePaths } from "@multica/core/paths";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { ComposioToolkitLogo } from "../../../common/composio-toolkit-logo";+import { AppLink } from "../../../navigation";+import { useT } from "../../../i18n";++/**+ * Creator-only MCP tab on the agent detail page (MUL-3870). Lets the agent+ * owner pick which of *their own* active Composio connections this agent may+ * mount as MCP servers — the selection is written to+ * `agent.composio_toolkit_allowlist`. At dispatch the overlay is mounted for+ * ANY run that passes the agent's invocation permission and always uses the+ * agent OWNER's Composio connection (MUL-3963) — it is no longer gated on the+ * run originator being the owner. That is why sharing the agent (public_to)+ * surfaces the warning banner below: everyone who can invoke the agent can+ * drive these apps through it.+ *+ * Visibility is enforced by the parent (the tab entry isn't rendered unless+ * `agent.owner_id === viewer.id`), so this component assumes the owner. It+ * still renders a defensive "hidden" state if the server redacted the+ * allowlist, and reads the checked state straight from the agent prop so the+ * optimistic cache write in `useUpdateAgentAllowlist` flips each box+ * instantly.+ */+export function AgentMcpTab({ agent }: { agent: Agent }) {+ const { t } = useT("agents");+ const paths = useWorkspacePaths();+ const composioEnabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);+ const updateAllowlist = useUpdateAgentAllowlist(agent.id);++ const connectionsQuery = useQuery({+ ...composioConnectionsOptions(),+ enabled: composioEnabled,+ });+ const toolkitsQuery = useQuery({+ ...composioToolkitsOptions(),+ enabled: composioEnabled,+ });++ // Toolkit metadata (name / logo) keyed by slug, so each connection row can+ // render a friendly label instead of the bare slug. The catalog is a+ // best-effort enrichment — a missing entry just falls back to the slug.+ const toolkitBySlug = useMemo(() => {+ const m = new Map<string, ComposioToolkit>();+ for (const tk of toolkitsQuery.data ?? []) m.set(tk.slug, tk);+ return m;+ }, [toolkitsQuery.data]);++ // Only ACTIVE connections are selectable — an expired / revoked connection+ // can't back an MCP mount, so offering its checkbox would be a dead toggle.+ // Dedupe by slug (a user could in theory hold two rows for one toolkit).+ const activeSlugs = useMemo(() => {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const c of connectionsQuery.data ?? []) {+ if (c.status !== "active") continue;+ if (seen.has(c.toolkit_slug)) continue;+ seen.add(c.toolkit_slug);+ out.push(c.toolkit_slug);+ }+ return out;+ }, [connectionsQuery.data]);++ const allowlist = useMemo(+ () => agent.composio_toolkit_allowlist ?? [],+ [agent.composio_toolkit_allowlist],+ );++ const settingsHref = `${paths.settings()}?tab=integrations`;++ // Composio access warning (MUL-3963). Once an agent is shared, anyone who+ // can invoke it can drive the Composio apps enabled here on the owner's+ // behalf — so surface a heads-up whenever the agent is not private and+ // there's something to enable (or already enabled). Public-to-workspace+ // gets the stronger copy because it opens the apps to every member.+ const isPrivate = agent.permission_mode === "private";+ const isWorkspacePublic =+ agent.permission_mode === "public_to" &&+ agent.invocation_targets.some((target) => target.target_type === "workspace");+ const showSharedWarning =+ !isPrivate && (allowlist.length > 0 || activeSlugs.length > 0);++ if (!composioEnabled) {+ return null;+ }++ const handleToggle = (slug: string, checked: boolean) => {+ const set = new Set(allowlist);+ if (checked) set.add(slug);+ else set.delete(slug);+ const next = Array.from(set);+ updateAllowlist.mutate(next, {+ onError: () => toast.error(t(($) => $.tab_body.composio_mcp.save_failed_toast)),+ });+ };++ // Defensive: the tab is owner-gated, so a redacted allowlist should never+ // reach here. If it somehow does (stale cache, future fan-out), show the+ // same "configured but hidden" affordance as the MCP config tab rather than+ // an empty editor that a Save could clobber.+ if (agent.composio_toolkit_allowlist_redacted === true) {+ return (+ <div className="space-y-3">+ <p className="flex items-center gap-2 text-sm font-medium">+ <Lock className="h-3.5 w-3.5 text-muted-foreground" />+ {t(($) => $.tab_body.composio_mcp.redacted_title)}+ </p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.tab_body.composio_mcp.redacted_hint)}+ </p>+ </div>+ );+ }++ return (+ <div className="space-y-4">+ <p className="text-xs text-muted-foreground">+ {t(($) => $.tab_body.composio_mcp.subtitle)}+ </p>++ {showSharedWarning && (+ <div+ role="alert"+ className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-400"+ >+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ <span>+ {isWorkspacePublic+ ? t(($) => $.tab_body.composio_mcp.workspace_warning)+ : t(($) => $.tab_body.composio_mcp.shared_warning)}+ </span>+ </div>+ )}++ {connectionsQuery.isLoading ? (+ <p className="text-sm text-muted-foreground">+ {t(($) => $.tab_body.composio_mcp.loading)}+ </p>+ ) : connectionsQuery.isError ? (+ <p className="text-sm text-destructive">+ {t(($) => $.tab_body.composio_mcp.load_failed)}+ </p>+ ) : activeSlugs.length === 0 ? (+ <div className="space-y-2 rounded-lg border border-dashed p-6 text-center">+ <p className="text-sm font-medium">+ {t(($) => $.tab_body.composio_mcp.empty_title)}+ </p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.tab_body.composio_mcp.empty_hint)}+ </p>+ <AppLink+ href={settingsHref}+ className="inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline"+ >+ <Plug className="h-3 w-3" />+ {t(($) => $.tab_body.composio_mcp.empty_link_to_settings)}+ </AppLink>+ </div>+ ) : (+ <ul className="divide-y rounded-lg border">+ {activeSlugs.map((slug) => {+ const tk = toolkitBySlug.get(slug);+ const name = tk?.name || slug;+ const checked = allowlist.includes(slug);+ return (+ <li key={slug} className="flex items-center gap-3 p-3">+ <ComposioToolkitLogo slug={slug} name={name} fallbackLogo={tk?.logo} />+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium">{name}</p>+ <p className="truncate text-[10px] uppercase tracking-wide text-emerald-600">+ {t(($) => $.tab_body.composio_mcp.connected)}+ </p>+ </div>+ <Checkbox+ checked={checked}+ disabled={updateAllowlist.isPending}+ onCheckedChange={(value) => handleToggle(slug, value === true)}+ aria-label={t(($) => $.tab_body.composio_mcp.toggle_aria, {+ toolkit: name,+ })}+ />+ </li>+ );+ })}+ </ul>+ )}++ {updateAllowlist.isPending && (+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin" />+ {t(($) => $.tab_body.composio_mcp.saving)}+ </p>+ )}+ </div>+ );+}diff --git a/packages/views/agents/components/tabs/integrations-tab.test.tsx b/packages/views/agents/components/tabs/integrations-tab.test.tsxindex 17f4624870..3386baa4b1 100644--- a/packages/views/agents/components/tabs/integrations-tab.test.tsx+++ b/packages/views/agents/components/tabs/integrations-tab.test.tsx@@ -102,6 +102,8 @@ const agent: Agent = {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "",diff --git a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx b/packages/views/agents/components/tabs/mcp-config-tab.test.tsxindex 4aaa03131d..6aa3f91c37 100644--- a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx+++ b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx@@ -31,6 +31,8 @@ const baseAgent: Agent = {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "",diff --git a/packages/views/agents/components/tabs/skills-tab.test.tsx b/packages/views/agents/components/tabs/skills-tab.test.tsxindex 7e3eda8997..0000663abe 100644--- a/packages/views/agents/components/tabs/skills-tab.test.tsx+++ b/packages/views/agents/components/tabs/skills-tab.test.tsx@@ -44,6 +44,8 @@ const agent: Agent = {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "",diff --git a/packages/views/chat/components/chat-window.agent-dropdown.test.tsx b/packages/views/chat/components/chat-window.agent-dropdown.test.tsxindex 8e2c495ddd..30935b4d3c 100644--- a/packages/views/chat/components/chat-window.agent-dropdown.test.tsx+++ b/packages/views/chat/components/chat-window.agent-dropdown.test.tsx@@ -26,6 +26,8 @@ function makeAgent(overrides: Partial<Agent> & Pick<Agent, "id" | "name" | "owneruntime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "sonnet",diff --git a/packages/views/common/composio-toolkit-logo.test.tsx b/packages/views/common/composio-toolkit-logo.test.tsxnew file mode 100644index 0000000000..c9f2cbcf71--- /dev/null+++ b/packages/views/common/composio-toolkit-logo.test.tsx@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { fireEvent, render } from "@testing-library/react";+import { ComposioToolkitLogo, composioToolkitLogoUrl } from "./composio-toolkit-logo";++describe("ComposioToolkitLogo", () => {+ it("builds Composio logo URLs from toolkit slugs", () => {+ expect(composioToolkitLogoUrl(" GitHub ")).toBe("https://logos.composio.dev/api/github");+ expect(composioToolkitLogoUrl("vercel", "dark")).toBe(+ "https://logos.composio.dev/api/vercel?theme=dark",+ );+ });++ it("uses backend logo for light mode and Composio dark logo for dark mode", () => {+ const { container } = render(+ <ComposioToolkitLogo+ slug="slack"+ name="Slack"+ fallbackLogo="https://cdn.example/slack.svg"+ />,+ );++ const images = Array.from(container.querySelectorAll("img"));+ expect(images).toHaveLength(2);+ expect(images[0]?.getAttribute("src")).toBe("https://cdn.example/slack.svg");+ expect(images[1]?.getAttribute("src")).toBe(+ "https://logos.composio.dev/api/slack?theme=dark",+ );+ });++ it("keeps the dark logo when the hidden light logo fails", () => {+ const { container } = render(<ComposioToolkitLogo slug="notion" name="Notion" />);++ const light = container.querySelector("img.dark\\:hidden");+ expect(light?.getAttribute("src")).toBe("https://logos.composio.dev/api/notion");++ fireEvent.error(light!);++ const dark = Array.from(container.querySelectorAll("img")).find((img) =>+ img.className.includes("dark:block"),+ );+ expect(dark?.getAttribute("src")).toBe(+ "https://logos.composio.dev/api/notion?theme=dark",+ );+ });+});diff --git a/packages/views/common/composio-toolkit-logo.tsx b/packages/views/common/composio-toolkit-logo.tsxnew file mode 100644index 0000000000..045285206a--- /dev/null+++ b/packages/views/common/composio-toolkit-logo.tsx@@ -0,0 +1,84 @@+"use client";++import { useEffect, useState } from "react";+import { cn } from "@multica/ui/lib/utils";++const COMPOSIO_LOGO_BASE_URL = "https://logos.composio.dev/api";++export function composioToolkitLogoUrl(slug: string, theme?: "dark") {+ const normalized = slug.trim().toLowerCase();+ if (!normalized) return "";+ const base = `${COMPOSIO_LOGO_BASE_URL}/${encodeURIComponent(normalized)}`;+ return theme === "dark" ? `${base}?theme=dark` : base;+}++function uniqueNonEmpty(values: Array<string | null | undefined>) {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const value of values) {+ const normalized = value?.trim();+ if (!normalized || seen.has(normalized)) continue;+ seen.add(normalized);+ out.push(normalized);+ }+ return out;+}++export function ComposioToolkitLogo({+ slug,+ name,+ fallbackLogo,+ className,+}: {+ slug: string;+ name?: string;+ fallbackLogo?: string | null;+ className?: string;+}) {+ const label = name || slug;+ const initial = label.charAt(0).toUpperCase();+ const dynamicLightLogo = composioToolkitLogoUrl(slug);+ const dynamicDarkLogo = composioToolkitLogoUrl(slug, "dark");+ const lightSources = uniqueNonEmpty([fallbackLogo, dynamicLightLogo]);+ const darkSources = uniqueNonEmpty([dynamicDarkLogo, fallbackLogo, dynamicLightLogo]);+ const [failedLightSources, setFailedLightSources] = useState(0);+ const [failedDarkSources, setFailedDarkSources] = useState(0);++ useEffect(() => {+ setFailedLightSources(0);+ setFailedDarkSources(0);+ }, [slug, fallbackLogo]);++ const imgClassName = cn("h-8 w-8 shrink-0 rounded bg-muted object-contain", className);+ const fallbackClassName = cn(+ "h-8 w-8 shrink-0 items-center justify-center rounded bg-muted text-xs font-semibold text-muted-foreground",+ className,+ );+ const lightSrc = lightSources[failedLightSources];+ const darkSrc = darkSources[failedDarkSources];++ return (+ <>+ {lightSrc ? (+ <img+ src={lightSrc}+ alt=""+ className={cn(imgClassName, "dark:hidden")}+ onError={() => setFailedLightSources((n) => n + 1)}+ />+ ) : (+ <div className={cn(fallbackClassName, "flex dark:hidden")}>{initial}</div>+ )}+ {darkSrc ? (+ <img+ src={darkSrc}+ alt=""+ className={cn(imgClassName, "hidden dark:block")}+ onError={() => setFailedDarkSources((n) => n + 1)}+ />+ ) : (+ <div className={cn(fallbackClassName, "hidden dark:flex")}>{initial}</div>+ )}+ </>+ );+}diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsxindex b4f100d0b6..83ad7935a5 100644--- a/packages/views/editor/extensions/mention-suggestion.test.tsx+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx@@ -64,6 +64,11 @@ function fakeQc(data: {archived_at: string | null;visibility?: "workspace" | "private";owner_id?: string | null;+ permission_mode?: "private" | "public_to";+ invocation_targets?: Array<{+ target_type: "workspace" | "member" | "team";+ target_id: string | null;+ }>;}>;squads?: Array<{id: string;@@ -74,7 +79,22 @@ function fakeQc(data: {}): QueryClient {const map = new Map<string, unknown>();map.set(JSON.stringify(workspaceKeys.members("ws-1")), data.members ?? []);- map.set(JSON.stringify(workspaceKeys.agents("ws-1")), data.agents ?? []);+ // MUL-3963: the mention filter runs through canAssignAgentToIssue, which+ // reads permission_mode + invocation_targets (not the legacy `visibility`).+ // Fixtures still express intent via `visibility`, so derive the permission+ // fields from it here (public_to + workspace target for "workspace";+ // private + no targets otherwise) unless a fixture sets them explicitly.+ const agentsWithPermissions = (data.agents ?? []).map((a) => ({+ ...a,+ permission_mode:+ a.permission_mode ?? (a.visibility === "private" ? "private" : "public_to"),+ invocation_targets:+ a.invocation_targets ??+ (a.visibility === "private"+ ? []+ : [{ target_type: "workspace" as const, target_id: null }]),+ }));+ map.set(JSON.stringify(workspaceKeys.agents("ws-1")), agentsWithPermissions);map.set(JSON.stringify(workspaceKeys.squads("ws-1")), data.squads ?? []);const byStatus: ListIssuesCache["byStatus"] = {};for (const status of PAGINATED_STATUSES) {@@ -367,10 +387,11 @@ describe("createMentionSuggestion", () => {expect(items.some((i) => i.type === "agent" && i.label === "Atlas")).toBe(false);});- it("shows everyone's personal agents to a workspace admin", () => {+ it("hides another owner's personal agent from a workspace admin (MUL-3963)", () => {// Role lives in the member fixture, not in authState — promoting Alice- // to admin here is enough to flip the gate. Backend gate allows admins- // to assign anyone's personal agent, so the @mention list mirrors that.+ // to admin here exercises the gate. MUL-3963 removed the admin bypass:+ // a private agent is invocable only by its owner, so the @mention list+ // must NOT surface Bob's personal agent to admin Alice.const qc = fakeQc({members: [{ user_id: "u1", name: "Alice", role: "admin" },@@ -392,7 +413,7 @@ describe("createMentionSuggestion", () => {const result = config.items!(itemArgs("a"));const items = result as MentionItem[];- expect(items.some((i) => i.type === "agent" && i.label === "Atlas")).toBe(true);+ expect(items.some((i) => i.type === "agent" && i.label === "Atlas")).toBe(false);});it("includes cached issues in the synchronous response", () => {diff --git a/packages/views/editor/extensions/slash-command-suggestion.test.tsx b/packages/views/editor/extensions/slash-command-suggestion.test.tsxindex 162bc49757..5726d95fb7 100644--- a/packages/views/editor/extensions/slash-command-suggestion.test.tsx+++ b/packages/views/editor/extensions/slash-command-suggestion.test.tsx@@ -59,6 +59,8 @@ function agent(overrides: Partial<Agent>): Agent {runtime_config: {},custom_args: [],visibility: "workspace",+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],status: "idle",max_concurrent_tasks: 1,model: "",@@ -232,6 +234,8 @@ describe("slash command suggestion items", () => {agent({id: "private-agent",visibility: "private",+ permission_mode: "private",+ invocation_targets: [],owner_id: "u2",skills: [{ id: "private-skill", name: "secret", description: "" }],}),diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex c2c11b578c..6e6558f66f 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -218,6 +218,7 @@"environment": "Environment","custom_args": "Custom Args","mcp_config": "MCP",+ "composio_mcp": "MCP Apps","integrations": "Integrations","runtime_config": "Routing","discard_dialog_title": "Discard unsaved changes?",@@ -331,6 +332,22 @@"redacted_title": "Configured — hidden from your view","redacted_hint": "Only the agent owner or a workspace admin can read this config."},+ "composio_mcp": {+ "subtitle": "Check a toolkit to let this agent mount it as an MCP server — but only when you (its creator) are the one who triggered the run, directly or down a sub-agent chain.",+ "loading": "Loading your connections…",+ "load_failed": "Couldn't load your connected apps. Try again shortly.",+ "empty_title": "No connected apps yet",+ "empty_hint": "You haven't connected any third-party services. Authorize one first, then come back here to allow it.",+ "empty_link_to_settings": "Connect one in Settings → Integrations",+ "connected": "Connected",+ "toggle_aria": "Allow {{toolkit}} for this agent",+ "saving": "Saving…",+ "save_failed_toast": "Couldn't save — please try again",+ "redacted_title": "Configured — hidden from your view",+ "redacted_hint": "Only the agent's creator can view or change which apps it may use.",+ "shared_warning": "This agent is shared. People who can run this agent may use the Composio apps you enable here. Use Private or narrow the access list if these apps expose sensitive data.",+ "workspace_warning": "Public to workspace: any workspace member may use these Composio apps through this agent."+ },"runtime_config": {"intro": "Choose how the OpenClaw runtime executes this agent's turns. Local mode runs the agent inside the daemon process. Gateway mode forwards each turn to an OpenClaw Gateway — useful when the daemon host is a lightweight coordinator and the agent should run on a more powerful machine.","mode_label": "Routing mode",@@ -432,6 +449,28 @@"tooltip": "Workspace · everyone in this workspace can use this agent"}},+ "access": {+ "tooltip": "Access · who may run this agent",+ "trigger_private": "Only me",+ "trigger_workspace": "Workspace",+ "trigger_members_count": "{{count}} people",+ "trigger_members_empty": "Specific people",+ "trigger_team": "Team",+ "private_title": "Private",+ "private_desc": "Only you can run this agent",+ "workspace_title": "Public to workspace",+ "workspace_desc": "Anyone in this workspace can run this agent",+ "members_title": "Public to specific people",+ "members_desc": "Only the people you pick can run this agent",+ "team_title": "Public to team",+ "team_desc": "Grant access to a whole team",+ "team_coming_soon": "Coming soon",+ "members_group": "People",+ "public_group": "Public access",+ "owner_only_readonly": "Only the agent owner can change who can run this agent.",+ "members_empty": "No workspace members to choose from",+ "composio_switch_hint": "Heads up — this agent has Composio apps enabled. Sharing it lets everyone with access use those apps through this agent."+ },"profile_card": {"unavailable": "Agent unavailable","detail_link": "Detail →",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 1b77a397c3..38e2a560d4 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -300,6 +300,38 @@"install_error_forbidden": "You no longer have permission to install Lark Bots in this workspace. Ask a workspace admin to continue.","install_error_generic": "Install failed. Try again."},+ "composio": {+ "section_title": "Composio",+ "page_description": "Browse the full Composio toolkit catalog and connect the apps your agents can act on. Only toolkits with a configured auth config can be connected right now.",+ "not_enabled_title": "Composio integration not enabled",+ "not_enabled_description_prefix": "Set",+ "not_enabled_description_suffix": "on the server to enable Composio toolkit connections.",+ "loading": "Loading toolkits…",+ "load_failed": "Failed to load Composio toolkits.",+ "empty_title": "No toolkits available",+ "empty_description": "Composio returned no toolkits. Check the API key and project configuration.",+ "search_placeholder": "Search toolkits…",+ "connect": "Connect",+ "connecting": "Connecting…",+ "connected": "Connected",+ "disconnect": "Disconnect",+ "disconnecting": "Disconnecting…",+ "not_connectable": "Not configured",+ "not_connectable_hint": "This toolkit has no auth config in your Composio project yet, so it can't be connected. Add an auth config for it in the Composio dashboard to enable connecting.",+ "connect_failed": "Couldn't start the connection. Please try again.",+ "disconnect_failed": "Couldn't disconnect. Please try again.",+ "toast_disconnected": "Disconnected",+ "disconnect_confirm_title": "Disconnect this app?",+ "disconnect_confirm_description": "Your connected account will be revoked at Composio and your agents will lose access to this toolkit. You can reconnect later.",+ "disconnect_confirm_cancel": "Cancel",+ "connections_load_failed": "Couldn't load your existing connections, so connected status may be incomplete.",+ "toast_connected": "Connected",+ "toast_connect_failed": "Couldn't complete the connection. Please try again.",+ "last_used": "Last used {{when}}",+ "last_used_never": "Never used",+ "expired": "Token expired",+ "reconnect": "Reconnect"+ },"slack": {"section_title": "Slack","page_description": "Connect each Multica Agent to its own Slack bot. Members can DM the bot, @mention it in a channel, and type /issue to spin up a new Multica issue.",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex a3ea511d61..8461e27143 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -202,6 +202,7 @@"environment": "環境","custom_args": "カスタム引数","mcp_config": "MCP",+ "composio_mcp": "MCP アプリ","integrations": "連携","runtime_config": "ルーティング","discard_dialog_title": "保存していない変更を破棄しますか?",@@ -313,6 +314,22 @@"redacted_title": "設定済み — 現在の表示では非表示","redacted_hint": "この config を読み取れるのは、エージェントのオーナーまたはワークスペースの admin のみです。"},+ "composio_mcp": {+ "subtitle": "ツールキットにチェックを入れると、あなた(この agent の作成者)が直接または下位 agent のチェーン経由でこの agent をトリガーしたときに限り、MCP サーバーとしてマウントされます。",+ "loading": "接続を読み込み中…",+ "load_failed": "接続済みアプリを読み込めませんでした。しばらくしてから再試行してください。",+ "empty_title": "接続済みのアプリがありません",+ "empty_hint": "サードパーティサービスをまだ接続していません。先に 1 つ認可してから、ここで許可してください。",+ "empty_link_to_settings": "設定 → 連携 で接続する",+ "connected": "接続済み",+ "toggle_aria": "この agent に {{toolkit}} を許可",+ "saving": "保存中…",+ "save_failed_toast": "保存できませんでした。もう一度お試しください",+ "redacted_title": "設定済み — あなたには非表示",+ "redacted_hint": "この agent が使用できるアプリを閲覧・変更できるのは作成者のみです。",+ "shared_warning": "このエージェントは共有されています。このエージェントを実行できる人は、ここで有効化した Composio アプリを利用できます。これらのアプリが機微なデータを扱う場合は、Private にするかアクセス範囲を絞ってください。",+ "workspace_warning": "ワークスペースに公開:ワークスペースの全メンバーがこのエージェントを通じてこれらの Composio アプリを利用できます。"+ },"runtime_config": {"intro": "OpenClaw ランタイムがこのエージェントの各ターンをどのように実行するかを選択します。Local モードはエージェントを daemon プロセス内で実行します。Gateway モードは各ターンを OpenClaw Gateway に転送します — daemon のホストが軽量な調整役で、エージェントの実作業はより強力なマシンで動かしたい場合に有用です。","mode_label": "ルーティングモード",@@ -411,6 +428,28 @@"tooltip": "ワークスペース · このワークスペースの全員がこのエージェントを使用できます"}},+ "access": {+ "tooltip": "アクセス · 誰がこのエージェントを実行できるか",+ "trigger_private": "自分のみ",+ "trigger_workspace": "ワークスペース",+ "trigger_members_count": "{{count}} 人",+ "trigger_members_empty": "特定のメンバー",+ "trigger_team": "チーム",+ "private_title": "プライベート",+ "private_desc": "あなただけがこのエージェントを実行できます",+ "workspace_title": "ワークスペースに公開",+ "workspace_desc": "このワークスペースの全員がこのエージェントを実行できます",+ "members_title": "特定のメンバーに公開",+ "members_desc": "選択した人だけがこのエージェントを実行できます",+ "team_title": "チームに公開",+ "team_desc": "チーム全体にアクセス権を付与します",+ "team_coming_soon": "近日公開",+ "members_group": "メンバー",+ "public_group": "公開アクセス",+ "owner_only_readonly": "このエージェントを実行できる相手は、オーナーのみが変更できます。",+ "members_empty": "選択できるワークスペースメンバーがいません",+ "composio_switch_hint": "ご注意 — このエージェントは Composio アプリが有効です。共有すると、アクセス権を持つ全員がこのエージェントを通じてこれらのアプリを利用できます。"+ },"profile_card": {"unavailable": "エージェントを利用できません","detail_link": "詳細 →",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 5df7494d8b..70501f72bf 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -300,6 +300,38 @@"install_error_forbidden": "このワークスペースに Lark ボットを設置する権限がなくなりました。ワークスペース管理者にお問い合わせください。","install_error_generic": "設置に失敗しました。もう一度お試しください。"},+ "composio": {+ "section_title": "Composio",+ "page_description": "Browse the full Composio toolkit catalog and connect the apps your agents can act on. Only toolkits with a configured auth config can be connected right now.",+ "not_enabled_title": "Composio integration not enabled",+ "not_enabled_description_prefix": "Set",+ "not_enabled_description_suffix": "on the server to enable Composio toolkit connections.",+ "loading": "Loading toolkits…",+ "load_failed": "Failed to load Composio toolkits.",+ "empty_title": "No toolkits available",+ "empty_description": "Composio returned no toolkits. Check the API key and project configuration.",+ "search_placeholder": "Search toolkits…",+ "connect": "Connect",+ "connecting": "Connecting…",+ "connected": "Connected",+ "disconnect": "Disconnect",+ "disconnecting": "Disconnecting…",+ "not_connectable": "Not configured",+ "not_connectable_hint": "This toolkit has no auth config in your Composio project yet, so it can't be connected. Add an auth config for it in the Composio dashboard to enable connecting.",+ "connect_failed": "Couldn't start the connection. Please try again.",+ "disconnect_failed": "Couldn't disconnect. Please try again.",+ "toast_disconnected": "Disconnected",+ "disconnect_confirm_title": "Disconnect this app?",+ "disconnect_confirm_description": "Your connected account will be revoked at Composio and your agents will lose access to this toolkit. You can reconnect later.",+ "disconnect_confirm_cancel": "Cancel",+ "connections_load_failed": "Couldn't load your existing connections, so connected status may be incomplete.",+ "toast_connected": "接続しました",+ "toast_connect_failed": "接続を完了できませんでした。もう一度お試しください。",+ "last_used": "最終使用 {{when}}",+ "last_used_never": "未使用",+ "expired": "トークンの有効期限切れ",+ "reconnect": "再接続"+ },"slack": {"section_title": "Slack","page_description": "各 Multica エージェントを専用の Slack ボットに接続します。メンバーはボットに DM したり、チャンネルで @メンションしたり、/issue と入力して新しい Multica イシューを起こすことができます。",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 73389a7679..bc78cca96f 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -210,6 +210,7 @@"environment": "환경","custom_args": "사용자 지정 인자","mcp_config": "MCP",+ "composio_mcp": "MCP 앱","integrations": "연동","runtime_config": "라우팅","discard_dialog_title": "저장하지 않은 변경사항을 버릴까요?",@@ -321,6 +322,22 @@"redacted_title": "설정됨 - 현재 보기에서는 숨김","redacted_hint": "에이전트 소유자 또는 워크스페이스 관리자만 이 config를 읽을 수 있습니다."},+ "composio_mcp": {+ "subtitle": "툴킷을 선택하면, 본인(이 에이전트의 생성자)이 직접 또는 하위 에이전트 체인을 통해 이 에이전트를 트리거할 때만 MCP 서버로 마운트됩니다.",+ "loading": "연결을 불러오는 중…",+ "load_failed": "연결된 앱을 불러오지 못했습니다. 잠시 후 다시 시도하세요.",+ "empty_title": "아직 연결된 앱이 없습니다",+ "empty_hint": "아직 서드파티 서비스를 연결하지 않았습니다. 먼저 하나를 인증한 뒤 여기서 허용하세요.",+ "empty_link_to_settings": "설정 → 연동에서 연결하기",+ "connected": "연결됨",+ "toggle_aria": "이 에이전트에 {{toolkit}} 허용",+ "saving": "저장 중…",+ "save_failed_toast": "저장하지 못했습니다. 다시 시도하세요",+ "redacted_title": "설정됨 — 보기에서 숨김",+ "redacted_hint": "이 에이전트가 사용할 수 있는 앱은 생성자만 보거나 변경할 수 있습니다.",+ "shared_warning": "이 에이전트는 공유되어 있습니다. 이 에이전트를 실행할 수 있는 사람은 여기서 활성화한 Composio 앱을 사용할 수 있습니다. 이러한 앱이 민감한 데이터를 노출한다면 Private로 설정하거나 접근 범위를 좁히세요.",+ "workspace_warning": "워크스페이스에 공개: 워크스페이스의 모든 구성원이 이 에이전트를 통해 이러한 Composio 앱을 사용할 수 있습니다."+ },"runtime_config": {"intro": "OpenClaw 런타임이 이 에이전트의 각 턴을 어떻게 실행할지 선택하세요. Local 모드는 에이전트를 daemon 프로세스 내부에서 실행합니다. Gateway 모드는 각 턴을 OpenClaw Gateway로 전달합니다 — daemon 호스트가 가벼운 조율기 역할을 하고 실제 작업은 더 강력한 머신에서 돌리고 싶을 때 유용합니다.","mode_label": "라우팅 모드",@@ -419,6 +436,28 @@"tooltip": "워크스페이스 · 이 워크스페이스의 모든 사람이 이 에이전트를 사용할 수 있습니다"}},+ "access": {+ "tooltip": "접근 권한 · 누가 이 에이전트를 실행할 수 있는지",+ "trigger_private": "나만",+ "trigger_workspace": "워크스페이스",+ "trigger_members_count": "{{count}}명",+ "trigger_members_empty": "특정 사용자",+ "trigger_team": "팀",+ "private_title": "비공개",+ "private_desc": "나만 이 에이전트를 실행할 수 있습니다",+ "workspace_title": "워크스페이스에 공개",+ "workspace_desc": "이 워크스페이스의 모든 사람이 이 에이전트를 실행할 수 있습니다",+ "members_title": "특정 사용자에게 공개",+ "members_desc": "선택한 사람만 이 에이전트를 실행할 수 있습니다",+ "team_title": "팀에 공개",+ "team_desc": "팀 전체에 접근 권한을 부여합니다",+ "team_coming_soon": "출시 예정",+ "members_group": "구성원",+ "public_group": "공개 액세스",+ "owner_only_readonly": "이 에이전트를 실행할 수 있는 대상은 소유자만 변경할 수 있습니다.",+ "members_empty": "선택할 워크스페이스 구성원이 없습니다",+ "composio_switch_hint": "참고 — 이 에이전트에는 Composio 앱이 활성화되어 있습니다. 공유하면 접근 권한이 있는 모든 사람이 이 에이전트를 통해 해당 앱을 사용할 수 있습니다."+ },"profile_card": {"unavailable": "에이전트를 사용할 수 없습니다","detail_link": "자세히 →",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 103f58c6e7..62675bd21f 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -377,6 +377,38 @@"install_error_forbidden": "이 워크스페이스에 Lark 봇을 설치할 권한이 더 이상 없어요. 워크스페이스 관리자에게 문의하세요.","install_error_generic": "설치에 실패했어요. 다시 시도하세요."},+ "composio": {+ "section_title": "Composio",+ "page_description": "Browse the full Composio toolkit catalog and connect the apps your agents can act on. Only toolkits with a configured auth config can be connected right now.",+ "not_enabled_title": "Composio integration not enabled",+ "not_enabled_description_prefix": "Set",+ "not_enabled_description_suffix": "on the server to enable Composio toolkit connections.",+ "loading": "Loading toolkits…",+ "load_failed": "Failed to load Composio toolkits.",+ "empty_title": "No toolkits available",+ "empty_description": "Composio returned no toolkits. Check the API key and project configuration.",+ "search_placeholder": "Search toolkits…",+ "connect": "Connect",+ "connecting": "Connecting…",+ "connected": "Connected",+ "disconnect": "Disconnect",+ "disconnecting": "Disconnecting…",+ "not_connectable": "Not configured",+ "not_connectable_hint": "This toolkit has no auth config in your Composio project yet, so it can't be connected. Add an auth config for it in the Composio dashboard to enable connecting.",+ "connect_failed": "Couldn't start the connection. Please try again.",+ "disconnect_failed": "Couldn't disconnect. Please try again.",+ "toast_disconnected": "Disconnected",+ "disconnect_confirm_title": "Disconnect this app?",+ "disconnect_confirm_description": "Your connected account will be revoked at Composio and your agents will lose access to this toolkit. You can reconnect later.",+ "disconnect_confirm_cancel": "Cancel",+ "connections_load_failed": "Couldn't load your existing connections, so connected status may be incomplete.",+ "toast_connected": "연결되었습니다",+ "toast_connect_failed": "연결을 완료하지 못했습니다. 다시 시도해 주세요.",+ "last_used": "마지막 사용 {{when}}",+ "last_used_never": "사용한 적 없음",+ "expired": "토큰 만료됨",+ "reconnect": "다시 연결"+ },"slack": {"section_title": "Slack","page_description": "각 Multica 에이전트를 전용 Slack 봇에 연결하세요. 멤버는 봇과 1:1로 대화하거나, 채널에서 @ 멘션하거나, /issue 를 입력해 새 Multica 이슈를 만들 수 있습니다.",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex cdc62763df..5d90a78505 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -210,6 +210,7 @@"environment": "环境变量","custom_args": "自定义参数","mcp_config": "MCP",+ "composio_mcp": "MCP 应用","integrations": "集成","runtime_config": "路由","discard_dialog_title": "放弃未保存的修改?",@@ -321,6 +322,22 @@"redacted_title": "已配置 —— 当前账号无权查看","redacted_hint": "只有智能体所有者或工作区管理员可以读取该配置。"},+ "composio_mcp": {+ "subtitle": "勾选 toolkit,只在你自己(这个 agent 的创建者)直接或通过下级 agent 链路触发这个 agent 时,才把它挂载为 MCP server。",+ "loading": "正在加载你的连接…",+ "load_failed": "无法加载你已连接的应用,请稍后重试。",+ "empty_title": "还没有已连接的应用",+ "empty_hint": "你还没连接任何第三方服务。先去授权一个,再回到这里勾选允许。",+ "empty_link_to_settings": "去 设置 → 集成 连一个",+ "connected": "已连接",+ "toggle_aria": "允许该 agent 使用 {{toolkit}}",+ "saving": "正在保存…",+ "save_failed_toast": "保存失败,请重试",+ "redacted_title": "已配置 —— 对你隐藏",+ "redacted_hint": "只有该 agent 的创建者才能查看或修改它可使用的应用。",+ "shared_warning": "该智能体已共享。能够运行该智能体的人可以通过它使用你在此启用的 Composio 应用。如果这些应用涉及敏感数据,请改用「私有」或缩小访问范围。",+ "workspace_warning": "公开给工作区:工作区内任何成员都可以通过该智能体使用这些 Composio 应用。"+ },"runtime_config": {"intro": "选择 OpenClaw 运行时执行该智能体每一回合的方式。Local 模式让智能体直接在 daemon 进程内运行;Gateway 模式则把每一回合转发到一个 OpenClaw Gateway —— 适合 daemon 宿主只是轻量协调机、希望真正算力落在更强的远端机器上的场景。","mode_label": "路由模式",@@ -419,6 +436,28 @@"tooltip": "工作区 · 工作区内所有人都可以使用该智能体"}},+ "access": {+ "tooltip": "访问权限 · 谁可以运行该智能体",+ "trigger_private": "仅自己",+ "trigger_workspace": "工作区",+ "trigger_members_count": "{{count}} 人",+ "trigger_members_empty": "指定成员",+ "trigger_team": "团队",+ "private_title": "私有",+ "private_desc": "只有你可以运行该智能体",+ "workspace_title": "公开给工作区",+ "workspace_desc": "工作区内任何人都可以运行该智能体",+ "members_title": "公开给指定成员",+ "members_desc": "只有你选择的人可以运行该智能体",+ "team_title": "公开给团队",+ "team_desc": "向整个团队授予访问权限",+ "team_coming_soon": "即将推出",+ "members_group": "成员",+ "public_group": "公开访问",+ "owner_only_readonly": "只有该 Agent 的所有者可以更改谁能调用它。",+ "members_empty": "没有可选择的工作区成员",+ "composio_switch_hint": "提示 —— 该智能体已启用 Composio 应用。共享后,所有获得访问权限的人都可以通过该智能体使用这些应用。"+ },"profile_card": {"unavailable": "智能体不可用","detail_link": "详情 →",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 1904535751..3c4b3e161e 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -300,6 +300,38 @@"install_error_forbidden": "你已没有在此工作区安装飞书 Bot 的权限,请联系工作区管理员。","install_error_generic": "安装失败,请重试。"},+ "composio": {+ "section_title": "Composio",+ "page_description": "浏览 Composio 的全部 toolkit,连接你的 agent 可以操作的应用。目前只有已配置 auth config 的 toolkit 可以连接。",+ "not_enabled_title": "Composio 集成未启用",+ "not_enabled_description_prefix": "在服务器上设置",+ "not_enabled_description_suffix": "以启用 Composio toolkit 连接。",+ "loading": "正在加载 toolkit…",+ "load_failed": "加载 Composio toolkit 失败。",+ "empty_title": "没有可用的 toolkit",+ "empty_description": "Composio 未返回任何 toolkit。请检查 API key 和项目配置。",+ "search_placeholder": "搜索 toolkit…",+ "connect": "连接",+ "connecting": "连接中…",+ "connected": "已连接",+ "disconnect": "断开",+ "disconnecting": "断开中…",+ "not_connectable": "未配置",+ "not_connectable_hint": "该 toolkit 在你的 Composio 项目中还没有 auth config,因此无法连接。请在 Composio 后台为它添加一个 auth config 后再连接。",+ "connect_failed": "无法发起连接,请重试。",+ "disconnect_failed": "无法断开连接,请重试。",+ "toast_disconnected": "已断开",+ "disconnect_confirm_title": "断开这个应用?",+ "disconnect_confirm_description": "你的已连接账号将在 Composio 侧被撤销,你的 agent 将失去对该 toolkit 的访问权限。你可以稍后重新连接。",+ "disconnect_confirm_cancel": "取消",+ "connections_load_failed": "无法加载你已有的连接,连接状态可能不完整。",+ "toast_connected": "已连接",+ "toast_connect_failed": "连接未能完成,请重试。",+ "last_used": "最近使用 {{when}}",+ "last_used_never": "从未使用",+ "expired": "令牌已过期",+ "reconnect": "重新连接"+ },"slack": {"section_title": "Slack","page_description": "将每个 Multica 智能体连接到专属的 Slack 机器人。成员可私聊机器人、在频道中 @ 它,或输入 /issue 直接创建 Multica issue。",diff --git a/packages/views/modals/create-squad.test.tsx b/packages/views/modals/create-squad.test.tsxindex 233b7b5942..772195fd4c 100644--- a/packages/views/modals/create-squad.test.tsx+++ b/packages/views/modals/create-squad.test.tsx@@ -204,6 +204,8 @@ function makeAgent(overrides: Partial<Agent> & { id: string; name: string; ownerruntime_config: {},custom_args: [],visibility: "private",+ permission_mode: "private",+ invocation_targets: [],status: "idle",max_concurrent_tasks: 1,model: "",diff --git a/packages/views/runtimes/components/delete-runtime-dialog.test.tsx b/packages/views/runtimes/components/delete-runtime-dialog.test.tsxindex 33fb884320..5eb82abfe0 100644--- a/packages/views/runtimes/components/delete-runtime-dialog.test.tsx+++ b/packages/views/runtimes/components/delete-runtime-dialog.test.tsx@@ -145,6 +145,8 @@ function makeAgent(id: string, overrides: Partial<Agent> = {}): Agent {runtime_config: {},custom_args: [],visibility: "private",+ permission_mode: "private",+ invocation_targets: [],status: "idle",max_concurrent_tasks: 1,model: "claude-sonnet-4-5",diff --git a/packages/views/runtimes/components/runtime-list.test.ts b/packages/views/runtimes/components/runtime-list.test.tsindex 5dd2344290..d66a5b8a1c 100644--- a/packages/views/runtimes/components/runtime-list.test.ts+++ b/packages/views/runtimes/components/runtime-list.test.ts@@ -15,6 +15,8 @@ function makeAgent(overrides: Partial<Agent> = {}): Agent {runtime_config: {},custom_args: [],visibility: "private",+ permission_mode: "private",+ invocation_targets: [],status: "idle",max_concurrent_tasks: 1,model: "gpt-5.4",diff --git a/packages/views/settings/components/composio-tab.test.tsx b/packages/views/settings/components/composio-tab.test.tsxnew file mode 100644index 0000000000..8367935fa8--- /dev/null+++ b/packages/views/settings/components/composio-tab.test.tsx@@ -0,0 +1,193 @@+import { describe, it, expect, beforeEach, vi } from "vitest";+import { StrictMode } from "react";+import { render, screen, waitFor } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";+import type { ComposioConnection, ComposioToolkit } from "@multica/core/types";++// --- Mutable refs the mocked hooks read from, so each test can shape the data+// without re-mocking the modules. ---+const toolkitsRef = vi.hoisted(() => ({+ current: { data: [] as ComposioToolkit[], isLoading: false, isError: false },+}));+const connectionsRef = vi.hoisted(() => ({+ current: { data: [] as ComposioConnection[], isError: false },+}));+const searchParamsRef = vi.hoisted(() => ({ current: new URLSearchParams("tab=integrations") }));++const mockInvalidate = vi.hoisted(() => vi.fn());+const mockReplace = vi.hoisted(() => vi.fn());+const mockToastSuccess = vi.hoisted(() => vi.fn());+const mockToastError = vi.hoisted(() => vi.fn());++vi.mock("@tanstack/react-query", () => ({+ useQuery: (opts: { queryKey: unknown[] }) => {+ const key = JSON.stringify(opts.queryKey);+ if (key.includes("toolkits")) return toolkitsRef.current;+ if (key.includes("connections")) return connectionsRef.current;+ return { data: undefined };+ },+ useQueryClient: () => ({ invalidateQueries: mockInvalidate }),+ queryOptions: <T,>(opts: T) => opts,+}));++vi.mock("@multica/core/composio", () => ({+ composioKeys: {+ all: ["composio"],+ toolkits: () => ["composio", "toolkits"],+ connections: () => ["composio", "connections"],+ },+ composioToolkitsOptions: () => ({ queryKey: ["composio", "toolkits"], queryFn: vi.fn() }),+ composioConnectionsOptions: () => ({ queryKey: ["composio", "connections"], queryFn: vi.fn() }),+}));++vi.mock("@multica/core/api", () => ({+ api: {+ beginComposioConnect: vi.fn(),+ deleteComposioConnection: vi.fn(),+ },+}));++vi.mock("../../navigation", () => ({+ useNavigation: () => ({+ push: vi.fn(),+ replace: mockReplace,+ back: vi.fn(),+ pathname: "/acme/settings",+ searchParams: searchParamsRef.current,+ getShareableUrl: (p: string) => `https://app.example${p}`,+ }),+}));++vi.mock("sonner", () => ({+ toast: { success: mockToastSuccess, error: mockToastError },+}));++import { ComposioTab } from "./composio-tab";++function renderTab() {+ return render(+ <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>+ <ComposioTab />+ </I18nProvider>,+ );+}++// StrictMode reproduces React's dev-mode mount → cleanup → mount double-invoke,+// which is exactly what would double-fire the callback toast without the+// consumed-key ref guard.+function renderTabStrict() {+ return render(+ <StrictMode>+ <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>+ <ComposioTab />+ </I18nProvider>+ </StrictMode>,+ );+}++const NOTION: ComposioToolkit = {+ slug: "notion",+ name: "Notion",+ connectable: true,+};++beforeEach(() => {+ vi.clearAllMocks();+ toolkitsRef.current = { data: [NOTION], isLoading: false, isError: false };+ connectionsRef.current = { data: [], isError: false };+ searchParamsRef.current = new URLSearchParams("tab=integrations");+});++describe("ComposioTab", () => {+ it("renders a connected card with a 'never used' placeholder when last_used_at is null", () => {+ connectionsRef.current = {+ data: [+ {+ id: "conn-1",+ toolkit_slug: "notion",+ status: "active",+ connected_at: "2026-06-01T00:00:00Z",+ last_used_at: null,+ },+ ],+ isError: false,+ };+ renderTab();+ expect(screen.getByText(enSettings.composio.connected)).toBeInTheDocument();+ expect(screen.getByText(enSettings.composio.last_used_never)).toBeInTheDocument();+ });++ it("renders a 'Last used' line when last_used_at is present", () => {+ connectionsRef.current = {+ data: [+ {+ id: "conn-1",+ toolkit_slug: "notion",+ status: "active",+ connected_at: "2026-06-01T00:00:00Z",+ last_used_at: new Date(Date.now() - 2 * 60 * 1000).toISOString(),+ },+ ],+ isError: false,+ };+ renderTab();+ // "Last used {{when}}" → relative time formatter yields "2m ago"+ expect(screen.getByText(/Last used/)).toBeInTheDocument();+ expect(screen.queryByText(enSettings.composio.last_used_never)).not.toBeInTheDocument();+ });++ it("renders the expired branch with a Reconnect button", () => {+ connectionsRef.current = {+ data: [+ {+ id: "conn-1",+ toolkit_slug: "notion",+ status: "expired",+ connected_at: "2026-06-01T00:00:00Z",+ last_used_at: null,+ },+ ],+ isError: false,+ };+ renderTab();+ expect(screen.getByText(enSettings.composio.expired)).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: new RegExp(enSettings.composio.reconnect) }),+ ).toBeInTheDocument();+ // Not treated as connected, so no Connected badge.+ expect(screen.queryByText(enSettings.composio.connected)).not.toBeInTheDocument();+ });++ it("toasts success and clears the ?connected param on a successful callback", async () => {+ searchParamsRef.current = new URLSearchParams("tab=integrations&connected=notion");+ renderTab();+ await waitFor(() => {+ expect(mockToastSuccess).toHaveBeenCalledWith(enSettings.composio.toast_connected);+ });+ expect(mockInvalidate).toHaveBeenCalledWith({ queryKey: ["composio", "connections"] });+ // The one-shot param is stripped while ?tab is preserved.+ expect(mockReplace).toHaveBeenCalledWith("/acme/settings?tab=integrations");+ });++ it("toasts error on a failed callback", async () => {+ searchParamsRef.current = new URLSearchParams("tab=integrations&error=composio_connect_failed");+ renderTab();+ await waitFor(() => {+ expect(mockToastError).toHaveBeenCalledWith(enSettings.composio.toast_connect_failed);+ });+ expect(mockReplace).toHaveBeenCalledWith("/acme/settings?tab=integrations");+ });++ it("fires the success callback exactly once under StrictMode double-invoke", async () => {+ searchParamsRef.current = new URLSearchParams("tab=integrations&connected=notion");+ renderTabStrict();+ await waitFor(() => {+ expect(mockToastSuccess).toHaveBeenCalled();+ });+ // The consumed-key ref must suppress the second (cleanup → re-mount) run.+ expect(mockToastSuccess).toHaveBeenCalledTimes(1);+ expect(mockInvalidate).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/views/settings/components/composio-tab.tsx b/packages/views/settings/components/composio-tab.tsxnew file mode 100644index 0000000000..bef474f82b--- /dev/null+++ b/packages/views/settings/components/composio-tab.tsx@@ -0,0 +1,365 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { AlertTriangle, Check, Loader2, Plug, RefreshCw, Trash2 } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Card, CardContent } from "@multica/ui/components/ui/card";+import { Input } from "@multica/ui/components/ui/input";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { api } from "@multica/core/api";+import {+ composioConnectionsOptions,+ composioKeys,+ composioToolkitsOptions,+} from "@multica/core/composio";+import type { ComposioToolkit } from "@multica/core/types";+import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";+import { useT, useTimeAgo } from "../../i18n";+import { useNavigation } from "../../navigation";++// ComposioTab renders the full Composio toolkit catalog and lets the user+// connect / disconnect the apps their agents can act on.+//+// Key UX rule (MUL-3720): listing ≠ connectable. Only toolkits with an enabled+// auth config in the Composio project carry `connectable: true`; the rest get a+// muted "not configured" hint instead of a dead Connect button that would 400.+export function ComposioTab() {+ const { t } = useT("settings");+ const qc = useQueryClient();+ const navigation = useNavigation();++ const toolkitsQuery = useQuery(composioToolkitsOptions());+ const connectionsQuery = useQuery(composioConnectionsOptions());++ const [query, setQuery] = useState("");+ const [connectingSlug, setConnectingSlug] = useState<string | null>(null);+ const [disconnectTarget, setDisconnectTarget] = useState<{+ connectionId: string;+ name: string;+ } | null>(null);+ const [disconnecting, setDisconnecting] = useState(false);++ // The hosted Composio consent flow is a full-page redirect that lands back+ // on the settings page carrying either `?connected=<slug>` (success) or+ // `?error=composio_connect_failed` (any backend-side failure — see+ // Service.CallbackRedirect, MUL-3720). Consume it exactly once: fire a toast,+ // refresh the connections list so the freshly-linked card flips to Connected+ // without a manual reload, then strip the one-shot params via `replace` so a+ // browser refresh doesn't re-toast.+ const connectedParam = navigation.searchParams.get("connected");+ const errorParam = navigation.searchParams.get("error");+ // React Strict Mode (dev / Next) double-invokes mount effects as+ // mount → cleanup → mount. On the second invoke the `replace` from the first+ // hasn't committed yet, so the closure still sees the same params and would+ // toast + invalidate twice. Guard with a ref keyed on the callback we already+ // consumed; a genuinely new callback (different slug, or the redirect being a+ // full page load that resets this ref) still fires.+ const consumedCallbackKey = useRef<string | null>(null);+ useEffect(() => {+ const callbackKey = connectedParam+ ? `connected:${connectedParam}`+ : errorParam === "composio_connect_failed"+ ? "error:composio_connect_failed"+ : null;+ if (!callbackKey) return;+ if (consumedCallbackKey.current === callbackKey) return;+ consumedCallbackKey.current = callbackKey;+ if (connectedParam) {+ toast.success(t(($) => $.composio.toast_connected));+ void qc.invalidateQueries({ queryKey: composioKeys.connections() });+ } else {+ toast.error(t(($) => $.composio.toast_connect_failed));+ }+ // Drop only the Composio one-shot params; keep everything else (notably+ // ?tab=integrations) so the user stays on this tab.+ const params = new URLSearchParams(navigation.searchParams);+ params.delete("connected");+ params.delete("error");+ const qs = params.toString();+ navigation.replace(qs ? `${navigation.pathname}?${qs}` : navigation.pathname);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [connectedParam, errorParam]);++ // Map active connections by toolkit slug so each card knows whether it is+ // already connected (and which connection id to disconnect).+ const connectionBySlug = useMemo(() => {+ const m = new Map<string, string>();+ for (const c of connectionsQuery.data ?? []) {+ if (c.status === "active") m.set(c.toolkit_slug, c.id);+ }+ return m;+ }, [connectionsQuery.data]);++ // Toolkits whose latest connection is expired render a Reconnect affordance+ // instead of Connected/Connect. Backend only emits `expired` once Stage 4+ // (MUL-3719) lands, but the branch is wired up now so it lights up for free.+ const expiredBySlug = useMemo(() => {+ const m = new Set<string>();+ for (const c of connectionsQuery.data ?? []) {+ if (c.status === "expired") m.add(c.toolkit_slug);+ }+ return m;+ }, [connectionsQuery.data]);++ // Last-used timestamp per active connection, for the "Last used …" line on a+ // connected card. Backend leaves this null until tool-call dispatch starts+ // stamping it (Stage 3, MUL-3721); the card shows a "never used" placeholder+ // until then.+ const lastUsedBySlug = useMemo(() => {+ const m = new Map<string, string | null>();+ for (const c of connectionsQuery.data ?? []) {+ if (c.status === "active") m.set(c.toolkit_slug, c.last_used_at ?? null);+ }+ return m;+ }, [connectionsQuery.data]);++ const toolkits = useMemo(() => toolkitsQuery.data ?? [], [toolkitsQuery.data]);+ const filtered = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (!q) return toolkits;+ return toolkits.filter(+ (tk) =>+ tk.name.toLowerCase().includes(q) ||+ tk.slug.toLowerCase().includes(q) ||+ (tk.category ?? "").toLowerCase().includes(q),+ );+ }, [toolkits, query]);++ // 503 handling lives in the parent IntegrationsTab, which hides the whole+ // Composio section when COMPOSIO_API_KEY is unset — this component only+ // mounts when the integration is configured, so it deals with the loaded /+ // error / empty / list states below.++ async function handleConnect(tk: ComposioToolkit) {+ if (connectingSlug) return;+ setConnectingSlug(tk.slug);+ try {+ const { redirect_url } = await api.beginComposioConnect(tk.slug);+ // Hand the browser to Composio's hosted consent flow; it redirects back+ // to /api/integrations/composio/callback when done.+ window.location.href = redirect_url;+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.composio.connect_failed));+ setConnectingSlug(null);+ }+ }++ async function handleDisconnect() {+ if (!disconnectTarget || disconnecting) return;+ setDisconnecting(true);+ try {+ await api.deleteComposioConnection(disconnectTarget.connectionId);+ await qc.invalidateQueries({ queryKey: composioKeys.connections() });+ toast.success(t(($) => $.composio.toast_disconnected));+ setDisconnectTarget(null);+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.composio.disconnect_failed));+ } finally {+ setDisconnecting(false);+ }+ }++ return (+ <div className="space-y-6">+ <section className="space-y-1">+ <p className="text-sm text-muted-foreground">{t(($) => $.composio.page_description)}</p>+ </section>++ {toolkitsQuery.isLoading ? (+ <Card>+ <CardContent>+ <p className="text-sm text-muted-foreground">{t(($) => $.composio.loading)}</p>+ </CardContent>+ </Card>+ ) : toolkitsQuery.isError ? (+ <Card>+ <CardContent>+ <p className="text-sm text-destructive">{t(($) => $.composio.load_failed)}</p>+ </CardContent>+ </Card>+ ) : toolkits.length === 0 ? (+ <Card>+ <CardContent className="space-y-2">+ <p className="text-sm font-medium">{t(($) => $.composio.empty_title)}</p>+ <p className="text-xs text-muted-foreground">{t(($) => $.composio.empty_description)}</p>+ </CardContent>+ </Card>+ ) : (+ <section className="space-y-3">+ <Input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t(($) => $.composio.search_placeholder)}+ className="max-w-xs"+ />+ {connectionsQuery.isError && (+ // Don't silently treat a failed connections fetch as "nothing+ // connected" — that would hide real connections and offer Connect+ // on something already linked. Surface it so the user knows the+ // connected state may be incomplete; the catalog still renders.+ <p className="text-xs text-destructive">+ {t(($) => $.composio.connections_load_failed)}+ </p>+ )}+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">+ {filtered.map((tk) => (+ <ToolkitCard+ key={tk.slug}+ toolkit={tk}+ connectionId={connectionBySlug.get(tk.slug)}+ expired={expiredBySlug.has(tk.slug)}+ lastUsedAt={lastUsedBySlug.get(tk.slug) ?? null}+ connecting={connectingSlug === tk.slug}+ anyConnecting={connectingSlug !== null}+ onConnect={() => handleConnect(tk)}+ onDisconnect={(connectionId, name) =>+ setDisconnectTarget({ connectionId, name })+ }+ />+ ))}+ </div>+ </section>+ )}++ <AlertDialog+ open={!!disconnectTarget}+ onOpenChange={(v) => {+ if (!v && !disconnecting) setDisconnectTarget(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.composio.disconnect_confirm_title)}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.composio.disconnect_confirm_description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={disconnecting}>+ {t(($) => $.composio.disconnect_confirm_cancel)}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>+ {disconnecting+ ? t(($) => $.composio.disconnecting)+ : t(($) => $.composio.disconnect)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++function ToolkitCard({+ toolkit,+ connectionId,+ expired,+ lastUsedAt,+ connecting,+ anyConnecting,+ onConnect,+ onDisconnect,+}: {+ toolkit: ComposioToolkit;+ connectionId?: string;+ expired: boolean;+ lastUsedAt: string | null;+ connecting: boolean;+ anyConnecting: boolean;+ onConnect: () => void;+ onDisconnect: (connectionId: string, name: string) => void;+}) {+ const { t } = useT("settings");+ const timeAgo = useTimeAgo();+ const isConnected = !!connectionId;++ return (+ <Card>+ <CardContent className="flex items-center gap-3 p-3">+ <ComposioToolkitLogo+ slug={toolkit.slug}+ name={toolkit.name}+ fallbackLogo={toolkit.logo}+ />+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium">{toolkit.name || toolkit.slug}</p>+ {isConnected ? (+ // Last-used line. Backend leaves last_used_at null until Stage 3+ // dispatch stamps it, so show a localized "never used" placeholder+ // rather than hiding the line entirely.+ <p className="truncate text-[10px] text-muted-foreground">+ {lastUsedAt+ ? t(($) => $.composio.last_used, { when: timeAgo(lastUsedAt) })+ : t(($) => $.composio.last_used_never)}+ </p>+ ) : toolkit.category ? (+ <p className="truncate text-[10px] uppercase tracking-wide text-muted-foreground">+ {toolkit.category}+ </p>+ ) : null}+ </div>++ {isConnected ? (+ <div className="flex items-center gap-2">+ <span className="inline-flex items-center gap-1 text-xs text-emerald-600">+ <Check className="h-3 w-3" />+ {t(($) => $.composio.connected)}+ </span>+ <Button+ variant="outline"+ size="sm"+ onClick={() => onDisconnect(connectionId!, toolkit.name || toolkit.slug)}+ aria-label={t(($) => $.composio.disconnect)}+ >+ <Trash2 className="h-3 w-3" />+ </Button>+ </div>+ ) : expired ? (+ // Token-expired connection: surface the failure and let the user+ // re-run the same connect flow in one click (no disconnect step).+ <div className="flex items-center gap-2">+ <span className="inline-flex items-center gap-1 text-xs text-amber-600">+ <AlertTriangle className="h-3 w-3" />+ {t(($) => $.composio.expired)}+ </span>+ <Button size="sm" variant="outline" onClick={onConnect} disabled={anyConnecting}>+ {connecting ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <RefreshCw className="h-3 w-3" />+ )}+ {connecting ? t(($) => $.composio.connecting) : t(($) => $.composio.reconnect)}+ </Button>+ </div>+ ) : toolkit.connectable ? (+ <Button size="sm" onClick={onConnect} disabled={anyConnecting}>+ {connecting ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <Plug className="h-3 w-3" />+ )}+ {connecting ? t(($) => $.composio.connecting) : t(($) => $.composio.connect)}+ </Button>+ ) : (+ <span+ className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground"+ title={t(($) => $.composio.not_connectable_hint)}+ >+ {t(($) => $.composio.not_connectable)}+ </span>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/packages/views/settings/components/integrations-tab.test.tsx b/packages/views/settings/components/integrations-tab.test.tsxnew file mode 100644index 0000000000..beee6e059e--- /dev/null+++ b/packages/views/settings/components/integrations-tab.test.tsx@@ -0,0 +1,88 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { ApiError } from "@multica/core/api";+import { configStore } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";++const composioErrorRef = vi.hoisted(() => ({+ current: null as Error | null,+}));+const queryCallsRef = vi.hoisted(() => ({+ current: [] as { queryKey: unknown[]; enabled?: boolean }[],+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: (opts: { queryKey: unknown[]; enabled?: boolean }) => {+ queryCallsRef.current.push(opts);+ return {+ data: undefined,+ error: opts.enabled === false ? null : composioErrorRef.current,+ isError: opts.enabled !== false && composioErrorRef.current != null,+ };+ },+ queryOptions: <T,>(opts: T) => opts,+}));++vi.mock("@multica/core/composio", () => ({+ composioToolkitsOptions: () => ({ queryKey: ["composio", "toolkits"] }),+}));++vi.mock("./lark-tab", () => ({+ LarkTab: () => <div data-testid="lark-tab" />,+}));++vi.mock("./composio-tab", () => ({+ ComposioTab: () => <div data-testid="composio-tab" />,+}));++vi.mock("./slack-tab", () => ({+ SlackTab: () => <div data-testid="slack-tab" />,+}));++import { IntegrationsTab } from "./integrations-tab";++function renderTab() {+ return render(+ <I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>+ <IntegrationsTab />+ </I18nProvider>,+ );+}++describe("Settings IntegrationsTab", () => {+ beforeEach(() => {+ queryCallsRef.current = [];+ composioErrorRef.current = null;+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: true });+ });++ it("hides Composio and disables the toolkits query when the feature flag is off", () => {+ configStore.getState().setFeatureFlags({ [COMPOSIO_MCP_APPS_FLAG]: false });++ renderTab();++ expect(screen.queryByTestId("composio-tab")).toBeNull();+ expect(queryCallsRef.current).toHaveLength(1);+ expect(queryCallsRef.current[0]?.enabled).toBe(false);+ });++ it("shows Composio when the feature flag is on and the integration is configured", () => {+ renderTab();++ expect(screen.getByTestId("composio-tab")).toBeInTheDocument();+ expect(queryCallsRef.current[0]?.enabled).toBe(true);+ });++ it("hides Composio when the feature flag is on but the server reports 503", () => {+ composioErrorRef.current = new ApiError("unavailable", 503, "Service Unavailable");++ renderTab();++ expect(screen.queryByTestId("composio-tab")).toBeNull();+ });+});diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsxindex 0986ca671c..affcf0b1db 100644--- a/packages/views/settings/components/integrations-tab.tsx+++ b/packages/views/settings/components/integrations-tab.tsx@@ -1,23 +1,47 @@"use client";+import { useQuery } from "@tanstack/react-query";import { LarkTab } from "./lark-tab";+import { ComposioTab } from "./composio-tab";import { SlackTab } from "./slack-tab";+import { ApiError } from "@multica/core/api";+import { composioToolkitsOptions } from "@multica/core/composio";+import { useFeatureEnabled } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";import { useT } from "../../i18n";// Integrations is the umbrella tab for third-party platform connections.// GitHub has its own top-level tab (see github-tab.tsx); everything else-// — currently Lark and Slack, with Linear etc. to follow — lives in here-// under its own section heading so additional integrations slot in without-// changing the IA. IntegrationsTab is just the host; each integration owns-// its own description and install flow.+// — currently Lark, Composio, and Slack, with Linear etc. to follow — lives in+// here under its own section heading so additional integrations slot in without+// changing the IA. IntegrationsTab is just the host; each integration owns its+// own description and install flow.export function IntegrationsTab() {const { t } = useT("settings");++ const composioEnabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);+ // Composio is hidden entirely until the feature is enabled and a key is+ // configured server-side. A 503 from the toolkits endpoint means the server+ // withheld the integration despite the frontend flag being on.+ const composioToolkits = useQuery({+ ...composioToolkitsOptions(),+ enabled: composioEnabled,+ });+ const composioUnconfigured =+ composioToolkits.error instanceof ApiError && composioToolkits.error.status === 503;+return (<div className="space-y-10"><section className="space-y-4"><h2 className="text-sm font-semibold">{t(($) => $.lark.section_title)}</h2><LarkTab /></section>+ {composioEnabled && !composioUnconfigured && (+ <section className="space-y-4">+ <h2 className="text-sm font-semibold">{t(($) => $.composio.section_title)}</h2>+ <ComposioTab />+ </section>+ )}<section className="space-y-4"><h2 className="text-sm font-semibold">{t(($) => $.slack.section_title)}</h2><SlackTab />diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 2b1a44c48d..65978d0ddc 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -171,7 +171,10 @@ func init() {agentCreateCmd.Flags().String("mcp-config", "", "MCP server configuration as a JSON object, e.g. '{\"mcpServers\":{\"shortcut\":{...}}}'. Treated as secret material (MCP entries often carry API tokens) — never logged by the CLI, but values passed on the command line are visible to shell history and 'ps'; prefer --mcp-config-stdin or --mcp-config-file for real secrets.")agentCreateCmd.Flags().Bool("mcp-config-stdin", false, "Read the --mcp-config JSON object from stdin. Keeps secrets out of shell history and 'ps'. Mutually exclusive with --mcp-config and --mcp-config-file.")agentCreateCmd.Flags().String("mcp-config-file", "", "Read the --mcp-config JSON object from a file path (suggested mode: 0600). Mutually exclusive with --mcp-config and --mcp-config-stdin.")- agentCreateCmd.Flags().String("visibility", "private", "Visibility: private or workspace")+ agentCreateCmd.Flags().String("visibility", "private", "Visibility: private or workspace (legacy; mapped to --permission-mode. private->private, workspace->public_to+workspace target)")+ agentCreateCmd.Flags().String("permission-mode", "", "Invocation permission mode: private (owner only) or public_to (allow-list via --public-to-*). Authoritative over --visibility when set.")+ agentCreateCmd.Flags().Bool("public-to-workspace", false, "public_to: allow every workspace member to invoke this agent.")+ agentCreateCmd.Flags().StringSlice("public-to-member", nil, "public_to: allow the given member user id(s) to invoke this agent. Repeatable.")agentCreateCmd.Flags().Int32("max-concurrent-tasks", 6, "Maximum concurrent tasks")agentCreateCmd.Flags().String("output", "json", "Output format: table or json")@@ -195,7 +198,10 @@ func init() {agentUpdateCmd.Flags().String("mcp-config", "", "New MCP server configuration as a JSON object, e.g. '{\"mcpServers\":{...}}'. Pass 'null' to clear. Treated as secret material — never logged by the CLI, but values passed on the command line are visible to shell history and 'ps'; prefer --mcp-config-stdin or --mcp-config-file for real secrets.")agentUpdateCmd.Flags().Bool("mcp-config-stdin", false, "Read the --mcp-config JSON from stdin. Keeps secrets out of shell history and 'ps'. Mutually exclusive with --mcp-config and --mcp-config-file.")agentUpdateCmd.Flags().String("mcp-config-file", "", "Read the --mcp-config JSON from a file path (suggested mode: 0600). Mutually exclusive with --mcp-config and --mcp-config-stdin.")- agentUpdateCmd.Flags().String("visibility", "", "New visibility: private or workspace")+ agentUpdateCmd.Flags().String("visibility", "", "New visibility: private or workspace (legacy; mapped to --permission-mode)")+ agentUpdateCmd.Flags().String("permission-mode", "", "New invocation permission mode: private or public_to. Authoritative over --visibility. Owner-only.")+ agentUpdateCmd.Flags().Bool("public-to-workspace", false, "public_to: allow every workspace member to invoke this agent.")+ agentUpdateCmd.Flags().StringSlice("public-to-member", nil, "public_to: allow the given member user id(s) to invoke this agent. Repeatable.")agentUpdateCmd.Flags().String("status", "", "New status")agentUpdateCmd.Flags().Int32("max-concurrent-tasks", 0, "New max concurrent tasks")agentUpdateCmd.Flags().String("output", "json", "Output format: table or json")@@ -471,6 +477,38 @@ func runAgentGet(cmd *cobra.Command, args []string) error {return nil}+// applyAgentPermissionFlags translates the invocation-permission flags+// (--permission-mode / --public-to-workspace / --public-to-member) into the+// permission_mode + invocation_targets request fields (MUL-3963). When none of+// the flags are set it is a no-op, so the legacy --visibility handling still+// drives the request. When any public-to-* flag is present without an explicit+// --permission-mode, the mode defaults to public_to.+func applyAgentPermissionFlags(cmd *cobra.Command, body map[string]any) {+ hasMode := cmd.Flags().Changed("permission-mode")+ hasWorkspace := cmd.Flags().Changed("public-to-workspace")+ hasMembers := cmd.Flags().Changed("public-to-member")+ if !hasMode && !hasWorkspace && !hasMembers {+ return+ }++ mode := "public_to"+ if hasMode {+ mode, _ = cmd.Flags().GetString("permission-mode")+ }+ body["permission_mode"] = mode++ targets := []map[string]any{}+ if on, _ := cmd.Flags().GetBool("public-to-workspace"); on {+ targets = append(targets, map[string]any{"target_type": "workspace"})+ }+ if members, _ := cmd.Flags().GetStringSlice("public-to-member"); len(members) > 0 {+ for _, m := range members {+ targets = append(targets, map[string]any{"target_type": "member", "target_id": m})+ }+ }+ body["invocation_targets"] = targets+}+func runAgentCreate(cmd *cobra.Command, _ []string) error {client, err := newAPIClient(cmd)if err != nil {@@ -538,6 +576,7 @@ func runAgentCreate(cmd *cobra.Command, _ []string) error {v, _ := cmd.Flags().GetString("visibility")body["visibility"] = v}+ applyAgentPermissionFlags(cmd, body)if cmd.Flags().Changed("max-concurrent-tasks") {v, _ := cmd.Flags().GetInt32("max-concurrent-tasks")body["max_concurrent_tasks"] = v@@ -614,6 +653,7 @@ func runAgentUpdate(cmd *cobra.Command, args []string) error {v, _ := cmd.Flags().GetString("visibility")body["visibility"] = v}+ applyAgentPermissionFlags(cmd, body)if cmd.Flags().Changed("status") {v, _ := cmd.Flags().GetString("status")body["status"] = vdiff --git a/server/cmd/server/composio_callback_public_test.go b/server/cmd/server/composio_callback_public_test.gonew file mode 100644index 0000000000..08b2d45065--- /dev/null+++ b/server/cmd/server/composio_callback_public_test.go@@ -0,0 +1,68 @@+package main++import (+ "io"+ "net/http"+ "testing"+)++// TestComposioCallbackIsPublic_NoCookieNot401 locks in the MUL-3843 fix: the+// Composio OAuth callback must live OUTSIDE the Auth middleware group, because+// Composio 302-redirects the user's browser to it and the cookie session is+// frequently absent (expired session, SameSite=Strict / Safari ITP, private+// window, self-hosted callback subdomain). Before the fix the route sat under+// Auth, so a cookie-less browser got a hard 401 and a JSON blob instead of the+// settings redirect — the exact symptom Yushen hit.+//+// With no COMPOSIO_API_KEY configured in the test env, h.Composio == nil, so a+// cookie-less hit on the callback now reaches the handler and returns 503+// ("not configured") rather than being short-circuited to 401 by the Auth+// middleware. The precise non-401 code is incidental; what this test pins is+// that the request is NOT rejected by auth.+func TestComposioCallbackIsPublic_NoCookieNot401(t *testing.T) {+ // Deliberately send NO Authorization header / cookie — simulate the+ // cookie-stripped browser redirect coming back from Composio.+ resp, err := http.Get(testServer.URL + "/api/integrations/composio/callback?state=bogus&status=success&connected_account_id=ca_x")+ if err != nil {+ t.Fatalf("callback request failed: %v", err)+ }+ defer resp.Body.Close()+ body, _ := io.ReadAll(resp.Body)++ if resp.StatusCode == http.StatusUnauthorized {+ t.Fatalf("callback returned 401 without a session — it is still behind the Auth group (regression of MUL-3843). body=%s", body)+ }+}++// TestComposioNonCallbackEndpointsStayGated is the other half of the invariant:+// moving the callback out of the Auth group must NOT loosen the four+// session-scoped endpoints. A cookie-less request to them must still 401.+func TestComposioNonCallbackEndpointsStayGated(t *testing.T) {+ gated := []struct {+ method string+ path string+ }{+ {http.MethodPost, "/api/integrations/composio/connect/init"},+ {http.MethodGet, "/api/integrations/composio/toolkits"},+ {http.MethodGet, "/api/integrations/composio/connections"},+ {http.MethodDelete, "/api/integrations/composio/connections/11111111-1111-1111-1111-111111111111"},+ }+ for _, tc := range gated {+ t.Run(tc.method+" "+tc.path, func(t *testing.T) {+ req, err := http.NewRequest(tc.method, testServer.URL+tc.path, nil)+ if err != nil {+ t.Fatalf("build request: %v", err)+ }+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("request failed: %v", err)+ }+ defer resp.Body.Close()+ io.Copy(io.Discard, resp.Body)++ if resp.StatusCode != http.StatusUnauthorized {+ t.Fatalf("expected 401 without a session, got %d — endpoint is no longer auth-gated", resp.StatusCode)+ }+ })+ }+}diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.goindex bd5a546337..3ef5632ba9 100644--- a/server/cmd/server/rerun_session_test.go+++ b/server/cmd/server/rerun_session_test.go@@ -235,7 +235,7 @@ func TestCreateRetryTaskFreshensCodexSemanticInactivity(t *testing.T) {}queries := db.New(testPool)- child, err := queries.CreateRetryTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(parentID), Valid: true})+ child, err := queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: pgtype.UUID{Bytes: parseUUIDBytes(parentID), Valid: true}})if err != nil {t.Fatalf("CreateRetryTask failed: %v", err)}@@ -278,7 +278,7 @@ func TestCreateRetryTaskKeepsOrdinaryTimeoutSession(t *testing.T) {}queries := db.New(testPool)- child, err := queries.CreateRetryTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(parentID), Valid: true})+ child, err := queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: pgtype.UUID{Bytes: parseUUIDBytes(parentID), Valid: true}})if err != nil {t.Fatalf("CreateRetryTask failed: %v", err)}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 14a777bc97..efe862131b 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2,6 +2,7 @@ package mainimport ("context"+ "crypto/sha256""log/slog""net/http""net/netip"@@ -22,9 +23,11 @@ import ("github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/featureflagdispatch"+ "github.com/multica-ai/multica/server/internal/featureflags""github.com/multica-ai/multica/server/internal/handler""github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ composiointeg "github.com/multica-ai/multica/server/internal/integrations/composio""github.com/multica-ai/multica/server/internal/integrations/lark""github.com/multica-ai/multica/server/internal/integrations/slack"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"@@ -34,6 +37,7 @@ import ("github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/internal/util/secretbox"+ composiosdk "github.com/multica-ai/multica/server/pkg/composio"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/featureflag")@@ -175,9 +179,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus}h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)h.Metrics = opts.BusinessMetrics+ h.FeatureFlags = opts.FeatureFlagsif opts.FeatureFlags != nil {h.DaemonFeatureFlags = featureflagdispatch.NewEvaluator(opts.FeatureFlags)}+ h.TaskService.FeatureFlags = opts.FeatureFlagsh.TaskService.Metrics = opts.BusinessMetricsh.IssueService.Metrics = opts.BusinessMetricsif opts.BusinessMetrics != nil {@@ -505,6 +511,63 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busslog.Info("slack integration disabled (MULTICA_SLACK_SECRET_KEY not set)")}+ // Composio integration (MUL-3720). Gated by COMPOSIO_API_KEY plus the+ // composio_mcp_apps feature flag. The env var is the project-scoped key the+ // standalone SDK authenticates Composio with (sent as x-api-key; the project+ // is resolved from the key, so NO project id is configured). When unset or+ // flag-disabled the whole block is skipped and the composio HTTP handlers+ // return 503; existing deployments are unaffected. An operator opts in by+ // setting COMPOSIO_API_KEY plus a callback base+ // (COMPOSIO_CALLBACK_BASE_URL, falling back to MULTICA_PUBLIC_URL). The+ // toolkit→auth-config mapping is NOT configured here — it is resolved+ // dynamically from the project's /auth_configs at request time, so enabling+ // a toolkit is a dashboard action, not a redeploy. State signing uses+ // COMPOSIO_STATE_SECRET, or a key derived from JWT_SECRET when that is unset.+ if composioAPIKey := strings.TrimSpace(os.Getenv("COMPOSIO_API_KEY")); composioAPIKey != "" {+ if !featureflags.ComposioMCPAppsEnabled(context.Background(), opts.FeatureFlags) {+ slog.Info("composio integration disabled (feature flag off)")+ } else {+ sdkClient, err := composiosdk.NewClient(composiosdk.Options{APIKey: composioAPIKey})+ if err != nil {+ slog.Error("composio: SDK client init failed; composio integration disabled", "error", err)+ } else {+ stateSecret := composioStateSecret()+ callbackBase := composioCallbackBaseURL(signupConfig.PublicURL)+ switch {+ case len(stateSecret) == 0:+ slog.Error("composio: no state secret (set COMPOSIO_STATE_SECRET or JWT_SECRET); composio integration disabled")+ case callbackBase == "":+ slog.Error("composio: no callback base url (set COMPOSIO_CALLBACK_BASE_URL or MULTICA_PUBLIC_URL); composio integration disabled")+ default:+ svc, serr := composiointeg.NewService(sdkClient, queries, composiointeg.Config{+ StateSecret: stateSecret,+ CallbackBaseURL: callbackBase,+ FrontendBaseURL: appURLFromEnv(),+ })+ if serr != nil {+ slog.Error("composio: service init failed; composio integration disabled", "error", serr)+ } else {+ h.Composio = svc+ // Stage 3 (MUL-3721) hook: feed the per-task MCP+ // overlay builder into TaskService so every Enqueue*+ // path attaches the initiator user's Composio session+ // URL to the task row before the daemon claims it.+ // taskSvc already exists by this point — it was+ // constructed inside NewHandler — and exposes its+ // Composio field for exactly this kind of late wiring,+ // so no Handler-level mutation is needed.+ if h.TaskService != nil {+ h.TaskService.Composio = svc+ }+ slog.Info("composio integration enabled")+ }+ }+ }+ }+ } else {+ slog.Info("composio integration disabled (COMPOSIO_API_KEY not set)")+ }+if opts.HeartbeatScheduler != nil {h.HeartbeatScheduler = opts.HeartbeatScheduler}@@ -644,6 +707,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// HandleCloudBillingStripeWebhook for the rationale).r.Post("/api/webhooks/stripe", h.HandleCloudBillingStripeWebhook)+ // Composio OAuth callback (MUL-3843). NOT under the Auth group on purpose:+ // Composio 302-redirects the user's browser here at the end of the OAuth+ // flow, and the cookie session is frequently absent (expired session,+ // SameSite=Strict / Safari ITP stripping cross-site cookies, private+ // windows, self-hosted callbacks on a different subdomain). Identity is NOT+ // taken from the session — it comes from the HMAC-signed `state` query+ // param, which CompleteCallback verifies (signature, expiry, replay) before+ // doing anything. h.Composio == nil still returns 503. Keeping it inside the+ // Auth group made a missing cookie a hard 401, breaking the flow for exactly+ // the browsers above; the other four composio endpoints stay session-gated.+ r.Get("/api/integrations/composio/callback", h.ComposioCallback)+// Daemon API routes (require daemon token or valid user token)r.Route("/api/daemon", func(r chi.Router) {r.Use(middleware.DaemonAuth(queries, patCache, daemonTokenCache, cloudPATVerifier))@@ -822,6 +897,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// carries.r.Post("/api/slack/binding/redeem", h.RedeemSlackBindingToken)+ // Composio integration (MUL-3720). User-scoped (no workspace context):+ // a connection belongs to a user. These four require a logged-in+ // session; the OAuth callback is the outlier and lives outside the Auth+ // group (registered above with the other public OAuth/webhook routes —+ // see MUL-3843). All return 503 when COMPOSIO_API_KEY is unset.+ r.Route("/api/integrations/composio", func(r chi.Router) {+ r.Post("/connect/init", h.ComposioConnectInit)+ r.Get("/toolkits", h.ListComposioToolkits)+ r.Get("/connections", h.ListComposioConnections)+ r.Delete("/connections/{id}", h.DeleteComposioConnection)+ })+// User-scoped invitation routes (no workspace context required)r.Get("/api/invitations", h.ListMyInvitations)r.Get("/api/invitations/{id}", h.GetMyInvitation)@@ -1354,3 +1441,31 @@ func cloudRuntimeFleetURLFromEnv() string {}return strings.TrimSpace(os.Getenv("MULTICA_FLEET_URL"))}++// composioStateSecret resolves the HMAC key for the connect-state. Prefers an+// explicit COMPOSIO_STATE_SECRET; otherwise derives a composio-specific key+// from JWT_SECRET via SHA-256 so the two signing domains never share an+// identical key. Returns nil when neither is set (composio stays disabled).+func composioStateSecret() []byte {+ if v := strings.TrimSpace(os.Getenv("COMPOSIO_STATE_SECRET")); v != "" {+ return []byte(v)+ }+ if v := strings.TrimSpace(os.Getenv("JWT_SECRET")); v != "" {+ sum := sha256.Sum256([]byte("composio-state:" + v))+ return sum[:]+ }+ return nil+}++// composioCallbackBaseURL resolves the public API base used to build the+// Composio callback URL. Prefers COMPOSIO_CALLBACK_BASE_URL, then the+// already-resolved MULTICA_PUBLIC_URL, then the app URL.+func composioCallbackBaseURL(publicURL string) string {+ if v := strings.TrimRight(strings.TrimSpace(os.Getenv("COMPOSIO_CALLBACK_BASE_URL")), "/"); v != "" {+ return v+ }+ if publicURL != "" {+ return publicURL+ }+ return appURLFromEnv()+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 7e11d0ad14..0696fc04f7 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -3543,6 +3543,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iInitiatorName: task.InitiatorName,InitiatorEmail: task.InitiatorEmail,WorkspaceContext: task.WorkspaceContext,+ ConnectedApps: task.ConnectedApps,}// Mark candidate env roots as active before any env work so the GC loopdiff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 20e1832ec8..f565bcc214 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -10,6 +10,8 @@ import ("os""path/filepath""time"++ "github.com/multica-ai/multica/server/internal/runtimeapps")// RepoContextForEnv describes a workspace repo available for checkout.@@ -93,6 +95,10 @@ type TaskContextForEnv struct {// non-empty so every agent in the workspace sees the same shared context,// regardless of issue / chat / autopilot / quick-create.WorkspaceContext string+ // ConnectedApps lists per-run external app capabilities mounted through+ // MCP overlays. Rendered briefly so the agent can map app names such as+ // Notion to the actual MCP server name (`composio`).+ ConnectedApps []runtimeapps.ConnectedApp// RequestingUserName + RequestingUserProfileDescription describe the// human the agent is acting on behalf of. v1 sources them from the// runtime owner (the user who registered the daemon). Rendered into thediff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex 3ca31bca7a..68614080d3 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -494,6 +494,7 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {b.WriteString(ctxText)b.WriteString("\n\n")}+ writeConnectedApps(&b, ctx)b.WriteString("## Available Commands\n\n")b.WriteString("**Use `--output json` for structured data.** Human table output now prints routable issue keys (for example `MUL-123`) and short UUID prefixes for workspace resources; use `--full-id` on list commands when you need canonical UUIDs.\n\n")diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 6742ea264f..2d5529ee8a 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -3,6 +3,8 @@ package execenvimport ("fmt""strings"++ "github.com/multica-ai/multica/server/internal/runtimeapps")// This file holds the slim runtime brief — the post-MUL-3560 path that@@ -136,6 +138,48 @@ func writeWorkspaceContext(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("\n\n")}+func writeConnectedApps(b *strings.Builder, ctx TaskContextForEnv) {+ if len(ctx.ConnectedApps) == 0 {+ return+ }+ var lines strings.Builder+ for _, app := range ctx.ConnectedApps {+ serverName := sanitizeBriefCodeToken(app.ServerName)+ toolkitSlug := sanitizeBriefCodeToken(app.ToolkitSlug)+ if serverName == "" || toolkitSlug == "" {+ continue+ }+ name := sanitizeNameForBriefMarkdown(app.ToolkitName)+ if name == "" {+ name = sanitizeNameForBriefMarkdown(runtimeapps.DisplayNameForToolkitSlug(toolkitSlug))+ }+ if name == "" {+ name = toolkitSlug+ }+ fmt.Fprintf(&lines, "- %s (`%s`) via MCP server `%s`\n", name, toolkitSlug, serverName)+ }+ if lines.Len() == 0 {+ return+ }+ b.WriteString("## Connected Apps\n\n")+ b.WriteString(lines.String())+ b.WriteString("\nUse the listed MCP server when the task asks to read or act in one of these apps.\n\n")+}++func sanitizeBriefCodeToken(s string) string {+ s = strings.TrimSpace(s)+ if s == "" {+ return ""+ }+ for _, r := range s {+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == '.' {+ continue+ }+ return ""+ }+ return s+}+// writeAvailableCommands emits the slim Available Commands section// (~2.4k chars vs legacy ~4.4k). Every test-asserted substring is// preserved: each `multica issue …` command name, all three `comment add`@@ -465,9 +509,9 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {// Attachments | ✓ | ✓ | — | — | —//// Always-on rows — Header, Background Task Safety, Agent Identity,-// Requesting User, Task Initiator, Workspace Context, Workflow, Always-// Use CLI, Output — are shared by every kind and emitted unconditionally-// (or gated by their own data preconditions).+// Requesting User, Task Initiator, Workspace Context, Connected Apps,+// Workflow, Always Use CLI, Output — are shared by every kind and emitted+// unconditionally (or gated by their own data preconditions).func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {var b strings.Builderkind := classifyTask(ctx)@@ -478,6 +522,7 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {writeRequestingUser(&b, ctx)writeTaskInitiator(&b, ctx)writeWorkspaceContext(&b, ctx)+ writeConnectedApps(&b, ctx)switch kind {case kindQuickCreate:diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex 275ca43e68..65ad446490 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -6,6 +6,8 @@ import ("path/filepath""strings""testing"++ "github.com/multica-ai/multica/server/internal/runtimeapps")// Sub-issue Creation section — after MUL-2538 the platform posts the@@ -550,6 +552,52 @@ func TestWorkspaceContextHeadingSkippedWhenEmpty(t *testing.T) {}}+func TestConnectedAppsRenderedAcrossBriefModes(t *testing.T) {+ ctx := TaskContextForEnv{+ IssueID: "11111111-2222-3333-4444-555555555555",+ WorkspaceContext: "Prefer source-of-truth systems.",+ ConnectedApps: []runtimeapps.ConnectedApp{{+ Provider: "composio",+ ServerName: "composio",+ ToolkitSlug: "notion",+ ToolkitName: "Notion",+ }},+ }++ run := func(t *testing.T, label string) {+ out := buildMetaSkillContent("claude", ctx)+ for _, want := range []string{+ "## Connected Apps",+ "- Notion (`notion`) via MCP server `composio`",+ "Use the listed MCP server when the task asks to read or act in one of these apps.",+ } {+ if !strings.Contains(out, want) {+ t.Fatalf("%s brief missing connected app text %q\n---\n%s", label, want, out)+ }+ }+ wsIdx := strings.Index(out, "## Workspace Context")+ appIdx := strings.Index(out, "## Connected Apps")+ cmdIdx := strings.Index(out, "## Available Commands")+ if wsIdx == -1 || appIdx == -1 || cmdIdx == -1 || !(wsIdx < appIdx && appIdx < cmdIdx) {+ t.Fatalf("%s connected apps should sit between workspace context and available commands (ws=%d app=%d cmd=%d)", label, wsIdx, appIdx, cmdIdx)+ }+ }++ t.Run("legacy", func(t *testing.T) { run(t, "legacy") })+ t.Run("slim", func(t *testing.T) {+ withSlimBrief(t)+ run(t, "slim")+ })+}++func TestConnectedAppsHeadingSkippedWhenEmpty(t *testing.T) {+ t.Parallel()+ out := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: "11111111-2222-3333-4444-555555555555"})+ if strings.Contains(out, "## Connected Apps") {+ t.Fatalf("empty connected apps must not emit the heading")+ }+}+func TestSubIssueCreationSectionSkippedForNonIssueModes(t *testing.T) {t.Parallel()cases := []struct {diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 5fd309d8b8..20fe7987ab 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -1,6 +1,10 @@package daemon-import "encoding/json"+import (+ "encoding/json"++ "github.com/multica-ai/multica/server/internal/runtimeapps"+)// AgentEntry describes a single available agent CLI.type AgentEntry struct {@@ -38,6 +42,10 @@ type ProjectResourceData struct {Label string `json:"label,omitempty"`}+// ConnectedAppData keeps the claim-response field local to daemon types while+// sharing the canonical JSON shape with the runtime app metadata package.+type ConnectedAppData = runtimeapps.ConnectedApp+// Task represents a claimed task from the server.// Agent data (name, skills) is populated by the claim endpoint.type Task struct {@@ -53,6 +61,7 @@ type Task struct {WorkspaceContext string `json:"workspace_context,omitempty"`ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread historyAgent *AgentData `json:"agent,omitempty"`+ ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // per-run app capabilities mounted through runtime MCP overlaysRepos []RepoData `json:"repos,omitempty"`ProjectID string `json:"project_id,omitempty"` // issue's project, when presentProjectTitle string `json:"project_title,omitempty"` // human-readable project title for context injectiondiff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.gonew file mode 100644index 0000000000..b2928a9cd9--- /dev/null+++ b/server/internal/featureflags/keys.go@@ -0,0 +1,29 @@+package featureflags++import (+ "context"++ "github.com/multica-ai/multica/server/pkg/featureflag"+)++const (+ // ComposioMCPApps gates the Composio app management UI and runtime MCP+ // overlay injection.+ ComposioMCPApps = "composio_mcp_apps"+)++var frontendPublicFlags = []string{+ ComposioMCPApps,+}++func ComposioMCPAppsEnabled(ctx context.Context, flags *featureflag.Service) bool {+ return flags.IsEnabled(ctx, ComposioMCPApps, false)+}++func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {+ out := make(map[string]bool, len(frontendPublicFlags))+ for _, key := range frontendPublicFlags {+ out[key] = flags.IsEnabled(ctx, key, false)+ }+ return out+}diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex d31b55de20..6277d6956c 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -19,6 +19,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/runtimeapps""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -50,23 +51,45 @@ type AgentResponse struct {// across the API surface. Reading values requires the dedicated, audited// `GET /api/agents/{id}/env` endpoint; writing requires `PUT` to the// same path. agent-actor tokens are denied there. See MUL-2600.- HasCustomEnv bool `json:"has_custom_env"`- CustomEnvKeyCount int `json:"custom_env_key_count"`- McpConfigRedacted bool `json:"mcp_config_redacted"`- Visibility string `json:"visibility"`- Status string `json:"status"`- MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`- Model string `json:"model"`+ HasCustomEnv bool `json:"has_custom_env"`+ CustomEnvKeyCount int `json:"custom_env_key_count"`+ McpConfigRedacted bool `json:"mcp_config_redacted"`+ Visibility string `json:"visibility"`+ // PermissionMode is the invocation-permission mode (MUL-3963):+ // "private" (owner only) or "public_to" (allow-list in InvocationTargets).+ // Replaces Visibility as the authorization source; Visibility is kept as a+ // derived legacy field so old clients never see a permission widening.+ PermissionMode string `json:"permission_mode"`+ // InvocationTargets is the allow-list for a public_to agent. Empty for+ // private agents. Only populated on the detail / list / create / update+ // responses that load it; broadcast payloads leave it empty.+ InvocationTargets []AgentInvocationTargetDTO `json:"invocation_targets"`+ Status string `json:"status"`+ MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`+ Model string `json:"model"`// ThinkingLevel is the runtime-native reasoning/effort token persisted// for this agent (empty = use runtime default). The picker is per-runtime// per-model; the API never normalizes across providers. See MUL-2339.- ThinkingLevel string `json:"thinking_level"`- OwnerID *string `json:"owner_id"`- Skills []AgentSkillSummary `json:"skills"`- CreatedAt string `json:"created_at"`- UpdatedAt string `json:"updated_at"`- ArchivedAt *string `json:"archived_at"`- ArchivedBy *string `json:"archived_by"`+ ThinkingLevel string `json:"thinking_level"`+ // ComposioToolkitAllowlist is the subset of Composio toolkit slugs this+ // agent is allowed to mount as MCP at task dispatch — for ANY run that+ // passes the agent's invocation permission, using the agent OWNER's+ // Composio connection (MUL-3963; no longer gated on originator == owner).+ // NULL or empty = no overlay. Like mcp_config, this is+ // owner-only data: the slugs themselves are not secret, but the+ // "this is what {agent owner} is willing to surface" view is — surfacing+ // it cross-account is privacy-confusing UX and would let workspace+ // members infer another member's integration footprint. Redacted to+ // `nil` + `composio_toolkit_allowlist_redacted=true` for non-owners,+ // mirroring the existing mcp_config redaction contract.+ ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist,omitempty"`+ ComposioToolkitAllowlistRedacted bool `json:"composio_toolkit_allowlist_redacted,omitempty"`+ OwnerID *string `json:"owner_id"`+ Skills []AgentSkillSummary `json:"skills"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+ ArchivedAt *string `json:"archived_at"`+ ArchivedBy *string `json:"archived_by"`}// runtimeConfigGatewayTokenMask is the placeholder the API substitutes for@@ -117,31 +140,43 @@ func agentToResponse(a db.Agent) AgentResponse {mcpConfig = json.RawMessage(a.McpConfig)}+ // composio_toolkit_allowlist: the column is stored as TEXT[] and arrives+ // here as a []string (sqlc). NULL and `{}` both serialize as nil through+ // the postgres driver — both correctly mean "no toolkits", but the API+ // surface keeps them distinguishable from "owner has not opened the+ // integration yet" only via the trio (slice nil / slice empty / slice+ // non-empty). We hand the slice through verbatim so the redaction ++ // owner-only gate below can decide.+ composioAllowlist := a.ComposioToolkitAllowlist+return AgentResponse{- ID: uuidToString(a.ID),- WorkspaceID: uuidToString(a.WorkspaceID),- RuntimeID: uuidToString(a.RuntimeID),- Name: a.Name,- Description: a.Description,- Instructions: a.Instructions,- AvatarURL: textToPtr(a.AvatarUrl),- RuntimeMode: a.RuntimeMode,- RuntimeConfig: rc,- CustomArgs: customArgs,- McpConfig: mcpConfig,- HasCustomEnv: envKeyCount > 0,- CustomEnvKeyCount: envKeyCount,- Visibility: a.Visibility,- Status: a.Status,- MaxConcurrentTasks: a.MaxConcurrentTasks,- Model: a.Model.String,- ThinkingLevel: a.ThinkingLevel.String,- OwnerID: uuidToPtr(a.OwnerID),- Skills: []AgentSkillSummary{},- CreatedAt: timestampToString(a.CreatedAt),- UpdatedAt: timestampToString(a.UpdatedAt),- ArchivedAt: timestampToPtr(a.ArchivedAt),- ArchivedBy: uuidToPtr(a.ArchivedBy),+ ID: uuidToString(a.ID),+ WorkspaceID: uuidToString(a.WorkspaceID),+ RuntimeID: uuidToString(a.RuntimeID),+ Name: a.Name,+ Description: a.Description,+ Instructions: a.Instructions,+ AvatarURL: textToPtr(a.AvatarUrl),+ RuntimeMode: a.RuntimeMode,+ RuntimeConfig: rc,+ CustomArgs: customArgs,+ McpConfig: mcpConfig,+ HasCustomEnv: envKeyCount > 0,+ CustomEnvKeyCount: envKeyCount,+ Visibility: a.Visibility,+ PermissionMode: a.PermissionMode,+ InvocationTargets: []AgentInvocationTargetDTO{},+ Status: a.Status,+ MaxConcurrentTasks: a.MaxConcurrentTasks,+ Model: a.Model.String,+ ThinkingLevel: a.ThinkingLevel.String,+ ComposioToolkitAllowlist: composioAllowlist,+ OwnerID: uuidToPtr(a.OwnerID),+ Skills: []AgentSkillSummary{},+ CreatedAt: timestampToString(a.CreatedAt),+ UpdatedAt: timestampToString(a.UpdatedAt),+ ArchivedAt: timestampToPtr(a.ArchivedAt),+ ArchivedBy: uuidToPtr(a.ArchivedBy),}}@@ -223,6 +258,10 @@ type ProjectResourceData struct {Label string `json:"label,omitempty"`}+// ConnectedAppData keeps the daemon-claim wire field local to handler types+// while sharing the canonical JSON shape with the runtime app metadata package.+type ConnectedAppData = runtimeapps.ConnectedApp+type AgentTaskResponse struct {ID string `json:"id"`AgentID string `json:"agent_id"`@@ -248,6 +287,7 @@ type AgentTaskResponse struct {MaxAttempts int32 `json:"max_attempts"`ParentTaskID *string `json:"parent_task_id,omitempty"`Agent *TaskAgentData `json:"agent,omitempty"`+ ConnectedApps []ConnectedAppData `json:"connected_apps,omitempty"` // daemon-claim only: per-run app capabilities mounted through runtime MCP overlaysRepos []RepoData `json:"repos,omitempty"`ProjectID string `json:"project_id,omitempty"` // issue's project, when presentProjectTitle string `json:"project_title,omitempty"` // for surfacing in agent context@@ -589,18 +629,27 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {}alwaysRedact := workspaceAlwaysRedactSecrets(ws.Settings)- // Resolve the request actor once. Agents bypass the private-agent gate- // to preserve A2A collaboration; members must be in allowed_principals- // (agent owner or workspace owner/admin) to see private agents.+ // Resolve the request actor once. Agents bypass the view gate to preserve+ // A2A collaboration; members see a private agent only when they own it or+ // are workspace owner/admin, and a public_to agent only when on its+ // invocation allow-list. Targets are batch-loaded to avoid an N+1 and+ // reused to enrich each response's invocation_targets.actorType, actorID := h.resolveActor(r, userID, workspaceID)+ targetsByAgent, ok := h.loadInvocationTargetsByAgent(r.Context(), agents)+ if !ok {+ writeError(w, http.StatusInternalServerError, "failed to load agent invocation targets")+ return+ }visible := make([]AgentResponse, 0, len(agents))for _, a := range agents {- if a.Visibility == "private" && actorType == "member" {- if !memberAllowedForPrivateAgent(a, actorID, member.Role) {+ targets := targetsByAgent[uuidToString(a.ID)]+ if actorType == "member" {+ if !memberAllowedToViewAgent(a, targets, actorID, member.Role) {continue}}resp := agentToResponse(a)+ applyInvocationTargetsToResponse(&resp, targets)if skills, ok := skillMap[resp.ID]; ok {resp.Skills = skills}@@ -612,6 +661,20 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {if actorType == "agent" || alwaysRedact || !canViewAgentSecrets(a, userID, member.Role) {redactMcpConfig(&resp)}+ // composio_toolkit_allowlist is owner-only — not because the slugs+ // are secret but because surfacing "what {owner} has opted into"+ // across the workspace leaks the owner's integration footprint and+ // confuses non-owners who cannot actually edit it. Workspace+ // owner/admin do NOT bypass this gate (unlike mcp_config): the overlay+ // uses the OWNER's connection and follows invocation permission+ // (MUL-3963), so surfacing the slugs to admins gives them nothing+ // actionable. Agent actors are also redacted (same A2A+ // lateral-movement reasoning as mcp_config).+ if !h.composioMCPAppsEnabled(r.Context()) {+ suppressComposioToolkitAllowlist(&resp)+ } else if actorType == "agent" || uuidToString(a.OwnerID) != userID {+ redactComposioToolkitAllowlist(&resp)+ }visible = append(visible, resp)}@@ -635,6 +698,9 @@ func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {return}resp := agentToResponse(agent)+ if !h.enrichAgentResponseWithTargetsHTTP(w, r, &resp, agent.ID) {+ return+ }// Use the summary query (no `content` column) — the embedded// AgentSkillSummary only needs id/name/description, and reading large// SKILL.md bodies just to discard them is the exact regression we fixed@@ -662,24 +728,45 @@ func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {redactMcpConfig(&resp)}}+ // composio_toolkit_allowlist visibility is strictly owner-only (see+ // ListAgents for the rationale). No workspace owner/admin bypass.+ if !h.composioMCPAppsEnabled(r.Context()) {+ suppressComposioToolkitAllowlist(&resp)+ } else if actorType == "agent" || uuidToString(agent.OwnerID) != userID {+ redactComposioToolkitAllowlist(&resp)+ }writeJSON(w, http.StatusOK, resp)}type CreateAgentRequest struct {- Name string `json:"name"`- Description string `json:"description"`- Instructions string `json:"instructions"`- AvatarURL *string `json:"avatar_url"`- RuntimeID string `json:"runtime_id"`- RuntimeConfig any `json:"runtime_config"`- CustomEnv map[string]string `json:"custom_env"`- CustomArgs []string `json:"custom_args"`- McpConfig json.RawMessage `json:"mcp_config"`- Visibility string `json:"visibility"`- MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`- Model string `json:"model"`- ThinkingLevel string `json:"thinking_level"`+ Name string `json:"name"`+ Description string `json:"description"`+ Instructions string `json:"instructions"`+ AvatarURL *string `json:"avatar_url"`+ RuntimeID string `json:"runtime_id"`+ RuntimeConfig any `json:"runtime_config"`+ CustomEnv map[string]string `json:"custom_env"`+ CustomArgs []string `json:"custom_args"`+ McpConfig json.RawMessage `json:"mcp_config"`+ Visibility string `json:"visibility"`+ // PermissionMode + InvocationTargets are the new invocation-permission+ // inputs (MUL-3963). When permission_mode is present it is authoritative+ // and Visibility is ignored; when absent, legacy Visibility is mapped+ // (private -> private, workspace -> public_to+workspace target). On create+ // only the caller can be the owner, so targets are accepted unconditionally.+ PermissionMode *string `json:"permission_mode"`+ InvocationTargets []AgentInvocationTargetDTO `json:"invocation_targets"`+ MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`+ Model string `json:"model"`+ ThinkingLevel string `json:"thinking_level"`+ // ComposioToolkitAllowlist seeds the per-task overlay gate (MUL-3869). On+ // create only the calling user can be the owner, so we accept the field+ // unconditionally here; the cross-owner permission gate lives on PUT.+ // Nil = leave column NULL (no overlay). Empty slice = explicit `{}` (no+ // overlay either, but the column reads as "configured" — distinct from+ // "owner has never opened the integration").+ ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist"`// Template records which template slug was used to seed this agent// (e.g. "coding" / "planning" / "writing" / "assistant"). Empty when// the caller didn't come from a template picker — the `agent_created`@@ -752,6 +839,17 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {return}+ // Resolve invocation permission (MUL-3963). permission_mode is+ // authoritative when present; otherwise the legacy visibility value is+ // mapped. On create the caller is always the owner, so targets are+ // accepted unconditionally.+ _, hasTargets := rawFields["invocation_targets"]+ legacyVis := req.Visibility+ perm, _, permErr := parsePermissionInput(wsUUID, req.PermissionMode, req.InvocationTargets, req.PermissionMode != nil, hasTargets, &legacyVis)+ if permErr != nil {+ writeError(w, http.StatusBadRequest, permErr.Error())+ return+ }runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{ID: runtimeUUID,WorkspaceID: wsUUID,@@ -813,23 +911,36 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {mc = append([]byte(nil), rawMcpConfig...)}+ // composio_toolkit_allowlist: the JSON field is a list-of-slugs that gets+ // stored as TEXT[]. We normalise here (lowercase + trim + dedupe) so the+ // dispatch path can compare against per-user connection rows with a+ // straight equality. A nil slice (or absent JSON key) maps to a NULL+ // column on insert. An explicitly empty list (`[]`) is preserved as an+ // empty TEXT[] (the dispatch path treats NULL and `{}` identically).+ allowlist := normaliseComposioToolkitAllowlist(req.ComposioToolkitAllowlist)+ if !h.composioMCPAppsEnabled(r.Context()) {+ allowlist = nil+ }+created, err := h.Queries.CreateAgent(r.Context(), db.CreateAgentParams{- WorkspaceID: wsUUID,- Name: req.Name,- Description: req.Description,- Instructions: req.Instructions,- AvatarUrl: ptrToText(req.AvatarURL),- RuntimeMode: runtime.RuntimeMode,- RuntimeConfig: rc,- RuntimeID: runtime.ID,- Visibility: req.Visibility,- MaxConcurrentTasks: req.MaxConcurrentTasks,- OwnerID: parseUUID(ownerID),- CustomEnv: ce,- CustomArgs: ca,- McpConfig: mc,- Model: pgtype.Text{String: req.Model, Valid: req.Model != ""},- ThinkingLevel: pgtype.Text{String: req.ThinkingLevel, Valid: req.ThinkingLevel != ""},+ WorkspaceID: wsUUID,+ Name: req.Name,+ Description: req.Description,+ Instructions: req.Instructions,+ AvatarUrl: ptrToText(req.AvatarURL),+ RuntimeMode: runtime.RuntimeMode,+ RuntimeConfig: rc,+ RuntimeID: runtime.ID,+ Visibility: perm.legacyVisibility(),+ PermissionMode: perm.mode,+ MaxConcurrentTasks: req.MaxConcurrentTasks,+ OwnerID: parseUUID(ownerID),+ CustomEnv: ce,+ CustomArgs: ca,+ McpConfig: mc,+ Model: pgtype.Text{String: req.Model, Valid: req.Model != ""},+ ThinkingLevel: pgtype.Text{String: req.ThinkingLevel, Valid: req.ThinkingLevel != ""},+ ComposioToolkitAllowlist: allowlist,})if err != nil {// Unique constraint on (workspace_id, name) — return a clear conflict error@@ -845,12 +956,22 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {}slog.Info("agent created", append(logger.RequestAttrs(r), "agent_id", uuidToString(created.ID), "name", created.Name, "workspace_id", workspaceID)...)+ // Persist the invocation allow-list (MUL-3963). Best-effort log on failure+ // but do not fail the create — the agent row already exists and defaults+ // to no targets (deny-by-default private).+ if err := h.replaceInvocationTargets(r.Context(), created.ID, parseUUID(ownerID), perm.targets); err != nil {+ slog.Warn("create agent: persist invocation targets failed", append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(created.ID))...)+ }+if runtime.Status == "online" {h.TaskService.ReconcileAgentStatus(r.Context(), created.ID)created, _ = h.Queries.GetAgent(r.Context(), created.ID)}resp := agentToResponse(created)+ if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, created.ID); err != nil {+ slog.Warn("create agent: load invocation targets for response failed", append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(created.ID))...)+ }actorType, actorID := h.resolveActor(r, ownerID, workspaceID)h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})@@ -865,6 +986,9 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {))redactAgentResponseForActor(&resp, actorType)+ if !h.composioMCPAppsEnabled(r.Context()) {+ suppressComposioToolkitAllowlist(&resp)+ }writeJSON(w, http.StatusCreated, resp)}@@ -884,12 +1008,20 @@ type UpdateAgentRequest struct {// actually unchanged, and so a client that round-tripped a// previously-returned masked map cannot silently overwrite real// secret values with literal `****`. See MUL-2600.- CustomArgs *[]string `json:"custom_args"`- McpConfig *json.RawMessage `json:"mcp_config"`- Visibility *string `json:"visibility"`- Status *string `json:"status"`- MaxConcurrentTasks *int32 `json:"max_concurrent_tasks"`- Model *string `json:"model"`+ CustomArgs *[]string `json:"custom_args"`+ McpConfig *json.RawMessage `json:"mcp_config"`+ Visibility *string `json:"visibility"`+ // PermissionMode + InvocationTargets are the invocation-permission inputs+ // (MUL-3963). Owner-only writes (like composio_toolkit_allowlist): a+ // non-owner admin passing them is silently ignored, because the invoke+ // gate is owner/allow-list based and an admin-authored allow-list would+ // confuse the owner about who can run their agent. permission_mode is+ // authoritative when present; otherwise legacy visibility is mapped.+ PermissionMode *string `json:"permission_mode"`+ InvocationTargets *[]AgentInvocationTargetDTO `json:"invocation_targets"`+ Status *string `json:"status"`+ MaxConcurrentTasks *int32 `json:"max_concurrent_tasks"`+ Model *string `json:"model"`// ThinkingLevel is treated as a tri-state per-MUL-2339:// - field omitted → no change (leave existing value alone)// - field present with "" → explicit clear (use runtime default)@@ -897,6 +1029,16 @@ type UpdateAgentRequest struct {// Distinguishing those modes is why this is a pointer; the raw-fields// map captured at decode time tells us whether the key was sent.ThinkingLevel *string `json:"thinking_level"`+ // ComposioToolkitAllowlist is a tri-state, same pattern as+ // thinking_level, mcp_config:+ // - field omitted → no change (column preserved as-is)+ // - field present with null → explicit clear (ClearAgent... query)+ // - field present with [] → store empty TEXT[] (configured, no toolkits)+ // - field present with non-empty → store deduped lowercase slugs+ // The decode-time raw fields map disambiguates "omitted" from "explicit+ // null" (a *[]string can't, because a nil pointer is the same wire+ // representation as both). MUL-3869.+ ComposioToolkitAllowlist *[]string `json:"composio_toolkit_allowlist"`}// workspaceAlwaysRedactSecrets reports whether the workspace has opted@@ -944,9 +1086,17 @@ func canViewAgentSecrets(agent db.Agent, userID string, memberRole string) bool// redaction in ListAgents / GetAgent. The caller still receives the// canonical form in the HTTP response; only the broadcast copy is// redacted.+//+// composio_toolkit_allowlist follows the same fan-out rule: every+// workspace member subscribes to agent:created/updated/archived, so+// a non-redacted broadcast would leak the agent owner's per-toolkit+// allowlist to every member regardless of whether they would have+// been allowed to read it via GET. Redact unconditionally on the+// broadcast copy.func broadcastAgentResponse(resp AgentResponse) AgentResponse {out := respredactMcpConfig(&out)+ redactComposioToolkitAllowlist(&out)// Belt-and-suspenders: agentToResponse already masks gateway.token on// every read, so by the time a response reaches this broadcast helper// the field is already "***". Re-mask anyway so a future refactor that@@ -967,6 +1117,66 @@ func redactMcpConfig(resp *AgentResponse) {}}+// redactComposioToolkitAllowlist removes the composio_toolkit_allowlist+// value from the response when the caller is not the agent owner. The slug+// list itself is not secret, but the "what {agent owner} has opted into"+// view leaks the owner's integration footprint across the workspace, which+// is the same privacy concern that gates mcp_config visibility behind+// owner-only canViewAgentSecrets. We surface a coarse `_redacted` flag so+// the front-end can render "Configured" without the contents (parity with+// mcp_config_redacted). The clearing matters: the JSON `omitempty` only+// drops nil slices, so reset to nil rather than `[]string{}`.+func redactComposioToolkitAllowlist(resp *AgentResponse) {+ if resp.ComposioToolkitAllowlist != nil {+ resp.ComposioToolkitAllowlist = nil+ resp.ComposioToolkitAllowlistRedacted = true+ }+}++func suppressComposioToolkitAllowlist(resp *AgentResponse) {+ resp.ComposioToolkitAllowlist = nil+ resp.ComposioToolkitAllowlistRedacted = false+}++// normaliseComposioToolkitAllowlist canonicalises an incoming allowlist+// payload before persisting. Each slug is trimmed + lowercased so the+// dispatch path (which compares against user_composio_connection.toolkit_slug,+// stored lowercased by the Composio service) does a flat string match+// without needing a CITEXT or per-query LOWER(). Empty / whitespace-only+// strings are dropped and duplicates collapsed so a sloppy UI payload+// can't waste DB row-length or surface twice in the response.+//+// Contract:+// - nil in → nil out: "field absent / explicit null" preserved. Combined+// with sqlc.narg('composio_toolkit_allowlist')::text[] in UpdateAgent,+// this is what makes "omit field" mean "leave column alone".+// - empty slice in → empty slice out: "owner cleared all toolkits".+// Distinct from nil only at the column-NULL level; the dispatch path+// treats both identically as "no overlay".+// - non-empty in → trimmed, lowercased, deduped, stable order.+func normaliseComposioToolkitAllowlist(in []string) []string {+ if in == nil {+ return nil+ }+ if len(in) == 0 {+ return []string{}+ }+ seen := make(map[string]struct{}, len(in))+ out := make([]string, 0, len(in))+ for _, raw := range in {+ s := strings.ToLower(strings.TrimSpace(raw))+ if s == "" {+ continue+ }+ if _, dup := seen[s]; dup {+ continue+ }+ seen[s] = struct{}{}+ out = append(out, s)+ }+ return out+}+// redactAgentResponseForActor strips secret-bearing fields from an agent// resource HTTP response when the request actor is an agent. Read// handlers already gate on actorType — mutation handlers@@ -974,9 +1184,14 @@ func redactMcpConfig(resp *AgentResponse) {// an agent with a host owner/admin token can do an unrelated mutation// (e.g. flip max_concurrent_tasks) on a target agent and harvest the// target's mcp_config from the mutation response. MUL-2600.+//+// composio_toolkit_allowlist is redacted under the same logic: an agent+// runs with its host owner's PAT, so a mutation against a sibling agent+// could otherwise return the sibling owner's allowlist in the response.func redactAgentResponseForActor(resp *AgentResponse, actorType string) {if actorType == "agent" {redactMcpConfig(resp)+ redactComposioToolkitAllowlist(resp)}}@@ -1100,8 +1315,50 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {targetRuntimeID = runtime.IDtargetProvider = runtime.Provider}- if req.Visibility != nil {- params.Visibility = pgtype.Text{String: *req.Visibility, Valid: true}+ // Invocation permission (MUL-3963). OWNER-ONLY write: access is the one+ // agent property a workspace admin may NOT change (only the owner decides+ // who can run their agent — the overlay uses the owner's own Composio+ // connection, so admin-authored access would be confusing and unsafe).+ //+ // Non-owner behaviour: a *real* change is rejected with 403 so the contract+ // is explicit and matches the owner-only UI (the picker is read-only for+ // non-owners). A no-op resubmit — an admin editing OTHER fields via a+ // PATCH-as-PUT client that echoes the unchanged permission back — is+ // tolerated (dropped) so it doesn't break legitimate admin edits.+ _, hasPermissionMode := rawFields["permission_mode"]+ _, hasTargets := rawFields["invocation_targets"]+ permissionTouched := hasPermissionMode || hasTargets || req.Visibility != nil+ replacePermissionTargets := false+ var resolvedPerm resolvedPermission+ if permissionTouched {+ isAgentOwner := uuidToString(existing.OwnerID) == requestUserID(r)+ if !isAgentOwner {+ changed, permErr := h.permissionInputChangesAgent(r.Context(), existing, req, hasPermissionMode, hasTargets)+ if permErr != nil {+ writeError(w, http.StatusInternalServerError, "failed to evaluate invocation permission change")+ return+ }+ if changed {+ writeError(w, http.StatusForbidden, "only the agent owner can change access (permission_mode / invocation_targets)")+ return+ }+ slog.Debug("update agent: non-owner permission fields matched current state; ignored",+ append(logger.RequestAttrs(r), "agent_id", id)...)+ } else {+ var targetsDTO []AgentInvocationTargetDTO+ if req.InvocationTargets != nil {+ targetsDTO = *req.InvocationTargets+ }+ perm, _, permErr := parsePermissionInput(existing.WorkspaceID, req.PermissionMode, targetsDTO, hasPermissionMode, hasTargets, req.Visibility)+ if permErr != nil {+ writeError(w, http.StatusBadRequest, permErr.Error())+ return+ }+ resolvedPerm = perm+ replacePermissionTargets = true+ params.PermissionMode = pgtype.Text{String: perm.mode, Valid: true}+ params.Visibility = pgtype.Text{String: perm.legacyVisibility(), Valid: true}+ }}if req.Status != nil {params.Status = pgtype.Text{String: *req.Status, Valid: true}@@ -1182,6 +1439,43 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {}}+ // composio_toolkit_allowlist handling (MUL-3869). Tri-state semantics+ // mirror thinking_level (see above): omitted → no change, null →+ // ClearAgentComposioToolkitAllowlist, slice → wholesale replace.+ //+ // Owner-only WRITE. The caller is already past canManageAgent, which lets+ // workspace owner/admins through alongside the agent owner — but the+ // Composio overlay uses the agent OWNER's connection (MUL-3963), so an+ // admin editing someone else's allowlist would silently reshape what the+ // OWNER exposes through their own connected apps, confusing the owner+ // about what their agent surfaces. Keep it owner-only.+ // Drop the field with a debug log instead of erroring so an over-eager+ // UI that sends the whole agent payload back on every save (PATCH-as-PUT)+ // keeps working — same "silent ignore" stance the issue calls out, and+ // the same one mcp_config takes for the broader admin pattern.+ shouldClearComposioAllowlist := false+ if _, hasAllowlist := rawFields["composio_toolkit_allowlist"]; hasAllowlist {+ isAgentOwner := uuidToString(existing.OwnerID) == requestUserID(r)+ if !h.composioMCPAppsEnabled(r.Context()) {+ slog.Debug("update agent: composio_toolkit_allowlist write dropped because feature flag is disabled",+ append(logger.RequestAttrs(r), "agent_id", id)...)+ } else if !isAgentOwner {+ slog.Debug("update agent: composio_toolkit_allowlist write by non-owner silently dropped",+ append(logger.RequestAttrs(r), "agent_id", id)...)+ } else if req.ComposioToolkitAllowlist == nil {+ // JSON null → explicit clear via the dedicated query.+ shouldClearComposioAllowlist = true+ } else {+ // Normalise (trim/lowercase/dedupe). Empty slice is preserved as+ // an empty TEXT[] so the persisted value distinguishes "owner+ // cleared every toolkit" from "owner has never opened the+ // integration" (the dispatch path treats both as "no overlay"+ // either way, but the column tells UX whether to show a primed+ // vs empty picker).+ params.ComposioToolkitAllowlist = normaliseComposioToolkitAllowlist(*req.ComposioToolkitAllowlist)+ }+ }+updated, err := h.Queries.UpdateAgent(r.Context(), params)if err != nil {slog.Warn("update agent failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)@@ -1208,8 +1502,32 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {return}}+ if shouldClearComposioAllowlist {+ updated, err = h.Queries.ClearAgentComposioToolkitAllowlist(r.Context(), updated.ID)+ if err != nil {+ slog.Warn("clear agent composio_toolkit_allowlist failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)+ writeError(w, http.StatusInternalServerError, "failed to clear composio_toolkit_allowlist: "+err.Error())+ return+ }+ }++ // Invocation targets (MUL-3963): replace wholesale when the owner touched+ // permission. Done after the row update so a permission_mode flip and its+ // targets land together.+ if replacePermissionTargets {+ if err := h.replaceInvocationTargets(r.Context(), updated.ID, parseUUID(requestUserID(r)), resolvedPerm.targets); err != nil {+ slog.Warn("update agent: persist invocation targets failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)+ writeError(w, http.StatusInternalServerError, "failed to update invocation targets: "+err.Error())+ return+ }+ }resp := agentToResponse(updated)+ if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, updated.ID); err != nil {+ slog.Warn("update agent: load invocation targets for response failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)+ writeError(w, http.StatusInternalServerError, "failed to load agent invocation targets")+ return+ }// agentToResponse always initialises Skills as []; junction-table rows// are untouched by the SQL update, so we reload them here to keep the// response (and the broadcast that mirrors it) in sync with reality.@@ -1225,6 +1543,15 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {actorType, actorID := h.resolveActor(r, userID, uuidToString(updated.WorkspaceID))h.publish(protocol.EventAgentStatus, uuidToString(updated.WorkspaceID), actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})redactAgentResponseForActor(&resp, actorType)+ // Workspace admins / non-owner members pass canManageAgent for legitimate+ // admin actions (e.g. bulk reassigning agents off a leaving member's+ // runtime), but they must not learn the agent owner's composio allowlist+ // from the mutation response. See ListAgents/GetAgent for the same gate.+ if !h.composioMCPAppsEnabled(r.Context()) {+ suppressComposioToolkitAllowlist(&resp)+ } else if uuidToString(updated.OwnerID) != userID {+ redactComposioToolkitAllowlist(&resp)+ }writeJSON(w, http.StatusOK, resp)}diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.goindex 58cac9f181..53968c122e 100644--- a/server/internal/handler/agent_access.go+++ b/server/internal/handler/agent_access.go@@ -2,30 +2,122 @@ package handlerimport ("context"+ "net/http""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")-// canAccessPrivateAgent gates the four protected surfaces for private-// agents: chat / @-mention dispatch, viewing the agent's history, editing-// configuration, and deletion.+// Agent invocation permission model (MUL-3963).//-// Public agents are unrestricted — the predicate returns true unconditionally.+// Two distinct questions, previously conflated in canAccessPrivateAgent://-// Agent-to-agent traffic is always allowed (actorType == "agent"); this is-// what preserves A2A collaboration even with private agents. The trust-// boundary is at member↔agent, not agent↔agent.+// - "can this actor SEE / open this agent in the UI" -> canAccessPrivateAgent+// - "can this actor TRIGGER a run for this agent" -> canInvokeAgent//-// For members, the implicit allowed_principals set is computed inline as:-// {agent.owner_id} ∪ workspace owner/admin members. Manual configuration of-// allowed_principals is not exposed in v1; future work can extend this set-// without changing call sites.-func (h *Handler) canAccessPrivateAgent(ctx context.Context, agent db.Agent, actorType, actorID, workspaceID string) bool {- if agent.Visibility != "private" {+// The invoke gate is the security-critical one: a workspace admin must NOT be+// able to invoke someone's private agent (and thereby use that owner's+// Composio/OAuth connections) just because they are an admin. Admin retains+// management + inventory visibility, not the ability to run.+//+// permission_mode drives invoke:+// - private -> only the agent owner may invoke; NO admin bypass, NO A2A bypass.+// - public_to -> the agent_invocation_target allow-list decides:+// * workspace target -> any workspace member (and workspace-internal+// agent/system principals) may invoke.+// * member target -> only the specific user may invoke.+// * team target -> reserved, inert in V1.+//+// A2A is judged by the top-of-chain human originator, never by the immediate+// agent actor: if user U triggers agent A and A @-mentions agent B, B is only+// invocable when U (the originator) is in B's allow-list. This prevents agents+// from forming a channel that bypasses the owner's white-list.++// canInvokeAgent reports whether a run may be enqueued for `agent` on behalf of+// the given actor. Judgement is by the *effective invoking user*:+// - member actor -> the member themselves (actorID)+// - agent actor -> the top-of-chain human originator (originatorUserID)+// - system actor -> the originator when one was resolved, else no user+//+// originatorUserID is the empty string when no human could be attributed. For+// private agents that means "deny" (unless the actor is the owner). For+// public_to agents, a workspace target still admits workspace-internal+// agent/system principals, but member/team targets fail closed without a+// matching human.+func (h *Handler) canInvokeAgent(ctx context.Context, agent db.Agent, actorType, actorID, originatorUserID, workspaceID string) bool {+ effectiveUser := actorID+ if actorType != "member" {+ // agent / system: never trust the immediate principal, only the+ // resolved human originator at the top of the chain.+ effectiveUser = originatorUserID+ }++ // The agent owner may always invoke their own agent.+ if effectiveUser != "" && uuidToString(agent.OwnerID) == effectiveUser {return true}++ if agent.PermissionMode != "public_to" {+ // private (or any unknown mode) is deny-by-default: no admin bypass,+ // no A2A bypass. Only the owner branch above passes.+ return false+ }++ targets, err := h.Queries.ListAgentInvocationTargets(ctx, agent.ID)+ if err != nil {+ return false+ }++ // Agents and system triggers are workspace-internal principals: a+ // workspace target admits them even when no human originator resolved.+ // This is a DELIBERATE, product-approved exception (MUL-3963): webhook /+ // system / workspace-wide automation must be able to trigger a+ // `public_to workspace` agent even though there is no human at the top of+ // the chain. It is scoped tightly — it ONLY relaxes the *workspace* target.+ // member/team targets still require a resolved human originator to match,+ // so an unattributed agent/system trigger FAILS CLOSED against a+ // member-/team-scoped private-ish allow-list and can never smuggle itself+ // onto someone's specific-people grant.+ workspaceBroad := actorType == "agent" || actorType == "system"+ isWorkspaceMember := false+ if effectiveUser != "" {+ if _, err := h.getWorkspaceMember(ctx, effectiveUser, workspaceID); err == nil {+ isWorkspaceMember = true+ }+ }++ for _, t := range targets {+ switch t.TargetType {+ case "workspace":+ if isWorkspaceMember || workspaceBroad {+ return true+ }+ case "member":+ // Requires a resolved human. agent/system triggers with no+ // originator (effectiveUser == "") never match here — fail closed.+ if effectiveUser != "" && uuidToString(t.TargetID) == effectiveUser {+ return true+ }+ case "team":+ // Reserved: team membership does not exist yet in V1, so team+ // targets never admit anyone (also fail-closed for system/agent).+ }+ }+ return false+}++// canAccessPrivateAgent gates the VIEW surfaces (list/detail navigation, chat+// transcript read, task-cancel authorization). It is NOT the trigger gate —+// see canInvokeAgent for that.+//+// Rules:+// - agent actors always pass (A2A collaboration + inspection preserved).+// - the agent owner always passes.+// - workspace owner/admin pass (governance / inventory visibility retained).+// - a regular member passes for a public_to agent only when they hit a+// workspace or member target; private agents stay owner+admin only.+func (h *Handler) canAccessPrivateAgent(ctx context.Context, agent db.Agent, actorType, actorID, workspaceID string) bool {if actorType == "agent" {return true}@@ -36,23 +128,82 @@ func (h *Handler) canAccessPrivateAgent(ctx context.Context, agent db.Agent, actif err != nil {return false}- return roleAllowed(member.Role, "owner", "admin")+ if roleAllowed(member.Role, "owner", "admin") {+ return true+ }+ if agent.PermissionMode != "public_to" {+ return false+ }+ targets, err := h.Queries.ListAgentInvocationTargets(ctx, agent.ID)+ if err != nil {+ return false+ }+ return memberHitsInvocationTargets(targets, actorID)+}++// memberHitsInvocationTargets is the pure predicate deciding whether a regular+// member is on a public_to agent's allow-list, used by both the single-agent+// view gate and the ListAgents batch filter. A workspace target admits any+// member; a member target admits the matching user; team targets are inert.+func memberHitsInvocationTargets(targets []db.AgentInvocationTarget, userID string) bool {+ for _, t := range targets {+ switch t.TargetType {+ case "workspace":+ return true+ case "member":+ if uuidToString(t.TargetID) == userID {+ return true+ }+ }+ }+ return false}-// memberAllowedForPrivateAgent is the pure predicate used by both-// canAccessPrivateAgent and the ListAgents filter loop. Caller must have-// already confirmed agent.Visibility == "private".-func memberAllowedForPrivateAgent(agent db.Agent, userID, role string) bool {+// memberAllowedToViewAgent is the ListAgents / aggregation filter predicate.+// Caller supplies the agent's already-batch-loaded invocation targets so the+// list endpoint avoids an N+1. Workspace owner/admin and the agent owner see+// everything; a regular member sees a public_to agent only when on its+// allow-list, and never sees other members' private agents.+func memberAllowedToViewAgent(agent db.Agent, targets []db.AgentInvocationTarget, userID, role string) bool {if roleAllowed(role, "owner", "admin") {return true}- return uuidToString(agent.OwnerID) == userID+ if uuidToString(agent.OwnerID) == userID {+ return true+ }+ if agent.PermissionMode != "public_to" {+ return false+ }+ return memberHitsInvocationTargets(targets, userID)+}++// invokeOriginatorFromRequest resolves the top-of-chain human user id for an+// invocation initiated over HTTP. Members are their own originator; agent+// actors inherit the originator from the task named by the X-Task-ID header+// (set by the CLI on every request), matching+// TaskService.resolveOriginatorFromTriggerComment. Returns "" when no human+// can be attributed — canInvokeAgent then fails closed for member/team targets.+func (h *Handler) invokeOriginatorFromRequest(r *http.Request, actorType, actorID string) string {+ if actorType == "member" {+ return actorID+ }+ if actorType == "agent" {+ if taskIDHeader := r.Header.Get("X-Task-ID"); taskIDHeader != "" {+ if taskUUID, err := util.ParseUUID(taskIDHeader); err == nil {+ if task, err := h.Queries.GetAgentTask(r.Context(), taskUUID); err == nil {+ return uuidToString(task.OriginatorUserID)+ }+ }+ }+ }+ return ""}// accessibleAgentIDs returns the set of agent IDs in the workspace the actor// is allowed to see, for use by workspace-wide aggregation endpoints// (run counts, activity histograms, task snapshots) that need to filter out-// private agents the member can't access. Returns nil and false on error.+// private / non-allow-listed agents the member can't access. Returns nil and+// false on error.func (h *Handler) accessibleAgentIDs(ctx context.Context, workspaceID, actorType, actorID, role string) (map[string]struct{}, bool) {wsUUID, err := util.ParseUUID(workspaceID)if err != nil {@@ -62,10 +213,14 @@ func (h *Handler) accessibleAgentIDs(ctx context.Context, workspaceID, actorTypeif err != nil {return nil, false}+ targetsByAgent, ok := h.loadInvocationTargetsByAgent(ctx, agents)+ if !ok {+ return nil, false+ }allowed := make(map[string]struct{}, len(agents))for _, a := range agents {- if a.Visibility == "private" && actorType == "member" {- if !memberAllowedForPrivateAgent(a, actorID, role) {+ if actorType == "member" {+ if !memberAllowedToViewAgent(a, targetsByAgent[uuidToString(a.ID)], actorID, role) {continue}}@@ -73,17 +228,40 @@ func (h *Handler) accessibleAgentIDs(ctx context.Context, workspaceID, actorType}return allowed, true}++// loadInvocationTargetsByAgent batch-loads invocation targets for a set of+// agents and buckets them by agent id string. Avoids the per-agent query the+// list / aggregation paths would otherwise incur.+func (h *Handler) loadInvocationTargetsByAgent(ctx context.Context, agents []db.Agent) (map[string][]db.AgentInvocationTarget, bool) {+ ids := make([]pgtype.UUID, 0, len(agents))+ for _, a := range agents {+ ids = append(ids, a.ID)+ }+ out := make(map[string][]db.AgentInvocationTarget, len(agents))+ if len(ids) == 0 {+ return out, true+ }+ rows, err := h.Queries.ListAgentInvocationTargetsByAgentIDs(ctx, ids)+ if err != nil {+ return nil, false+ }+ for _, row := range rows {+ aid := uuidToString(row.AgentID)+ out[aid] = append(out[aid], row)+ }+ return out, true+}+// canEnqueueSquadLeader returns true when the given actor is allowed to// trigger the squad's private leader. It loads the leader agent and delegates-// to canAccessPrivateAgent. Non-private leaders always pass. System-initiated-// triggers (e.g. github webhooks) pass by treating "system" like "agent".-func (h *Handler) canEnqueueSquadLeader(ctx context.Context, leaderID pgtype.UUID, actorType, actorID, workspaceID string) bool {+// to canInvokeAgent so the leader-trigger path honours invocation permission+// exactly like a direct assignment/mention. Non-public leaders require owner /+// allow-list; system-initiated triggers (e.g. github webhooks) are judged as+// system principals (workspace target only).+func (h *Handler) canEnqueueSquadLeader(ctx context.Context, leaderID pgtype.UUID, actorType, actorID, originatorUserID, workspaceID string) bool {agent, err := h.Queries.GetAgent(ctx, leaderID)if err != nil {return false}- if actorType == "system" {- actorType = "agent"- }- return h.canAccessPrivateAgent(ctx, agent, actorType, actorID, workspaceID)+ return h.canInvokeAgent(ctx, agent, actorType, actorID, originatorUserID, workspaceID)}diff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.goindex ed33ec39cb..8aa631c769 100644--- a/server/internal/handler/agent_access_test.go+++ b/server/internal/handler/agent_access_test.go@@ -12,18 +12,19 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")-// TestMemberAllowedForPrivateAgent_Pure exercises the pure predicate that-// drives the private-agent gate. The gate must allow:+// TestMemberAllowedToViewAgent_Pure exercises the pure predicate that drives+// the private-agent VIEW gate. For a private agent it must allow:// - workspace owner / admin (regardless of agent ownership)// - the agent owner (regardless of role)//// And deny everyone else. This test runs without a database.-func TestMemberAllowedForPrivateAgent_Pure(t *testing.T) {+func TestMemberAllowedToViewAgent_Pure(t *testing.T) {ownerUserID := "11111111-1111-1111-1111-111111111111"otherUserID := "22222222-2222-2222-2222-222222222222"agent := db.Agent{- OwnerID: util.MustParseUUID(ownerUserID),+ OwnerID: util.MustParseUUID(ownerUserID),+ PermissionMode: "private",}cases := []struct {@@ -41,9 +42,9 @@ func TestMemberAllowedForPrivateAgent_Pure(t *testing.T) {}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {- got := memberAllowedForPrivateAgent(agent, tc.userID, tc.role)+ got := memberAllowedToViewAgent(agent, nil, tc.userID, tc.role)if got != tc.want {- t.Fatalf("memberAllowedForPrivateAgent(userID=%s, role=%s) = %v; want %v",+ t.Fatalf("memberAllowedToViewAgent(userID=%s, role=%s) = %v; want %v",tc.userID, tc.role, got, tc.want)}})@@ -246,11 +247,13 @@ func TestCreateIssue_AssignToPrivateAgentForbidsPlainMember(t *testing.T) {}}- // Workspace owner (testUserID): allowed.+ // Workspace owner (testUserID) who is NOT the agent owner: DENIED under+ // the invocation-permission model (MUL-3963) — admin/owner status no+ // longer grants the ability to invoke someone else's private agent.w := httptest.NewRecorder()testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, body(testUserID)))- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue as workspace owner: expected 201, got %d: %s", w.Code, w.Body.String())+ if w.Code != http.StatusForbidden {+ t.Fatalf("CreateIssue as workspace owner (not agent owner): expected 403, got %d: %s", w.Code, w.Body.String())}// Agent owner (plain member who happens to own the agent): allowed.@@ -567,18 +570,18 @@ func TestShouldEnqueueOnComment_PrivateAgentGate(t *testing.T) {reason: "agent owner is always in the allowed_principals set",},{- name: "workspace owner — allowed",+ name: "workspace owner — denied (not agent owner)",actorType: "member",actorID: testUserID,- want: true,- reason: "workspace owners/admins are in the allowed_principals set",+ want: false,+ reason: "MUL-3963: workspace owners/admins no longer bypass a private agent's invocation gate",},{- name: "agent-to-agent — allowed",+ name: "agent-to-agent — denied without allowed originator",actorType: "agent",actorID: agentID,- want: true,- reason: "A2A traffic bypasses the visibility gate by design",+ want: false,+ reason: "MUL-3963: A2A is judged by the top-of-chain originator; a private agent denies an agent actor with no owner/allow-listed originator",},}diff --git a/server/internal/handler/agent_composio_allowlist_test.go b/server/internal/handler/agent_composio_allowlist_test.gonew file mode 100644index 0000000000..5fb39d36c3--- /dev/null+++ b/server/internal/handler/agent_composio_allowlist_test.go@@ -0,0 +1,341 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// allowlistFixture seeds an agent owned by a freshly-created user (not the+// workspace owner) so we can drive the "caller is workspace owner / admin+// but not agent owner" branch of UpdateAgent.composio_toolkit_allowlist.+// Returns the agent id and the agent owner's user id; the test's own+// testUserID stays the workspace owner.+func allowlistFixture(t *testing.T) (agentID, agentOwnerID string) {+ t.Helper()+ ctx := context.Background()+ if err := testPool.QueryRow(ctx, `+ INSERT INTO "user" (name, email)+ VALUES ('Allowlist Owner', '[email protected]')+ RETURNING id+ `).Scan(&agentOwnerID); err != nil {+ t.Fatalf("create owner user: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(),+ `DELETE FROM "user" WHERE email = '[email protected]'`)+ })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO member (workspace_id, user_id, role)+ VALUES ($1, $2, 'member')+ `, testWorkspaceID, agentOwnerID); err != nil {+ t.Fatalf("add owner as workspace member: %v", err)+ }++ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id,+ instructions, custom_env, custom_args+ )+ VALUES ($1, 'allowlist-test-agent', '', 'cloud', '{}'::jsonb,+ $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb)+ RETURNING id+ `, testWorkspaceID, handlerTestRuntimeID(t), agentOwnerID).Scan(&agentID); err != nil {+ t.Fatalf("create agent: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(),+ `DELETE FROM agent WHERE id = $1`, agentID)+ })+ return agentID, agentOwnerID+}++func readAllowlistColumn(t *testing.T, agentID string) ([]string, bool) {+ t.Helper()+ var stored []string+ var isNull bool+ if err := testPool.QueryRow(context.Background(), `+ SELECT COALESCE(composio_toolkit_allowlist, '{}'::text[]),+ composio_toolkit_allowlist IS NULL+ FROM agent WHERE id = $1+ `, agentID).Scan(&stored, &isNull); err != nil {+ t.Fatalf("read allowlist column: %v", err)+ }+ return stored, isNull+}++// TestUpdateAgent_AllowlistRoundtripForOwner is the happy path: the agent+// owner submits a list, then a normalised duplicate, then an empty array,+// then JSON null. The handler must persist the four canonical states+// distinguishable by the dispatch path:+// - non-empty deduped lowercased TEXT[]+// - the same value after a noisy second write (idempotent)+// - empty `{}` after explicit []+// - NULL after an explicit null+func TestUpdateAgent_AllowlistRoundtripForOwner(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ withComposioMCPAppsFlag(t, testHandler, true)+ agentID, ownerID := allowlistFixture(t)++ // 1. Owner writes a noisy list — trims/casefolds/dedupes inline.+ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, withURLParam(newRequestAs(+ ownerID, http.MethodPut, "/api/agents/"+agentID,+ map[string]any{+ "composio_toolkit_allowlist": []string{" Notion ", "NOTION", "github", ""},+ },+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent owner write: got %d: %s", w.Code, w.Body.String())+ }+ stored, isNull := readAllowlistColumn(t, agentID)+ if isNull {+ t.Fatalf("after owner write, allowlist still NULL")+ }+ if len(stored) != 2 || stored[0] != "notion" || stored[1] != "github" {+ t.Errorf("normalised allowlist = %v; want [notion github]", stored)+ }++ // 2. Owner writes empty array — distinct from NULL on the column.+ w = httptest.NewRecorder()+ testHandler.UpdateAgent(w, withURLParam(newRequestAs(+ ownerID, http.MethodPut, "/api/agents/"+agentID,+ map[string]any{"composio_toolkit_allowlist": []string{}},+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent owner empty write: got %d: %s", w.Code, w.Body.String())+ }+ stored, isNull = readAllowlistColumn(t, agentID)+ if isNull {+ t.Fatalf("empty array must persist as empty TEXT[], not NULL")+ }+ if len(stored) != 0 {+ t.Errorf("after empty write, stored = %v; want empty", stored)+ }++ // 3. Owner explicitly nulls the column.+ w = httptest.NewRecorder()+ testHandler.UpdateAgent(w, withURLParam(newRequestAs(+ ownerID, http.MethodPut, "/api/agents/"+agentID,+ map[string]any{"composio_toolkit_allowlist": nil},+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent owner null write: got %d: %s", w.Code, w.Body.String())+ }+ _, isNull = readAllowlistColumn(t, agentID)+ if !isNull {+ t.Errorf("explicit null must persist as NULL")+ }+}++// TestUpdateAgent_AllowlistSilentlyDroppedForNonOwner is the Stage 3.1+// privacy guarantee on the write path: a workspace owner / admin can call+// UpdateAgent against another user's agent (which canManageAgent allows+// for legitimate admin actions like reassigning the agent off a leaving+// member's runtime), but a `composio_toolkit_allowlist` field in that+// request must be silently ignored. Without this, an admin could+// arbitrarily widen what an agent surfaces from another member's+// connected accounts.+func TestUpdateAgent_AllowlistSilentlyDroppedForNonOwner(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ withComposioMCPAppsFlag(t, testHandler, true)+ agentID, _ := allowlistFixture(t)++ // Seed an existing allowlist via direct SQL so we can prove the+ // admin's submission did not overwrite it.+ if _, err := testPool.Exec(context.Background(), `+ UPDATE agent SET composio_toolkit_allowlist = $2 WHERE id = $1+ `, agentID, []string{"notion"}); err != nil {+ t.Fatalf("seed existing allowlist: %v", err)+ }++ // Workspace owner (testUserID) is NOT the agent owner.+ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, withURLParam(newRequest(+ http.MethodPut, "/api/agents/"+agentID,+ map[string]any{+ // Touch some other field too, so the request is otherwise+ // valid (canManageAgent admits workspace owners).+ "description": "admin description sweep",+ "composio_toolkit_allowlist": []string{+ "github", "slack", // would-be widening+ },+ },+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent admin sweep: got %d: %s", w.Code, w.Body.String())+ }+ // The non-owner-edit must NOT have replaced the allowlist; the+ // description update must have landed.+ stored, isNull := readAllowlistColumn(t, agentID)+ if isNull {+ t.Fatalf("allowlist must NOT be wiped by non-owner write; got NULL")+ }+ if len(stored) != 1 || stored[0] != "notion" {+ t.Errorf("non-owner widening landed: allowlist=%v; want unchanged [notion]", stored)+ }+ // The response shape should also not surface the would-be widened+ // allowlist to the admin. agentToResponse populates it from the+ // (unchanged) DB row, and the owner-only redaction at the end of+ // UpdateAgent then strips it for the admin caller.+ var resp AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(resp.ComposioToolkitAllowlist) != 0 {+ t.Errorf("admin response leaked allowlist contents: %v", resp.ComposioToolkitAllowlist)+ }+ if !resp.ComposioToolkitAllowlistRedacted {+ t.Errorf("admin response should mark allowlist redacted, got %+v", resp)+ }+}++// TestGetAgent_AllowlistVisibility verifies the read-path redaction is+// strictly owner-only:+// - the agent owner sees the slug list verbatim+// - the workspace owner (admin) sees nothing + redacted=true+// - the response shape stays parseable in both cases (no nil-pointer panic)+func TestGetAgent_AllowlistVisibility(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ withComposioMCPAppsFlag(t, testHandler, true)+ agentID, ownerID := allowlistFixture(t)+ if _, err := testPool.Exec(context.Background(), `+ UPDATE agent SET composio_toolkit_allowlist = $2 WHERE id = $1+ `, agentID, []string{"notion", "github"}); err != nil {+ t.Fatalf("seed allowlist: %v", err)+ }++ // Owner sees the list.+ w := httptest.NewRecorder()+ testHandler.GetAgent(w, withURLParam(newRequestAs(+ ownerID, http.MethodGet, "/api/agents/"+agentID, nil,+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("GetAgent as owner: got %d: %s", w.Code, w.Body.String())+ }+ var ownerResp AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &ownerResp); err != nil {+ t.Fatalf("decode owner response: %v", err)+ }+ if len(ownerResp.ComposioToolkitAllowlist) != 2 {+ t.Errorf("owner: allowlist=%v; want length 2", ownerResp.ComposioToolkitAllowlist)+ }+ if ownerResp.ComposioToolkitAllowlistRedacted {+ t.Errorf("owner should not see redacted flag")+ }++ // Workspace owner (testUserID) is NOT the agent owner — must be redacted.+ w = httptest.NewRecorder()+ testHandler.GetAgent(w, withURLParam(newRequest(+ http.MethodGet, "/api/agents/"+agentID, nil,+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("GetAgent as ws-owner: got %d: %s", w.Code, w.Body.String())+ }+ var adminResp AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &adminResp); err != nil {+ t.Fatalf("decode admin response: %v", err)+ }+ if len(adminResp.ComposioToolkitAllowlist) != 0 {+ t.Errorf("ws-owner response leaked allowlist: %v", adminResp.ComposioToolkitAllowlist)+ }+ if !adminResp.ComposioToolkitAllowlistRedacted {+ t.Errorf("ws-owner response should mark allowlist redacted")+ }+}++func TestAgentAllowlistSuppressedWhenComposioFlagDisabled(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ withComposioMCPAppsFlag(t, testHandler, false)+ agentID, ownerID := allowlistFixture(t)+ if _, err := testPool.Exec(context.Background(), `+ UPDATE agent SET composio_toolkit_allowlist = $2 WHERE id = $1+ `, agentID, []string{"notion"}); err != nil {+ t.Fatalf("seed allowlist: %v", err)+ }++ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, withURLParam(newRequestAs(+ ownerID, http.MethodPut, "/api/agents/"+agentID,+ map[string]any{"composio_toolkit_allowlist": []string{"github"}},+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent owner write with flag off: got %d: %s", w.Code, w.Body.String())+ }+ stored, isNull := readAllowlistColumn(t, agentID)+ if isNull || len(stored) != 1 || stored[0] != "notion" {+ t.Fatalf("flag-off write changed allowlist: stored=%v isNull=%v; want unchanged [notion]", stored, isNull)+ }+ var updateResp AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &updateResp); err != nil {+ t.Fatalf("decode update response: %v", err)+ }+ if len(updateResp.ComposioToolkitAllowlist) != 0 || updateResp.ComposioToolkitAllowlistRedacted {+ t.Fatalf("flag-off update response exposed allowlist state: %+v", updateResp)+ }++ w = httptest.NewRecorder()+ testHandler.GetAgent(w, withURLParam(newRequestAs(+ ownerID, http.MethodGet, "/api/agents/"+agentID, nil,+ ), "id", agentID))+ if w.Code != http.StatusOK {+ t.Fatalf("GetAgent owner with flag off: got %d: %s", w.Code, w.Body.String())+ }+ var getResp AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &getResp); err != nil {+ t.Fatalf("decode get response: %v", err)+ }+ if len(getResp.ComposioToolkitAllowlist) != 0 || getResp.ComposioToolkitAllowlistRedacted {+ t.Fatalf("flag-off get response exposed allowlist state: %+v", getResp)+ }+}++// TestNormaliseComposioToolkitAllowlist_PureFunction exercises the canonical+// normalisation so future refactors don't silently change the persisted+// form (and break the dispatch path's flat slug compare).+func TestNormaliseComposioToolkitAllowlist_PureFunction(t *testing.T) {+ cases := []struct {+ name string+ in []string+ want []string+ }{+ {"nil-in nil-out", nil, nil},+ {"empty-in empty-out", []string{}, []string{}},+ {"trim", []string{" notion "}, []string{"notion"}},+ {"lower", []string{"NOTION", "GitHub"}, []string{"notion", "github"}},+ {"dedupe", []string{"notion", "NOTION", "notion"}, []string{"notion"}},+ {"drop empty", []string{"", " ", "notion"}, []string{"notion"}},+ {"preserve order of first-seen", []string{"notion", "github", "notion"}, []string{"notion", "github"}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := normaliseComposioToolkitAllowlist(tc.in)+ if tc.want == nil {+ if got != nil {+ t.Fatalf("got %v; want nil", got)+ }+ return+ }+ if len(got) != len(tc.want) {+ t.Fatalf("got %v; want %v", got, tc.want)+ }+ for i := range tc.want {+ if got[i] != tc.want[i] {+ t.Errorf("got[%d]=%q; want %q", i, got[i], tc.want[i])+ }+ }+ })+ }+}diff --git a/server/internal/handler/agent_permission.go b/server/internal/handler/agent_permission.gonew file mode 100644index 0000000000..c775e1cd23--- /dev/null+++ b/server/internal/handler/agent_permission.go@@ -0,0 +1,295 @@+package handler++import (+ "context"+ "fmt"+ "net/http"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// AgentInvocationTargetDTO is the wire shape of one invocation allow-list+// entry (MUL-3963). target_id is null for team placeholders that a client+// omitted, but is always present for workspace (the workspace id) and member+// (the user id) rows persisted by the backend.+type AgentInvocationTargetDTO struct {+ TargetType string `json:"target_type"`+ TargetID *string `json:"target_id"`+}++const (+ permissionModePrivate = "private"+ permissionModePublicTo = "public_to"++ invocationTargetWorkspace = "workspace"+ invocationTargetMember = "member"+ invocationTargetTeam = "team"+)++// deriveLegacyVisibility maps the permission model back onto the legacy+// two-value visibility field so old clients never observe a widening:+// - public_to WITH a workspace target -> "workspace" (everyone can invoke)+// - everything else (private, or public_to limited to member/team) -> "private"+func deriveLegacyVisibility(permissionMode string, targets []db.AgentInvocationTarget) string {+ if permissionMode == permissionModePublicTo {+ for _, t := range targets {+ if t.TargetType == invocationTargetWorkspace {+ return "workspace"+ }+ }+ }+ return "private"+}++// applyInvocationTargetsToResponse fills InvocationTargets and recomputes the+// derived legacy Visibility from the loaded targets, keeping both views of the+// permission consistent in a single place.+func applyInvocationTargetsToResponse(resp *AgentResponse, targets []db.AgentInvocationTarget) {+ dto := make([]AgentInvocationTargetDTO, 0, len(targets))+ for _, t := range targets {+ var idPtr *string+ if t.TargetID.Valid {+ s := uuidToString(t.TargetID)+ idPtr = &s+ }+ dto = append(dto, AgentInvocationTargetDTO{TargetType: t.TargetType, TargetID: idPtr})+ }+ resp.InvocationTargets = dto+ resp.Visibility = deriveLegacyVisibility(resp.PermissionMode, targets)+}++// resolvedPermission is the normalised outcome of parsing the permission+// fields (or legacy visibility) off a create/update request.+type resolvedPermission struct {+ mode string+ targets []targetSpec+}++type targetSpec struct {+ targetType string+ targetID pgtype.UUID // invalid for team placeholders+}++// legacyVisibility is what this permission maps to for the visibility column+// we keep in sync for backwards compatibility.+func (p resolvedPermission) legacyVisibility() string {+ if p.mode == permissionModePublicTo {+ for _, t := range p.targets {+ if t.targetType == invocationTargetWorkspace {+ return "workspace"+ }+ }+ }+ return "private"+}++// parsePermissionInput normalises a permission_mode + invocation_targets pair,+// falling back to a legacy visibility value when the new fields are absent.+//+// - permissionMode == nil && visibility == nil -> caller default (returns ok=false, nil)+// - permissionMode provided -> authoritative+// - only legacy visibility provided -> mapped:+// "private" -> private+// "workspace" -> public_to + workspace target+//+// workspaceID seeds workspace targets (stored as the workspace id). The+// returned error is a client-facing 400 message.+func parsePermissionInput(workspaceID pgtype.UUID, permissionMode *string, targets []AgentInvocationTargetDTO, hasPermissionMode, hasTargets bool, legacyVisibility *string) (resolvedPermission, bool, error) {+ if !hasPermissionMode && legacyVisibility == nil {+ return resolvedPermission{}, false, nil+ }++ // Legacy-only path: map visibility onto the new model.+ if !hasPermissionMode {+ switch *legacyVisibility {+ case "workspace":+ return resolvedPermission{+ mode: permissionModePublicTo,+ targets: []targetSpec{{targetType: invocationTargetWorkspace, targetID: workspaceID}},+ }, true, nil+ case "private", "":+ return resolvedPermission{mode: permissionModePrivate}, true, nil+ default:+ return resolvedPermission{}, false, fmt.Errorf("visibility must be 'private' or 'workspace'")+ }+ }++ mode := permissionModePrivate+ if permissionMode != nil && *permissionMode != "" {+ mode = *permissionMode+ }+ if mode != permissionModePrivate && mode != permissionModePublicTo {+ return resolvedPermission{}, false, fmt.Errorf("permission_mode must be 'private' or 'public_to'")+ }++ res := resolvedPermission{mode: mode}+ if mode == permissionModePrivate {+ // Private ignores any submitted targets: deny-by-default.+ return res, true, nil+ }++ // public_to: normalise the target list, de-duping and validating.+ if hasTargets {+ seen := map[string]struct{}{}+ for _, t := range targets {+ switch t.TargetType {+ case invocationTargetWorkspace:+ key := "workspace"+ if _, dup := seen[key]; dup {+ continue+ }+ seen[key] = struct{}{}+ res.targets = append(res.targets, targetSpec{targetType: invocationTargetWorkspace, targetID: workspaceID})+ case invocationTargetMember:+ if t.TargetID == nil || *t.TargetID == "" {+ return resolvedPermission{}, false, fmt.Errorf("member invocation target requires target_id")+ }+ uid, err := util.ParseUUID(*t.TargetID)+ if err != nil {+ return resolvedPermission{}, false, fmt.Errorf("member invocation target_id is not a valid uuid")+ }+ key := "member:" + *t.TargetID+ if _, dup := seen[key]; dup {+ continue+ }+ seen[key] = struct{}{}+ res.targets = append(res.targets, targetSpec{targetType: invocationTargetMember, targetID: uid})+ case invocationTargetTeam:+ if t.TargetID == nil || *t.TargetID == "" {+ return resolvedPermission{}, false, fmt.Errorf("team invocation target requires target_id")+ }+ tid, err := util.ParseUUID(*t.TargetID)+ if err != nil {+ return resolvedPermission{}, false, fmt.Errorf("team invocation target_id is not a valid uuid")+ }+ key := "team:" + *t.TargetID+ if _, dup := seen[key]; dup {+ continue+ }+ seen[key] = struct{}{}+ res.targets = append(res.targets, targetSpec{targetType: invocationTargetTeam, targetID: tid})+ default:+ return resolvedPermission{}, false, fmt.Errorf("invocation target_type must be 'workspace', 'member', or 'team'")+ }+ }+ }+ // An empty public_to is a phantom: "shared with nobody" that the front-end+ // would render as workspace-shared while the backend admits no one. Per the+ // MUL-3963 ruling, a public_to with no resolvable targets is normalised to+ // a single workspace target — this also makes `--permission-mode public_to`+ // with no --public-to-* flags mean "public to workspace".+ if len(res.targets) == 0 {+ res.targets = append(res.targets, targetSpec{targetType: invocationTargetWorkspace, targetID: workspaceID})+ }+ return res, true, nil+}++// replaceInvocationTargets rewrites an agent's invocation allow-list wholesale:+// clear then re-insert. Called inside create/update after the agent row exists.+func (h *Handler) replaceInvocationTargets(ctx context.Context, agentID pgtype.UUID, createdBy pgtype.UUID, targets []targetSpec) error {+ if err := h.Queries.DeleteAgentInvocationTargets(ctx, agentID); err != nil {+ return err+ }+ for _, t := range targets {+ if err := h.Queries.CreateAgentInvocationTarget(ctx, db.CreateAgentInvocationTargetParams{+ AgentID: agentID,+ TargetType: t.targetType,+ TargetID: t.targetID,+ CreatedBy: createdBy,+ }); err != nil {+ return err+ }+ }+ return nil+}++// permissionInputChangesAgent reports whether the permission fields on an+// update request would actually CHANGE the agent's current invocation+// permission (mode or the set of targets). Used to let a non-owner's no-op+// resubmit through (PATCH-as-PUT that echoes unchanged permission) while+// rejecting a real change with 403. Invalid/absent permission input counts as+// "no change" — a non-owner sending garbage should not get a 403 either, it is+// simply ignored. Fails safe: on a DB error it returns changed=true so a+// non-owner attempt is rejected rather than silently applied.+func (h *Handler) permissionInputChangesAgent(ctx context.Context, existing db.Agent, req UpdateAgentRequest, hasPermissionMode, hasTargets bool) (bool, error) {+ // Legacy-only request: the caller sent ONLY `visibility`, no permission_mode+ // and no invocation_targets (an old client / PATCH-as-PUT echoing the field+ // back while editing something else). Compare on the DERIVED legacy+ // visibility, NOT by expanding "private" into a real private permission.+ // A member-only public_to agent derives to legacy "private", so an admin+ // resubmitting visibility:"private" is a NO-OP, not a public_to→private+ // downgrade. Only a real legacy change (e.g. "workspace") counts. (MUL-3963+ // review — this is the compatibility fix for PR #4853.)+ if !hasPermissionMode && !hasTargets {+ if req.Visibility == nil {+ return false, nil+ }+ current, err := h.Queries.ListAgentInvocationTargets(ctx, existing.ID)+ if err != nil {+ return true, err+ }+ submitted := "private"+ if *req.Visibility == "workspace" {+ submitted = "workspace"+ }+ return submitted != deriveLegacyVisibility(existing.PermissionMode, current), nil+ }++ var targetsDTO []AgentInvocationTargetDTO+ if req.InvocationTargets != nil {+ targetsDTO = *req.InvocationTargets+ }+ perm, ok, err := parsePermissionInput(existing.WorkspaceID, req.PermissionMode, targetsDTO, hasPermissionMode, hasTargets, req.Visibility)+ if err != nil || !ok {+ // Unparseable or effectively no permission fields → treat as no change.+ return false, nil+ }+ if perm.mode != existing.PermissionMode {+ return true, nil+ }+ current, err := h.Queries.ListAgentInvocationTargets(ctx, existing.ID)+ if err != nil {+ return true, err+ }+ want := make(map[string]struct{}, len(perm.targets))+ for _, tgt := range perm.targets {+ want[tgt.targetType+":"+uuidToString(tgt.targetID)] = struct{}{}+ }+ have := make(map[string]struct{}, len(current))+ for _, row := range current {+ have[row.TargetType+":"+uuidToString(row.TargetID)] = struct{}{}+ }+ if len(want) != len(have) {+ return true, nil+ }+ for k := range want {+ if _, ok := have[k]; !ok {+ return true, nil+ }+ }+ return false, nil+}++// enrichAgentResponseWithTargets loads an agent's invocation targets and+// applies them to the response (InvocationTargets + derived Visibility). Used+// by the single-agent detail / create / update responses.+func (h *Handler) enrichAgentResponseWithTargets(ctx context.Context, resp *AgentResponse, agentID pgtype.UUID) error {+ targets, err := h.Queries.ListAgentInvocationTargets(ctx, agentID)+ if err != nil {+ return err+ }+ applyInvocationTargetsToResponse(resp, targets)+ return nil+}++// enrichAgentResponseWithTargetsHTTP is the HTTP-boundary wrapper that writes a+// 500 and returns false on failure.+func (h *Handler) enrichAgentResponseWithTargetsHTTP(w http.ResponseWriter, r *http.Request, resp *AgentResponse, agentID pgtype.UUID) bool {+ if err := h.enrichAgentResponseWithTargets(r.Context(), resp, agentID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load agent invocation targets")+ return false+ }+ return true+}diff --git a/server/internal/handler/agent_permission_test.go b/server/internal/handler/agent_permission_test.gonew file mode 100644index 0000000000..08fc44d2df--- /dev/null+++ b/server/internal/handler/agent_permission_test.go@@ -0,0 +1,735 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/multica-ai/multica/server/internal/util"+)++// createPermissionTestMember inserts a fresh workspace member and returns its+// user id, registering cleanup.+func createPermissionTestMember(t *testing.T, email string) string {+ t.Helper()+ ctx := context.Background()+ var userID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id+ `, email, email).Scan(&userID); err != nil {+ t.Fatalf("create member user %s: %v", email, err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID) })+ if _, err := testPool.Exec(ctx, `+ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')+ `, testWorkspaceID, userID); err != nil {+ t.Fatalf("add member %s: %v", email, err)+ }+ return userID+}++// TestCreateAgent_LegacyVisibilityMapsToPermission verifies the lossless+// legacy-visibility mapping (MUL-3963) at the API layer — the same mapping the+// migration backfill applies to existing rows:+// - visibility "workspace" -> permission_mode public_to + a workspace target+// - visibility "private" -> permission_mode private + no targets+func TestCreateAgent_LegacyVisibilityMapsToPermission(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ runtimeID := handlerTestRuntimeID(t)++ create := func(name, visibility string) AgentResponse {+ w := httptest.NewRecorder()+ testHandler.CreateAgent(w, newRequest("POST", "/api/agents?workspace_id="+testWorkspaceID, map[string]any{+ "name": name,+ "runtime_id": runtimeID,+ "visibility": visibility,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create %q (visibility=%s): expected 201, got %d: %s", name, visibility, w.Code, w.Body.String())+ }+ var resp AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, resp.ID) })+ return resp+ }++ ws := create("legacy-visibility-workspace", "workspace")+ if ws.PermissionMode != "public_to" {+ t.Errorf("workspace agent permission_mode = %q, want public_to", ws.PermissionMode)+ }+ if ws.Visibility != "workspace" {+ t.Errorf("workspace agent derived visibility = %q, want workspace", ws.Visibility)+ }+ foundWorkspaceTarget := false+ for _, tgt := range ws.InvocationTargets {+ if tgt.TargetType == "workspace" {+ foundWorkspaceTarget = true+ }+ }+ if !foundWorkspaceTarget {+ t.Errorf("workspace agent invocation_targets = %+v, want a workspace target", ws.InvocationTargets)+ }++ priv := create("legacy-visibility-private", "private")+ if priv.PermissionMode != "private" {+ t.Errorf("private agent permission_mode = %q, want private", priv.PermissionMode)+ }+ if priv.Visibility != "private" {+ t.Errorf("private agent derived visibility = %q, want private", priv.Visibility)+ }+ if len(priv.InvocationTargets) != 0 {+ t.Errorf("private agent invocation_targets = %+v, want none", priv.InvocationTargets)+ }+}++// TestMigrationBackfill_VisibilityToPermission exercises the exact backfill+// statements from migration 130 against a synthetic pre-migration row+// (visibility='workspace' but permission_mode='private', no target). The+// statements are idempotent, so re-running them on the live (already-migrated)+// DB only affects the synthetic row.+func TestMigrationBackfill_VisibilityToPermission(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID := handlerTestRuntimeID(t)++ var agentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id+ )+ VALUES ($1, 'backfill-legacy-workspace-agent', '', 'cloud', '{}'::jsonb,+ $2, 'workspace', 'private', 1, $3)+ RETURNING id+ `, testWorkspaceID, runtimeID, testUserID).Scan(&agentID); err != nil {+ t.Fatalf("insert pre-migration agent: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID) })++ // Exact backfill statements from migration 130 (idempotent).+ if _, err := testPool.Exec(ctx, `UPDATE agent SET permission_mode = 'public_to' WHERE visibility = 'workspace'`); err != nil {+ t.Fatalf("backfill update: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id, created_by)+ SELECT id, 'workspace', workspace_id, NULL FROM agent WHERE visibility = 'workspace'+ ON CONFLICT (agent_id, target_type, target_id) DO NOTHING+ `); err != nil {+ t.Fatalf("backfill insert targets: %v", err)+ }++ var mode string+ if err := testPool.QueryRow(ctx, `SELECT permission_mode FROM agent WHERE id = $1`, agentID).Scan(&mode); err != nil {+ t.Fatalf("read permission_mode: %v", err)+ }+ if mode != "public_to" {+ t.Errorf("after backfill permission_mode = %q, want public_to", mode)+ }+ var targetCount int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM agent_invocation_target+ WHERE agent_id = $1 AND target_type = 'workspace' AND target_id = $2+ `, agentID, testWorkspaceID).Scan(&targetCount); err != nil {+ t.Fatalf("count targets: %v", err)+ }+ if targetCount != 1 {+ t.Errorf("workspace target count = %d, want 1", targetCount)+ }+}++// TestCanInvokeAgent_PublicToMemberWhitelist verifies that a public_to agent+// restricted to a specific member is invocable (assignable) only by that+// member — not by other plain members, and not by workspace admins who are not+// on the list (MUL-3963).+func TestCanInvokeAgent_PublicToMemberWhitelist(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ runtimeID := handlerTestRuntimeID(t)++ allowedMember := createPermissionTestMember(t, "[email protected]")+ otherMember := createPermissionTestMember(t, "[email protected]")++ // Owner (testUserID) creates an agent public_to the allowed member only.+ w := httptest.NewRecorder()+ testHandler.CreateAgent(w, newRequest("POST", "/api/agents?workspace_id="+testWorkspaceID, map[string]any{+ "name": "public-to-specific-member-agent",+ "runtime_id": runtimeID,+ "permission_mode": "public_to",+ "invocation_targets": []map[string]any{+ {"target_type": "member", "target_id": allowedMember},+ },+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create agent: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var agent AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&agent); err != nil {+ t.Fatalf("decode: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agent.ID) })++ // Derived legacy visibility for a member-only public_to agent must be+ // "private" so old clients never treat it as workspace-wide.+ if agent.Visibility != "private" {+ t.Errorf("member-only public_to derived visibility = %q, want private", agent.Visibility)+ }++ assignAs := func(actorID string) int {+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequestAs(actorID, "POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "assign to member-scoped agent",+ "status": "todo",+ "assignee_type": "agent",+ "assignee_id": agent.ID,+ }))+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE agent_id = $1`, agent.ID)+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE workspace_id = $1 AND title = 'assign to member-scoped agent'`, testWorkspaceID)+ })+ return rec.Code+ }++ if code := assignAs(allowedMember); code != http.StatusCreated {+ t.Errorf("allow-listed member assign: expected 201, got %d", code)+ }+ if code := assignAs(otherMember); code != http.StatusForbidden {+ t.Errorf("non-allow-listed member assign: expected 403, got %d", code)+ }+}++// --- MUL-3963 follow-up: stackable / mixed / batch-replaced targets -------++// createPublicToAgentWithTargets creates a public_to agent (owned by+// testUserID) with the given invocation targets via the CreateAgent handler+// and returns its id.+func createPublicToAgentWithTargets(t *testing.T, name string, targets []map[string]any) string {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.CreateAgent(w, newRequest("POST", "/api/agents?workspace_id="+testWorkspaceID, map[string]any{+ "name": name,+ "runtime_id": handlerTestRuntimeID(t),+ "permission_mode": "public_to",+ "invocation_targets": targets,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create %q: expected 201, got %d: %s", name, w.Code, w.Body.String())+ }+ var resp AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, resp.ID) })+ return resp.ID+}++// canMemberInvoke loads the agent fresh and asks canInvokeAgent whether the+// given member may invoke it (member is their own originator).+func canMemberInvoke(t *testing.T, agentID, userID string) bool {+ t.Helper()+ agent, err := testHandler.Queries.GetAgent(context.Background(), util.MustParseUUID(agentID))+ if err != nil {+ t.Fatalf("load agent: %v", err)+ }+ return testHandler.canInvokeAgent(context.Background(), agent, "member", userID, userID, testWorkspaceID)+}++func invocationTargetCount(t *testing.T, agentID string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(context.Background(),+ `SELECT count(*) FROM agent_invocation_target WHERE agent_id = $1`, agentID,+ ).Scan(&n); err != nil {+ t.Fatalf("count targets: %v", err)+ }+ return n+}++// TestCanInvokeAgent_MixedMemberAndTeamTargets verifies a public_to agent can+// carry a MIX of target types on one agent, and canInvokeAgent OR-matches: a+// member target admits that member; a team target is inert in v1 so it admits+// nobody, but co-existing with the member target does not break the member+// grant.+func TestCanInvokeAgent_MixedMemberAndTeamTargets(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ memberA := createPermissionTestMember(t, "[email protected]")+ memberB := createPermissionTestMember(t, "[email protected]")+ teamID := "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" // no team table FK in v1++ agentID := createPublicToAgentWithTargets(t, "mixed-member-team-agent", []map[string]any{+ {"target_type": "member", "target_id": memberA},+ {"target_type": "team", "target_id": teamID},+ })++ if n := invocationTargetCount(t, agentID); n != 2 {+ t.Errorf("expected 2 mixed targets persisted, got %d", n)+ }+ if !canMemberInvoke(t, agentID, memberA) {+ t.Errorf("member A (on member target) should be able to invoke")+ }+ if canMemberInvoke(t, agentID, memberB) {+ t.Errorf("member B should NOT invoke — only a (inert) team target applies to them")+ }+}++// TestUpdateAgent_BatchReplaceOverlappingMembers verifies the create/update+// path replaces the WHOLE allow-list (not one row) and that overlapping+// members survive the replace while removed ones lose access.+func TestUpdateAgent_BatchReplaceOverlappingMembers(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ memberA := createPermissionTestMember(t, "[email protected]")+ memberB := createPermissionTestMember(t, "[email protected]")+ memberC := createPermissionTestMember(t, "[email protected]")++ agentID := createPublicToAgentWithTargets(t, "batch-replace-agent", []map[string]any{+ {"target_type": "member", "target_id": memberA},+ {"target_type": "member", "target_id": memberB},+ })+ if !canMemberInvoke(t, agentID, memberA) || !canMemberInvoke(t, agentID, memberB) {+ t.Fatalf("initial: A and B should both invoke")+ }+ if canMemberInvoke(t, agentID, memberC) {+ t.Fatalf("initial: C should not invoke")+ }++ // Batch-replace the allow-list with an overlapping set: drop A, keep B, add C.+ w := httptest.NewRecorder()+ r := newRequest("PUT", "/api/agents/"+agentID, map[string]any{+ "permission_mode": "public_to",+ "invocation_targets": []map[string]any{+ {"target_type": "member", "target_id": memberB},+ {"target_type": "member", "target_id": memberC},+ },+ })+ r = withURLParam(r, "id", agentID)+ testHandler.UpdateAgent(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("update: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ if n := invocationTargetCount(t, agentID); n != 2 {+ t.Errorf("after batch replace expected exactly 2 targets, got %d (stale rows not cleared?)", n)+ }+ if canMemberInvoke(t, agentID, memberA) {+ t.Errorf("A was removed and must no longer invoke")+ }+ if !canMemberInvoke(t, agentID, memberB) {+ t.Errorf("B overlapped both sets and must still invoke")+ }+ if !canMemberInvoke(t, agentID, memberC) {+ t.Errorf("C was added and must now invoke")+ }+}++// TestUpdateAgent_WorkspaceStacksWithMembersThenNarrowed verifies workspace and+// member targets stack (workspace admits any member via OR), and that a+// subsequent batch replace to a member-only set narrows access correctly.+func TestUpdateAgent_WorkspaceStacksWithMembersThenNarrowed(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ memberA := createPermissionTestMember(t, "[email protected]")+ memberB := createPermissionTestMember(t, "[email protected]")++ agentID := createPublicToAgentWithTargets(t, "workspace-plus-member-agent", []map[string]any{+ {"target_type": "workspace"},+ {"target_type": "member", "target_id": memberA},+ })+ // Workspace target admits ANY workspace member via OR, including B who is+ // not on an explicit member target.+ if !canMemberInvoke(t, agentID, memberA) || !canMemberInvoke(t, agentID, memberB) {+ t.Fatalf("workspace target should admit any member (A and B)")+ }++ // Narrow to member C only — workspace grant is dropped by the replace.+ memberC := createPermissionTestMember(t, "[email protected]")+ w := httptest.NewRecorder()+ r := newRequest("PUT", "/api/agents/"+agentID, map[string]any{+ "permission_mode": "public_to",+ "invocation_targets": []map[string]any{+ {"target_type": "member", "target_id": memberC},+ },+ })+ r = withURLParam(r, "id", agentID)+ testHandler.UpdateAgent(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("narrow update: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if canMemberInvoke(t, agentID, memberB) {+ t.Errorf("after dropping workspace target, non-listed member B must lose access")+ }+ if !canMemberInvoke(t, agentID, memberC) {+ t.Errorf("member C must have access after the replace")+ }+}++// TestCreateAgent_EmptyPublicToNormalizesToWorkspace locks the MUL-3963 review+// ruling: a public_to agent with no invocation targets is a phantom, so the+// backend normalises it to a single workspace target (and therefore derived+// visibility "workspace"). This also covers `--permission-mode public_to`+// alone from the CLI, which sends permission_mode without targets.+func TestCreateAgent_EmptyPublicToNormalizesToWorkspace(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ testHandler.CreateAgent(w, newRequest("POST", "/api/agents?workspace_id="+testWorkspaceID, map[string]any{+ "name": "empty-public-to-agent",+ "runtime_id": handlerTestRuntimeID(t),+ "permission_mode": "public_to",+ // no invocation_targets on purpose+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var resp AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, resp.ID) })++ if resp.PermissionMode != "public_to" {+ t.Errorf("permission_mode = %q, want public_to", resp.PermissionMode)+ }+ if resp.Visibility != "workspace" {+ t.Errorf("empty public_to should derive visibility=workspace, got %q", resp.Visibility)+ }+ foundWorkspace := false+ for _, tgt := range resp.InvocationTargets {+ if tgt.TargetType == "workspace" {+ foundWorkspace = true+ }+ }+ if !foundWorkspace {+ t.Errorf("empty public_to must normalise to a workspace target, got %+v", resp.InvocationTargets)+ }+ // And any workspace member can then invoke it.+ someMember := createPermissionTestMember(t, "[email protected]")+ if !canMemberInvoke(t, resp.ID, someMember) {+ t.Errorf("a workspace member should be able to invoke the normalised public_to-workspace agent")+ }+}++// TestCanInvokeAgent_SystemWorkspaceExceptionAndMemberFailClosed locks the+// product-approved exception (MUL-3963): a system / no-human-originator trigger+// MAY hit a workspace target (webhook / workspace-wide automation), but MUST+// fail closed against a member/team target when no originator resolves.+func TestCanInvokeAgent_SystemWorkspaceExceptionAndMemberFailClosed(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ // public_to workspace agent → system trigger (no originator) is admitted.+ wsAgentID := createPublicToAgentWithTargets(t, "sys-exception-workspace-agent", []map[string]any{+ {"target_type": "workspace"},+ })+ wsAgent, err := testHandler.Queries.GetAgent(ctx, util.MustParseUUID(wsAgentID))+ if err != nil {+ t.Fatalf("load ws agent: %v", err)+ }+ if !testHandler.canInvokeAgent(ctx, wsAgent, "system", "", "", testWorkspaceID) {+ t.Errorf("system trigger should hit a workspace target (product-approved exception)")+ }+ if !testHandler.canInvokeAgent(ctx, wsAgent, "agent", "", "", testWorkspaceID) {+ t.Errorf("agent trigger with no originator should still hit a workspace target")+ }++ // public_to member-only agent → system / unattributed agent trigger must+ // fail closed (member target requires a resolved human originator).+ memberX := createPermissionTestMember(t, "[email protected]")+ memAgentID := createPublicToAgentWithTargets(t, "sys-exception-member-agent", []map[string]any{+ {"target_type": "member", "target_id": memberX},+ })+ memAgent, err := testHandler.Queries.GetAgent(ctx, util.MustParseUUID(memAgentID))+ if err != nil {+ t.Fatalf("load member agent: %v", err)+ }+ if testHandler.canInvokeAgent(ctx, memAgent, "system", "", "", testWorkspaceID) {+ t.Errorf("system trigger must FAIL CLOSED against a member target with no originator")+ }+ if testHandler.canInvokeAgent(ctx, memAgent, "agent", "", "", testWorkspaceID) {+ t.Errorf("agent trigger with no originator must FAIL CLOSED against a member target")+ }+ // But the actual member (as originator) is admitted.+ if !testHandler.canInvokeAgent(ctx, memAgent, "agent", "", memberX, testWorkspaceID) {+ t.Errorf("agent trigger whose originator IS the targeted member should be admitted")+ }+}++// TestRevokeMember_ClearsInvocationTargets is the MUL-3963 review regression:+// removing a member must prune their member-target invocation grants (there is+// no DB FK), and a re-invited user must NOT silently reclaim the old grant.+func TestRevokeMember_ClearsInvocationTargets(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ memberX := createPermissionTestMember(t, "[email protected]")+ agentID := createPublicToAgentWithTargets(t, "revoke-member-target-agent", []map[string]any{+ {"target_type": "member", "target_id": memberX},+ })+ if !canMemberInvoke(t, agentID, memberX) {+ t.Fatalf("member X should be able to invoke before removal")+ }++ // Resolve the member row id for the revoke call.+ var memberRowID string+ if err := testPool.QueryRow(ctx,+ `SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2`,+ testWorkspaceID, memberX,+ ).Scan(&memberRowID); err != nil {+ t.Fatalf("load member row: %v", err)+ }++ if _, err := testHandler.revokeAndRemoveMember(ctx,+ util.MustParseUUID(testWorkspaceID),+ util.MustParseUUID(memberX),+ util.MustParseUUID(memberRowID),+ util.MustParseUUID(testUserID),+ ); err != nil {+ t.Fatalf("revokeAndRemoveMember: %v", err)+ }++ // The member-target grant must be gone.+ if n := invocationTargetCount(t, agentID); n != 0 {+ t.Errorf("member target should be pruned on removal, still have %d", n)+ }+ if canMemberInvoke(t, agentID, memberX) {+ t.Errorf("removed member must no longer invoke the agent")+ }++ // Re-invite the same user: they must NOT reclaim the old grant.+ if _, err := testPool.Exec(ctx,+ `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,+ testWorkspaceID, memberX,+ ); err != nil {+ t.Fatalf("re-invite member: %v", err)+ }+ if canMemberInvoke(t, agentID, memberX) {+ t.Errorf("re-invited member must NOT reclaim the stale invocation grant")+ }+}++// TestRevokeMember_InvocationTargetCleanupIsWorkspaceScoped locks the 3rd-review+// fix (MUL-3963): removing a user from ONE workspace must only prune their+// member-target invocation grants in THAT workspace. A user who belongs to+// multiple workspaces must keep their grants in the workspaces they remain in.+func TestRevokeMember_InvocationTargetCleanupIsWorkspaceScoped(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ userX := createPermissionTestMember(t, "[email protected]")++ // Workspace A (the shared test workspace): an agent allow-lists userX.+ agentA := createPublicToAgentWithTargets(t, "xws-agent-a", []map[string]any{+ {"target_type": "member", "target_id": userX},+ })++ // Workspace B: fresh workspace with its own runtime + agent that also+ // allow-lists the same userX.+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = 'xws-b-perm-test'`)+ var wsB string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ('XWS B', 'xws-b-perm-test', '', 'XWB')+ RETURNING id+ `).Scan(&wsB); err != nil {+ t.Fatalf("create workspace B: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsB) })++ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`, wsB, testUserID); err != nil {+ t.Fatalf("add owner to B: %v", err)+ }+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`, wsB, userX); err != nil {+ t.Fatalf("add userX to B: %v", err)+ }+ var rtB string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at+ )+ VALUES ($1, NULL, 'xws-b-rt', 'cloud', 'handler_test_runtime', 'online', 'dev', '{}'::jsonb, $2, now())+ RETURNING id+ `, wsB, testUserID).Scan(&rtB); err != nil {+ t.Fatalf("create runtime B: %v", err)+ }+ var agentB string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id+ )+ VALUES ($1, 'xws-agent-b', '', 'cloud', '{}'::jsonb, $2, 'private', 'public_to', 1, $3)+ RETURNING id+ `, wsB, rtB, testUserID).Scan(&agentB); err != nil {+ t.Fatalf("create agent B: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id) VALUES ($1, 'member', $2)+ `, agentB, userX); err != nil {+ t.Fatalf("seed B member target: %v", err)+ }++ if invocationTargetCount(t, agentA) != 1 || invocationTargetCount(t, agentB) != 1 {+ t.Fatalf("setup: expected one member target on each of A and B")+ }++ // Remove userX from workspace A only.+ var memberRowA string+ if err := testPool.QueryRow(ctx,+ `SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userX,+ ).Scan(&memberRowA); err != nil {+ t.Fatalf("load member row A: %v", err)+ }+ if _, err := testHandler.revokeAndRemoveMember(ctx,+ util.MustParseUUID(testWorkspaceID),+ util.MustParseUUID(userX),+ util.MustParseUUID(memberRowA),+ util.MustParseUUID(testUserID),+ ); err != nil {+ t.Fatalf("revokeAndRemoveMember(A): %v", err)+ }++ if n := invocationTargetCount(t, agentA); n != 0 {+ t.Errorf("workspace A target should be pruned on removal, got %d", n)+ }+ if n := invocationTargetCount(t, agentB); n != 1 {+ t.Errorf("workspace B target MUST survive removal from A (cross-workspace collateral), got %d", n)+ }+}++// createPermissionTestAdmin inserts a fresh workspace member with the admin+// role and returns its user id.+func createPermissionTestAdmin(t *testing.T, email string) string {+ t.Helper()+ ctx := context.Background()+ var userID string+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`, email, email).Scan(&userID); err != nil {+ t.Fatalf("create admin user %s: %v", email, err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID) })+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')`, testWorkspaceID, userID); err != nil {+ t.Fatalf("add admin %s: %v", email, err)+ }+ return userID+}++// TestUpdateAgent_AccessChangeIsOwnerOnly locks the interaction-bug fix+// (separate PR): a workspace ADMIN who is NOT the agent owner may edit other+// agent fields but must NOT change access — a real permission change returns an+// explicit 403 (no more silent "bounce back"), while a no-op resubmit and+// edits to other fields still succeed. The agent owner can change access.+func TestUpdateAgent_AccessChangeIsOwnerOnly(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ // Agent owned by testUserID, public_to workspace (createHandlerTestAgent).+ agentID := createHandlerTestAgent(t, "owner-only-access-agent", nil)+ adminID := createPermissionTestAdmin(t, "[email protected]")++ put := func(actorID string, body map[string]any) int {+ rec := httptest.NewRecorder()+ r := newRequestAs(actorID, "PUT", "/api/agents/"+agentID, body)+ r = withURLParam(r, "id", agentID)+ testHandler.UpdateAgent(rec, r)+ return rec.Code+ }++ // Admin (non-owner) attempts a REAL access change → 403.+ rec := httptest.NewRecorder()+ r := newRequestAs(adminID, "PUT", "/api/agents/"+agentID, map[string]any{"permission_mode": "private"})+ r = withURLParam(r, "id", agentID)+ testHandler.UpdateAgent(rec, r)+ if rec.Code != http.StatusForbidden {+ t.Fatalf("admin access change: expected 403, got %d: %s", rec.Code, rec.Body.String())+ }+ // Access must be unchanged (still public_to workspace).+ if a, _ := testHandler.Queries.GetAgent(ctx, util.MustParseUUID(agentID)); a.PermissionMode != "public_to" {+ t.Errorf("access must be unchanged after rejected admin write, got %q", a.PermissionMode)+ }++ // Admin no-op resubmit of the CURRENT permission (PATCH-as-PUT) → tolerated.+ if code := put(adminID, map[string]any{+ "permission_mode": "public_to",+ "invocation_targets": []map[string]any{{"target_type": "workspace"}},+ }); code != http.StatusOK {+ t.Errorf("admin no-op permission resubmit: expected 200, got %d", code)+ }++ // Admin editing a NON-permission field still works.+ if code := put(adminID, map[string]any{"description": "renamed by admin"}); code != http.StatusOK {+ t.Errorf("admin editing other fields: expected 200, got %d", code)+ }++ // The owner CAN change access.+ if code := put(testUserID, map[string]any{"permission_mode": "private"}); code != http.StatusOK {+ t.Errorf("owner access change: expected 200, got %d", code)+ }+ if n := invocationTargetCount(t, agentID); n != 0 {+ t.Errorf("owner set private: expected 0 targets, got %d", n)+ }+}++// TestUpdateAgent_LegacyVisibilityNoOpForMemberOnlyPublicTo locks the PR #4853+// compatibility fix: a member-only public_to agent DERIVES legacy visibility+// "private", so an admin (non-owner) echoing visibility:"private" via an old+// client / PATCH-as-PUT while editing another field must be treated as a NO-OP+// (200, targets unchanged) — not misread as a public_to→private downgrade+// (403). Submitting visibility:"workspace" is a real change and still 403.+func TestUpdateAgent_LegacyVisibilityNoOpForMemberOnlyPublicTo(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ memberX := createPermissionTestMember(t, "[email protected]")+ agentID := createPublicToAgentWithTargets(t, "legacy-vis-member-only-agent", []map[string]any{+ {"target_type": "member", "target_id": memberX},+ })+ adminID := createPermissionTestAdmin(t, "[email protected]")++ put := func(actorID string, body map[string]any) int {+ rec := httptest.NewRecorder()+ r := newRequestAs(actorID, "PUT", "/api/agents/"+agentID, body)+ r = withURLParam(r, "id", agentID)+ testHandler.UpdateAgent(rec, r)+ return rec.Code+ }++ // Derived legacy visibility of a member-only public_to agent is "private".+ // Admin echoing that back while editing description → 200 no-op.+ if code := put(adminID, map[string]any{"visibility": "private", "description": "admin note"}); code != http.StatusOK {+ t.Fatalf("admin legacy visibility=private no-op: expected 200, got %d", code)+ }+ // Access must be untouched: still public_to with the one member target.+ if a, _ := testHandler.Queries.GetAgent(ctx, util.MustParseUUID(agentID)); a.PermissionMode != "public_to" {+ t.Errorf("permission_mode must stay public_to after legacy no-op, got %q", a.PermissionMode)+ }+ if n := invocationTargetCount(t, agentID); n != 1 {+ t.Errorf("member target must be intact after legacy no-op, got %d targets", n)+ }++ // Admin submitting a REAL legacy change (workspace) is still rejected.+ if code := put(adminID, map[string]any{"visibility": "workspace"}); code != http.StatusForbidden {+ t.Errorf("admin legacy visibility=workspace (real change): expected 403, got %d", code)+ }+}diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex f75cef3d20..af4769c09c 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -1380,7 +1380,7 @@ func (h *Handler) validateAutopilotAssignee(w http.ResponseWriter, r *http.Reque// Private-leader gate: the member configuring the autopilot must have// access to the private leader, same as validateAssigneePair.actorType, actorID := h.resolveActor(r, requestUserID(r), util.UUIDToString(workspaceID))- if !h.canAccessPrivateAgent(r.Context(), leader, actorType, actorID, util.UUIDToString(workspaceID)) {+ if !h.canInvokeAgent(r.Context(), leader, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), util.UUIDToString(workspaceID)) {writeError(w, http.StatusForbidden, "cannot assign autopilot to squad with private leader")return false}diff --git a/server/internal/handler/autopilot_private_leader_test.go b/server/internal/handler/autopilot_private_leader_test.goindex 0a84ffc739..d615dea3ac 100644--- a/server/internal/handler/autopilot_private_leader_test.go+++ b/server/internal/handler/autopilot_private_leader_test.go@@ -110,7 +110,7 @@ func TestCreateAutopilot_SquadPrivateLeader_OwnerAllowed(t *testing.T) {}ctx := context.Background()- agentID, _, _ := privateAgentTestFixture(t)+ agentID, ownerID, _ := privateAgentTestFixture(t)var squadID stringif err := testPool.QueryRow(ctx, `@@ -124,9 +124,10 @@ func TestCreateAutopilot_SquadPrivateLeader_OwnerAllowed(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID)})- // testUserID is workspace owner — should succeed.+ // The AGENT OWNER creates the autopilot — allowed under MUL-3963 (workspace+ // owner/admin no longer bypasses a private leader's invocation gate).w := httptest.NewRecorder()- r := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{+ r := newRequestAs(ownerID, "POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "owner creates private-leader squad ap","assignee_type": "squad","assignee_id": squadID,@@ -154,7 +155,7 @@ func TestTriggerAutopilot_SquadPrivateLeader_OwnerCanDispatch(t *testing.T) {}ctx := context.Background()- agentID, _, _ := privateAgentTestFixture(t)+ agentID, ownerID, _ := privateAgentTestFixture(t)var squadID stringif err := testPool.QueryRow(ctx, `@@ -168,9 +169,10 @@ func TestTriggerAutopilot_SquadPrivateLeader_OwnerCanDispatch(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID)})- // Create autopilot as owner.+ // Create autopilot as the AGENT OWNER (MUL-3963: only owner/allow-listed+ // may invoke the private leader; workspace admin no longer bypasses).w := httptest.NewRecorder()- r := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{+ r := newRequestAs(ownerID, "POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "dispatch test private leader squad","assignee_type": "squad","assignee_id": squadID,diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 90718a81d6..ed9a1c66df 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -71,11 +71,11 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "agent is archived")return}- // Private-agent gate: members must be in allowed_principals to start- // a chat with a private agent. Agent-to-agent chat sessions bypass- // the gate so A2A collaboration still works.+ // Invocation gate: starting a chat produces agent runs, so it uses the+ // invoke permission (MUL-3963), not the softer view gate. Agent-to-agent+ // chat sessions are judged by the top-of-chain originator.actorType, actorID := h.resolveActor(r, userID, workspaceID)- if !h.canAccessPrivateAgent(r.Context(), agent, actorType, actorID, workspaceID) {+ if !h.canInvokeAgent(r.Context(), agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {writeError(w, http.StatusForbidden, "you do not have access to this agent")return}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex b1bf21a505..0ec69be0b2 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1042,6 +1042,11 @@ type commentAgentTrigger struct {type commentTriggerComputeOptions struct {ExcludeTriggerCommentID pgtype.UUID+ // OriginatorUserID is the top-of-chain human user id for this trigger+ // (MUL-3963). Only consulted for AGENT actors — canInvokeAgent judges A2A+ // by the originator, not the immediate agent principal. Members are their+ // own originator so this may be empty for member-authored triggers.+ OriginatorUserID string}func commentAgentTriggerReason(trigger commentAgentTrigger) string {@@ -1140,6 +1145,7 @@ func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request)}actorType, actorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))+ opts.OriginatorUserID = h.invokeOriginatorFromRequest(r, actorType, actorID)triggers := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID, opts)resp := CommentTriggerPreviewResponse{Agents: make([]CommentTriggerAgentResponse, 0, len(triggers))}for _, trigger := range triggers {@@ -1303,7 +1309,8 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {h.TaskService.CancelDeferredEscalationsForIssueAgent(r.Context(), issue.ID, comment.AuthorID)}- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, suppressAgentIDs)+ originatorUserID := h.invokeOriginatorFromRequest(r, authorType, authorID)+ h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, suppressAgentIDs)writeJSON(w, http.StatusCreated, resp)}@@ -1326,12 +1333,13 @@ func isNoteComment(content string) bool {return strings.EqualFold(firstToken, noteCommentPrefix)}-func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID string, suppressAgentIDs []pgtype.UUID) {+func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID string, suppressAgentIDs []pgtype.UUID) {if isNoteComment(comment.Content) {return}triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{ExcludeTriggerCommentID: comment.ID,+ OriginatorUserID: originatorUserID,})triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)@@ -1542,7 +1550,7 @@ func (h *Handler) routeReplyToParentAuthor(ctx context.Context, issue db.Issue,if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {return commentAgentTrigger{}, false}- if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, uuidToString(issue.WorkspaceID)) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {return commentAgentTrigger{}, false}hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, parent.AuthorID, opts)@@ -1660,7 +1668,7 @@ func (h *Handler) routeConversationContinuationToAgent(ctx context.Context, issuif err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {return commentAgentTrigger{}, false}- if !h.canAccessPrivateAgent(ctx, agent, "member", memberID, uuidToString(issue.WorkspaceID)) {+ if !h.canInvokeAgent(ctx, agent, "member", memberID, memberID, uuidToString(issue.WorkspaceID)) {return commentAgentTrigger{}, false}hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentID, opts)@@ -1716,7 +1724,7 @@ func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue dbif err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {return commentAgentTrigger{}, false}- if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, uuidToString(issue.WorkspaceID)) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {return commentAgentTrigger{}, false}hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, squad.LeaderID, opts)@@ -1797,7 +1805,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issucontinue}// Private-agent gate: prevent triggering a private leader via squad mention.- if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, wsID) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {continue}hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, leaderID, opts)@@ -1826,7 +1834,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu}// Private-agent gate (member→private requires allowed_principals;// agent→agent always passes).- if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, wsID) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {continue}hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentUUID, opts)@@ -1960,7 +1968,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {}}- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, suppressAgentIDs)+ h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)}}diff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 3eb2d509da..267ae2d65f 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -7,6 +7,7 @@ import ("strings""github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/featureflags")type AppConfig struct {@@ -44,6 +45,10 @@ type AppConfig struct {PosthogKey string `json:"posthog_key"`PosthogHost string `json:"posthog_host"`AnalyticsEnvironment string `json:"analytics_environment"`++ // FeatureFlags exposes only frontend-safe boolean decisions. Do not dump+ // raw rules here: /api/config is public and may be called anonymously.+ FeatureFlags map[string]bool `json:"feature_flags,omitempty"`}// GetConfig is mounted on the public (unauthenticated) route group because@@ -61,6 +66,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {}config.CdnSigned = h.CFSigner != nilconfig.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()+ config.FeatureFlags = featureflags.EvaluateFrontendPublicFlags(r.Context(), h.FeatureFlags)// Re-read from env on every request so operators can rotate keys via// secret refresh without a server restart.diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 076a61a31c..eb3a650aae 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -286,3 +286,33 @@ func TestGetConfigExposesWorkspaceCreationDisabled(t *testing.T) {t.Fatalf("workspace_creation_disabled: want true with env on, got false (body=%s)", w.Body.String())}}++func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {+ h := &Handler{}+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)+ w := httptest.NewRecorder()+ h.GetConfig(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetConfig default flags: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var cfg AppConfig+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode default config: %v", err)+ }+ if cfg.FeatureFlags["composio_mcp_apps"] {+ t.Fatalf("composio_mcp_apps: want false by default, got true")+ }++ withComposioMCPAppsFlag(t, h, true)+ w = httptest.NewRecorder()+ h.GetConfig(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetConfig enabled flags: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode enabled config: %v", err)+ }+ if !cfg.FeatureFlags["composio_mcp_apps"] {+ t.Fatalf("composio_mcp_apps: want true with flag enabled, got false")+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 78c664c4ce..631f2b7e98 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -23,6 +23,7 @@ import ("github.com/multica-ai/multica/server/internal/integrations/slack"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/runtimeapps""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -1229,6 +1230,22 @@ func requestHasDaemonCapability(r *http.Request, capability string) bool {return false}+func parseRuntimeConnectedAppsForClaim(raw []byte, taskID pgtype.UUID) []runtimeapps.ConnectedApp {+ raw = bytes.TrimSpace(raw)+ if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {+ return nil+ }+ var apps []runtimeapps.ConnectedApp+ if err := json.Unmarshal(raw, &apps); err != nil {+ slog.Warn("daemon claim: unmarshal runtime_connected_apps failed",+ "task_id", uuidToString(taskID),+ "error", err,+ )+ return nil+ }+ return apps+}+// ClaimTaskByRuntime atomically claims the next queued task for a runtime.// The response includes the agent's name and skills, fetched fresh from the DB.func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {@@ -1287,6 +1304,10 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {// Build response with fresh agent data (name + skills + custom_env + custom_args).resp := taskToResponse(*task, runtimeWorkspaceID)+ composioMCPEnabled := h.composioMCPAppsEnabled(r.Context())+ if composioMCPEnabled {+ resp.ConnectedApps = parseRuntimeConnectedAppsForClaim(task.RuntimeConnectedApps, task.ID)+ }if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {useSkillRefs := requestHasDaemonCapability(r, protocol.DaemonCapabilitySkillBundlesV1)var customEnv map[string]string@@ -1305,6 +1326,19 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if agent.McpConfig != nil {mcpConfig = json.RawMessage(agent.McpConfig)}+ // Layer the per-task overlay (set at enqueue from the initiator+ // user's active integrations — currently Composio) on top of the+ // agent's saved mcp_config. Overlay wins on server-name collisions+ // because it carries the live user-scoped session URL. Errors are+ // logged but never fail the claim: a broken overlay must not prevent+ // the agent from running with its base config.+ if composioMCPEnabled && len(task.RuntimeMcpOverlay) > 0 {+ if merged, err := mergeMCPOverlay(mcpConfig, json.RawMessage(task.RuntimeMcpOverlay)); err != nil {+ slog.Warn("daemon claim: merge runtime_mcp_overlay failed; falling back to agent mcp_config", "task_id", uuidToString(task.ID), "error", err)+ } else {+ mcpConfig = merged+ }+ }// runtime_config is stored as JSONB and may legitimately be the// empty object `{}` for agents that haven't opted into any// provider-specific tuning. Forward only non-empty payloads so thediff --git a/server/internal/handler/featureflag_test.go b/server/internal/handler/featureflag_test.gonew file mode 100644index 0000000000..121ebf75e0--- /dev/null+++ b/server/internal/handler/featureflag_test.go@@ -0,0 +1,29 @@+package handler++import (+ "testing"++ "github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/pkg/featureflag"+)++func withComposioMCPAppsFlag(t *testing.T, h *Handler, enabled bool) {+ t.Helper()+ provider := featureflag.NewStaticProvider()+ provider.Set(featureflags.ComposioMCPApps, featureflag.Rule{Default: enabled})+ flags := featureflag.NewService(provider)++ origHandlerFlags := h.FeatureFlags+ h.FeatureFlags = flags+ var origTaskFlags *featureflag.Service+ if h.TaskService != nil {+ origTaskFlags = h.TaskService.FeatureFlags+ h.TaskService.FeatureFlags = flags+ }+ t.Cleanup(func() {+ h.FeatureFlags = origHandlerFlags+ if h.TaskService != nil {+ h.TaskService.FeatureFlags = origTaskFlags+ }+ })+}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 1d97efc3ce..33f857c1d6 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -22,6 +22,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/featureflagdispatch""github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ composio "github.com/multica-ai/multica/server/internal/integrations/composio""github.com/multica-ai/multica/server/internal/integrations/lark""github.com/multica-ai/multica/server/internal/integrations/slack"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"@@ -31,6 +32,7 @@ import ("github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/featureflag")// randomID returns a random 16-byte hex string used as a request ID for@@ -119,6 +121,7 @@ type Handler struct {ModelListStore ModelListStoreLocalSkillListStore LocalSkillListStoreLocalSkillImportStore LocalSkillImportStore+ FeatureFlags *featureflag.ServiceDaemonFeatureFlags *featureflagdispatch.EvaluatorLivenessStore LivenessStoreHeartbeatScheduler HeartbeatScheduler@@ -158,6 +161,10 @@ type Handler struct {// UI consults IsConfigured() to decide whether to surface install// entry points.LarkAPIClient lark.APIClient+ // Composio integration (MUL-3720). Nil when COMPOSIO_API_KEY is unset;+ // the composio HTTP handlers return 503 in that case. Wired in+ // cmd/server/router.go after handler.New.+ Composio *composio.Service// ChannelSupervisor owns the per-installation supervisor goroutines// that hold the §4.4 WS lease and drive each channel.Channel// (MUL-3620 generalized the Feishu-only Hub into this channel-agnosticdiff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex 38a314cdaa..1162c26430 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -130,13 +130,24 @@ func setupHandlerTestFixture(ctx context.Context, pool *pgxpool.Pool) (string, s}testRuntimeID = runtimeID- if _, err := pool.Exec(ctx, `+ var seededAgentID string+ if err := pool.QueryRow(ctx, `INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config,- runtime_id, visibility, max_concurrent_tasks, owner_id+ runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id)- VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 1, $4)- `, workspaceID, "Handler Test Agent", runtimeID, userID); err != nil {+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 'public_to', 1, $4)+ RETURNING id+ `, workspaceID, "Handler Test Agent", runtimeID, userID).Scan(&seededAgentID); err != nil {+ return "", "", err+ }+ // MUL-3963: the seeded workspace-visible agent is invocable by workspace+ // members and A2A triggers, so seed its workspace invocation target.+ if _, err := pool.Exec(ctx, `+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id)+ VALUES ($1, 'workspace', $2)+ ON CONFLICT (agent_id, target_type, target_id) DO NOTHING+ `, seededAgentID, workspaceID); err != nil {return "", "", err}@@ -208,14 +219,26 @@ func createHandlerTestAgent(t *testing.T, name string, mcpConfig []byte) stringif err := testPool.QueryRow(context.Background(), `INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config,- runtime_id, visibility, max_concurrent_tasks, owner_id,+ runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id,instructions, custom_env, custom_args, mcp_config)- VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4, '', '{}'::jsonb, '[]'::jsonb, $5)+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 'public_to', 1, $4, '', '{}'::jsonb, '[]'::jsonb, $5)RETURNING id`, testWorkspaceID, name, handlerTestRuntimeID(t), testUserID, mcpConfig).Scan(&agentID); err != nil {t.Fatalf("failed to create handler test agent: %v", err)}+ // Generic test agents are workspace-invocable (MUL-3963): seed the+ // matching workspace invocation target so canInvokeAgent admits workspace+ // members and A2A triggers, mirroring the pre-permission-model behavior+ // where a workspace-visible agent could be triggered by anyone in the+ // workspace. Dedicated private-agent tests use privateAgentTestFixture.+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id)+ VALUES ($1, 'workspace', $2)+ ON CONFLICT (agent_id, target_type, target_id) DO NOTHING+ `, agentID, testWorkspaceID); err != nil {+ t.Fatalf("failed to seed workspace invocation target: %v", err)+ }t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)diff --git a/server/internal/handler/integrations_composio.go b/server/internal/handler/integrations_composio.gonew file mode 100644index 0000000000..126016b69d--- /dev/null+++ b/server/internal/handler/integrations_composio.go@@ -0,0 +1,225 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/featureflags"+ composio "github.com/multica-ai/multica/server/internal/integrations/composio"+)++// Composio integration handlers (MUL-3720, Stage 2 MVP). A Composio connection+// belongs to a user, not a workspace, so these handlers live outside the+// workspace-membership group. The four management endpoints (connect/init,+// toolkits, connections, delete) are user-scoped (requireUserID) and sit under+// the Auth middleware. ComposioCallback is the exception: it is a public route+// (outside the Auth group, see router.go / MUL-3843) because the browser often+// arrives without a session cookie — its identity comes from the signed state,+// not requireUserID. The whole block returns 503 when h.Composio is nil+// (COMPOSIO_API_KEY unset), matching the Lark/GitHub "integration not+// configured" convention.++// ComposioConnectInitRequest is the POST /connect/init body.+type ComposioConnectInitRequest struct {+ ToolkitSlug string `json:"toolkit_slug"`+}++// ComposioConnectInitResponse carries the hosted Composio Connect Link the+// frontend redirects the user to.+type ComposioConnectInitResponse struct {+ RedirectURL string `json:"redirect_url"`+}++// ComposioConnectionResponse is the wire shape for one connection row.+type ComposioConnectionResponse struct {+ ID string `json:"id"`+ ToolkitSlug string `json:"toolkit_slug"`+ Status string `json:"status"`+ ConnectedAt string `json:"connected_at"`+ LastUsedAt *string `json:"last_used_at"`+}++// ComposioToolkitResponse is the wire shape for one toolkit in the catalog.+// connectable is the key UX signal: false means the project has no enabled+// auth config for the toolkit, so the UI must not offer a working Connect+// button (BeginConnect would 400).+type ComposioToolkitResponse struct {+ Slug string `json:"slug"`+ Name string `json:"name"`+ Logo string `json:"logo,omitempty"`+ Category string `json:"category,omitempty"`+ Connectable bool `json:"connectable"`+}++func (h *Handler) composioMCPAppsEnabled(ctx context.Context) bool {+ return featureflags.ComposioMCPAppsEnabled(ctx, h.FeatureFlags)+}++// ComposioConnectInit (POST /api/integrations/composio/connect/init) starts a+// hosted Composio auth flow for the requested toolkit and returns the redirect+// URL. An unsupported toolkit slug is a 400 (the MVP only wires Notion).+func (h *Handler) ComposioConnectInit(w http.ResponseWriter, r *http.Request) {+ if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {+ writeError(w, http.StatusServiceUnavailable, "composio integration not configured")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }+ var req ComposioConnectInitRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if strings.TrimSpace(req.ToolkitSlug) == "" {+ writeError(w, http.StatusBadRequest, "toolkit_slug is required")+ return+ }++ redirectURL, err := h.Composio.BeginConnect(r.Context(), userUUID, req.ToolkitSlug)+ if err != nil {+ if errors.Is(err, composio.ErrToolkitNotSupported) {+ writeError(w, http.StatusBadRequest, "toolkit not supported")+ return+ }+ writeError(w, http.StatusBadGateway, "failed to start composio connect")+ return+ }+ writeJSON(w, http.StatusOK, ComposioConnectInitResponse{RedirectURL: redirectURL})+}++// ComposioCallback (GET /api/integrations/composio/callback) is the browser+// redirect target Composio sends the user back to after the hosted flow. It is+// registered as a PUBLIC route (outside the Auth middleware group — see+// router.go / MUL-3843), because the browser frequently lands here without a+// session cookie (expired session, SameSite/ITP stripping, private window,+// self-hosted callback subdomain). Identity therefore comes solely from the+// HMAC-signed `state` query param, which CompleteCallback verifies before+// doing anything. On success the row is upserted and the browser is redirected+// to the settings page; any failure redirects to the same page with a stable+// error code so the user is never left on a blank API response.+func (h *Handler) ComposioCallback(w http.ResponseWriter, r *http.Request) {+ if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {+ writeError(w, http.StatusServiceUnavailable, "composio integration not configured")+ return+ }+ q := r.URL.Query()+ state := q.Get("state")+ status := q.Get("status")+ connectedAccountID := q.Get("connected_account_id")++ slug, err := h.Composio.CompleteCallback(r.Context(), state, status, connectedAccountID)+ if err != nil {+ // Every failure (tampered/expired state, non-success status, write+ // error) collapses to the generic failure redirect — we never tell the+ // browser which check failed.+ http.Redirect(w, r, h.Composio.CallbackRedirect(slug, false), http.StatusFound)+ return+ }+ http.Redirect(w, r, h.Composio.CallbackRedirect(slug, true), http.StatusFound)+}++// ListComposioConnections (GET /api/integrations/composio/connections) returns+// the caller's active connections.+func (h *Handler) ListComposioConnections(w http.ResponseWriter, r *http.Request) {+ if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {+ writeError(w, http.StatusServiceUnavailable, "composio integration not configured")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }+ conns, err := h.Composio.ListConnections(r.Context(), userUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list composio connections")+ return+ }+ out := make([]ComposioConnectionResponse, 0, len(conns))+ for _, c := range conns {+ out = append(out, ComposioConnectionResponse{+ ID: c.ID,+ ToolkitSlug: c.ToolkitSlug,+ Status: c.Status,+ ConnectedAt: c.ConnectedAt,+ LastUsedAt: c.LastUsedAt,+ })+ }+ writeJSON(w, http.StatusOK, out)+}++// ListComposioToolkits (GET /api/integrations/composio/toolkits) returns the+// full Composio toolkit catalog for the Settings UI to render. Each entry+// carries a `connectable` flag: only toolkits with an enabled auth config in+// the project can actually be connected, so the UI gates its Connect button on+// it. The catalog itself is project-global (not per-user), but the route is+// user-scoped (requireUser) like the rest of the block.+func (h *Handler) ListComposioToolkits(w http.ResponseWriter, r *http.Request) {+ if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {+ writeError(w, http.StatusServiceUnavailable, "composio integration not configured")+ return+ }+ if _, ok := requireUserID(w, r); !ok {+ return+ }+ toolkits, err := h.Composio.ListToolkits(r.Context())+ if err != nil {+ writeError(w, http.StatusBadGateway, "failed to list composio toolkits")+ return+ }+ out := make([]ComposioToolkitResponse, 0, len(toolkits))+ for _, tk := range toolkits {+ out = append(out, ComposioToolkitResponse{+ Slug: tk.Slug,+ Name: tk.Name,+ Logo: tk.LogoURL,+ Category: tk.Category,+ Connectable: tk.Connectable,+ })+ }+ writeJSON(w, http.StatusOK, out)+}++// DeleteComposioConnection (DELETE /api/integrations/composio/connections/{id})+// disconnects a connection the caller owns. Idempotent at the service layer;+// a connection that does not belong to the caller is a 404.+func (h *Handler) DeleteComposioConnection(w http.ResponseWriter, r *http.Request) {+ if h.Composio == nil || !h.composioMCPAppsEnabled(r.Context()) {+ writeError(w, http.StatusServiceUnavailable, "composio integration not configured")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }+ connUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "connection id")+ if !ok {+ return+ }+ if err := h.Composio.Disconnect(r.Context(), userUUID, connUUID); err != nil {+ if errors.Is(err, composio.ErrConnectionNotFound) {+ writeError(w, http.StatusNotFound, "composio connection not found")+ return+ }+ writeError(w, http.StatusBadGateway, "failed to disconnect composio connection")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}diff --git a/server/internal/handler/integrations_composio_test.go b/server/internal/handler/integrations_composio_test.gonew file mode 100644index 0000000000..efcade6dbd--- /dev/null+++ b/server/internal/handler/integrations_composio_test.go@@ -0,0 +1,341 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ composio "github.com/multica-ai/multica/server/internal/integrations/composio"+ "github.com/multica-ai/multica/server/internal/util"+ sdk "github.com/multica-ai/multica/server/pkg/composio"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const composioTestUserID = "22222222-2222-2222-2222-222222222222"++// --- local fakes (handler package can only see the exported interfaces) ---++type composioFakeSDK struct {+ createLinkResp *sdk.CreateLinkResponse+ revokeErr error+}++func (f *composioFakeSDK) CreateLink(_ context.Context, _ sdk.CreateLinkRequest) (*sdk.CreateLinkResponse, error) {+ if f.createLinkResp != nil {+ return f.createLinkResp, nil+ }+ return &sdk.CreateLinkResponse{RedirectURL: "https://composio.example/redirect"}, nil+}++// ListConnectedAccounts echoes the requested id as an account owned by the+// handler-test user under the notion auth config, so callback ownership+// verification passes on the happy path.+func (f *composioFakeSDK) ListConnectedAccounts(_ context.Context, req sdk.ListConnectedAccountsRequest) (*sdk.ListConnectedAccountsResponse, error) {+ id := ""+ if len(req.ConnectedAccountIDs) > 0 {+ id = req.ConnectedAccountIDs[0]+ }+ return &sdk.ListConnectedAccountsResponse{Items: []sdk.ConnectedAccount{{+ ID: id,+ UserID: composioTestUserID,+ AuthConfigID: "ac_notion",+ }}}, nil+}+func (f *composioFakeSDK) RevokeConnection(_ context.Context, _ string) error { return f.revokeErr }+func (f *composioFakeSDK) DeleteConnectedAccount(_ context.Context, _ string) error { return nil }++// ListAuthConfigs reports a single enabled notion auth config so BeginConnect+// resolves notion → ac_notion and the callback's auth-config check matches.+func (f *composioFakeSDK) ListAuthConfigs(_ context.Context, _ sdk.ListAuthConfigsRequest) (*sdk.ListAuthConfigsResponse, error) {+ return &sdk.ListAuthConfigsResponse{Items: []sdk.AuthConfig{{+ ID: "ac_notion",+ Toolkit: sdk.Toolkit{Slug: "notion"},+ Status: "ENABLED",+ }}}, nil+}++func (f *composioFakeSDK) ListToolkits(_ context.Context, _ sdk.ListToolkitsRequest) (*sdk.ListToolkitsResponse, error) {+ return &sdk.ListToolkitsResponse{Items: []sdk.Toolkit{+ {Slug: "notion", Name: "Notion"},+ {Slug: "github", Name: "GitHub"},+ }}, nil+}+func (f *composioFakeSDK) CreateSession(_ context.Context, _ sdk.CreateSessionRequest) (*sdk.CreateSessionResponse, error) {+ return &sdk.CreateSessionResponse{}, nil+}+func (f *composioFakeSDK) MCPAuthHeaders() map[string]string {+ return map[string]string{"x-api-key": "k"}+}++type composioFakeStore struct {+ rows []db.UserComposioConnection+ nextID byte+}++func (s *composioFakeStore) UpsertUserComposioConnection(_ context.Context, arg db.UpsertUserComposioConnectionParams) (db.UserComposioConnection, error) {+ for i := range s.rows {+ if s.rows[i].UserID.Bytes == arg.UserID.Bytes && s.rows[i].ConnectedAccountID == arg.ConnectedAccountID {+ s.rows[i].Status = "active"+ return s.rows[i], nil+ }+ }+ s.nextID+++ var b [16]byte+ b[15] = s.nextID+ row := db.UserComposioConnection{+ ID: pgtype.UUID{Bytes: b, Valid: true},+ UserID: arg.UserID,+ ToolkitSlug: arg.ToolkitSlug,+ AuthConfigID: arg.AuthConfigID,+ ConnectedAccountID: arg.ConnectedAccountID,+ ComposioUserID: arg.ComposioUserID,+ Status: "active",+ ConnectedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ }+ s.rows = append(s.rows, row)+ return row, nil+}+func (s *composioFakeStore) ListActiveUserComposioConnections(_ context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error) {+ out := []db.UserComposioConnection{}+ for _, r := range s.rows {+ if r.UserID.Bytes == userID.Bytes && r.Status == "active" {+ out = append(out, r)+ }+ }+ return out, nil+}+func (s *composioFakeStore) GetUserComposioConnection(_ context.Context, arg db.GetUserComposioConnectionParams) (db.UserComposioConnection, error) {+ for _, r := range s.rows {+ if r.ID.Bytes == arg.ID.Bytes && r.UserID.Bytes == arg.UserID.Bytes {+ return r, nil+ }+ }+ return db.UserComposioConnection{}, pgx.ErrNoRows+}+func (s *composioFakeStore) MarkUserComposioConnectionRevoked(_ context.Context, arg db.MarkUserComposioConnectionRevokedParams) error {+ for i := range s.rows {+ if s.rows[i].ID.Bytes == arg.ID.Bytes && s.rows[i].UserID.Bytes == arg.UserID.Bytes {+ s.rows[i].Status = "revoked"+ }+ }+ return nil+}++func newComposioTestHandler(t *testing.T, sdkFake composio.SDK, store composio.Store) *Handler {+ t.Helper()+ svc, err := composio.NewService(sdkFake, store, composio.Config{+ StateSecret: []byte("handler-test-secret"),+ CallbackBaseURL: "https://app.multica.ai",+ FrontendBaseURL: "https://app.multica.ai",+ })+ if err != nil {+ t.Fatalf("NewService: %v", err)+ }+ h := &Handler{Composio: svc}+ withComposioMCPAppsFlag(t, h, true)+ return h+}++func composioReq(method, target, body string) *http.Request {+ var r *http.Request+ if body != "" {+ r = httptest.NewRequest(method, target, strings.NewReader(body))+ } else {+ r = httptest.NewRequest(method, target, nil)+ }+ r.Header.Set("X-User-ID", composioTestUserID)+ return r+}++// --- tests ---++func TestComposio_ServiceUnavailableWhenNil(t *testing.T) {+ h := &Handler{}+ for _, hf := range []http.HandlerFunc{+ h.ComposioConnectInit, h.ComposioCallback, h.ListComposioConnections, h.DeleteComposioConnection,+ } {+ w := httptest.NewRecorder()+ hf(w, composioReq(http.MethodGet, "/", ""))+ if w.Code != http.StatusServiceUnavailable {+ t.Errorf("expected 503 when Composio nil, got %d", w.Code)+ }+ }+}++func TestComposio_ServiceUnavailableWhenFlagDisabled(t *testing.T) {+ h := newComposioTestHandler(t, &composioFakeSDK{}, &composioFakeStore{})+ withComposioMCPAppsFlag(t, h, false)++ w := httptest.NewRecorder()+ h.ListComposioToolkits(w, composioReq(http.MethodGet, "/toolkits", ""))+ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503 when feature flag disabled, got %d", w.Code)+ }+}++func TestComposio_ConnectInit(t *testing.T) {+ h := newComposioTestHandler(t, &composioFakeSDK{}, &composioFakeStore{})++ // success+ w := httptest.NewRecorder()+ h.ComposioConnectInit(w, composioReq(http.MethodPost, "/", `{"toolkit_slug":"notion"}`))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d (%s)", w.Code, w.Body.String())+ }+ var resp ComposioConnectInitResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp.RedirectURL == "" {+ t.Error("expected redirect_url")+ }++ // unsupported toolkit → 400+ w = httptest.NewRecorder()+ h.ComposioConnectInit(w, composioReq(http.MethodPost, "/", `{"toolkit_slug":"github"}`))+ if w.Code != http.StatusBadRequest {+ t.Errorf("unsupported toolkit: expected 400, got %d", w.Code)+ }++ // missing slug → 400+ w = httptest.NewRecorder()+ h.ComposioConnectInit(w, composioReq(http.MethodPost, "/", `{}`))+ if w.Code != http.StatusBadRequest {+ t.Errorf("missing slug: expected 400, got %d", w.Code)+ }+}++func TestComposio_ListToolkits(t *testing.T) {+ h := newComposioTestHandler(t, &composioFakeSDK{}, &composioFakeStore{})++ w := httptest.NewRecorder()+ h.ListComposioToolkits(w, composioReq(http.MethodGet, "/toolkits", ""))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d (%s)", w.Code, w.Body.String())+ }+ var toolkits []ComposioToolkitResponse+ if err := json.Unmarshal(w.Body.Bytes(), &toolkits); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(toolkits) != 2 {+ t.Fatalf("expected 2 toolkits, got %d", len(toolkits))+ }+ // notion has an enabled auth config in the fake → connectable + sorted first.+ if toolkits[0].Slug != "notion" || !toolkits[0].Connectable {+ t.Errorf("first toolkit = %+v, want connectable notion", toolkits[0])+ }+ for _, tk := range toolkits {+ if tk.Slug == "github" && tk.Connectable {+ t.Error("github has no auth config and must not be connectable")+ }+ if tk.Logo == "" {+ t.Errorf("toolkit %q missing logo", tk.Slug)+ }+ }+}++func TestComposio_CallbackRedirects(t *testing.T) {+ store := &composioFakeStore{}++ // Mint a valid signed state by driving BeginConnect through a capturing+ // SDK, then replay it through the real callback handler.+ capturing := &composioCapturingSDK{}+ h2 := newComposioTestHandler(t, capturing, store)+ bw := httptest.NewRecorder()+ h2.ComposioConnectInit(bw, composioReq(http.MethodPost, "/", `{"toolkit_slug":"notion"}`))+ state := capturing.stateFromCallback()+ if state == "" {+ t.Fatal("could not capture signed state")+ }++ w := httptest.NewRecorder()+ h2.ComposioCallback(w, composioReq(http.MethodGet, "/callback?state="+state+"&status=success&connected_account_id=ca_1", ""))+ if w.Code != http.StatusFound {+ t.Fatalf("expected 302, got %d", w.Code)+ }+ if loc := w.Header().Get("Location"); !strings.Contains(loc, "connected=notion") {+ t.Errorf("success location = %q", loc)+ }++ // failure path: bad state → error redirect+ w = httptest.NewRecorder()+ h2.ComposioCallback(w, composioReq(http.MethodGet, "/callback?state=bad&status=success&connected_account_id=ca_1", ""))+ if w.Code != http.StatusFound {+ t.Fatalf("expected 302 on bad state, got %d", w.Code)+ }+ if loc := w.Header().Get("Location"); !strings.Contains(loc, "error=composio_connect_failed") {+ t.Errorf("failure location = %q", loc)+ }+}++func TestComposio_ListAndDelete(t *testing.T) {+ store := &composioFakeStore{}+ userUUID, _ := util.ParseUUID(composioTestUserID)+ row, _ := store.UpsertUserComposioConnection(context.Background(), db.UpsertUserComposioConnectionParams{+ UserID: userUUID,+ ToolkitSlug: "notion",+ AuthConfigID: "ac_notion",+ ConnectedAccountID: "ca_list",+ ComposioUserID: composioTestUserID,+ })+ h := newComposioTestHandler(t, &composioFakeSDK{}, store)++ // list+ w := httptest.NewRecorder()+ h.ListComposioConnections(w, composioReq(http.MethodGet, "/connections", ""))+ if w.Code != http.StatusOK {+ t.Fatalf("list: expected 200, got %d", w.Code)+ }+ var conns []ComposioConnectionResponse+ if err := json.Unmarshal(w.Body.Bytes(), &conns); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(conns) != 1 || conns[0].ToolkitSlug != "notion" {+ t.Fatalf("conns = %+v", conns)+ }++ // delete (owner) → 204, routed through chi so {id} resolves+ r := chi.NewRouter()+ r.Delete("/api/integrations/composio/connections/{id}", h.DeleteComposioConnection)+ delReq := composioReq(http.MethodDelete, "/api/integrations/composio/connections/"+util.UUIDToString(row.ID), "")+ w = httptest.NewRecorder()+ r.ServeHTTP(w, delReq)+ if w.Code != http.StatusNoContent {+ t.Fatalf("delete: expected 204, got %d (%s)", w.Code, w.Body.String())+ }++ // delete unknown id → 404+ missing := "33333333-3333-3333-3333-333333333333"+ w = httptest.NewRecorder()+ r.ServeHTTP(w, composioReq(http.MethodDelete, "/api/integrations/composio/connections/"+missing, ""))+ if w.Code != http.StatusNotFound {+ t.Fatalf("delete missing: expected 404, got %d", w.Code)+ }+}++// composioCapturingSDK records the callback URL so a test can replay the signed+// state through the real callback handler.+type composioCapturingSDK struct {+ composioFakeSDK+ lastCallbackURL string+}++func (f *composioCapturingSDK) CreateLink(_ context.Context, req sdk.CreateLinkRequest) (*sdk.CreateLinkResponse, error) {+ f.lastCallbackURL = req.CallbackURL+ return &sdk.CreateLinkResponse{RedirectURL: "https://composio.example/redirect"}, nil+}++func (f *composioCapturingSDK) stateFromCallback() string {+ idx := strings.Index(f.lastCallbackURL, "state=")+ if idx < 0 {+ return ""+ }+ return f.lastCallbackURL[idx+len("state="):]+}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex d3adce0ddf..61379521dc 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -2668,7 +2668,7 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, worreturn http.StatusBadRequest, "cannot assign to archived agent"}actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)- if !h.canAccessPrivateAgent(ctx, agent, actorType, actorID, workspaceID) {+ if !h.canInvokeAgent(ctx, agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {return http.StatusForbidden, "cannot assign to private agent"}return 0, ""@@ -2688,7 +2688,7 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, worreturn http.StatusBadRequest, "squad leader is archived; cannot assign to this squad"}actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)- if !h.canAccessPrivateAgent(ctx, leader, actorType, actorID, workspaceID) {+ if !h.canInvokeAgent(ctx, leader, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {return http.StatusForbidden, "cannot assign to squad with private leader"}return 0, ""@@ -2732,7 +2732,7 @@ func (h *Handler) assigneeFallbackAgent(ctx context.Context, issue db.Issue, actif err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {return db.Agent{}, false, false}- if !h.canAccessPrivateAgent(ctx, agent, actorType, actorID, uuidToString(issue.WorkspaceID)) {+ if !h.canInvokeAgent(ctx, agent, actorType, actorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {return db.Agent{}, false, false}// Coalescing queue: pending is still a valid route target, but callersdiff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.goindex 6ef89d71e7..87b950db8f 100644--- a/server/internal/handler/issue_child_done.go+++ b/server/internal/handler/issue_child_done.go@@ -495,8 +495,15 @@ func (h *Handler) triggerChildDoneSquad(ctx context.Context, parent db.Issue, trreturn}- // Private-leader gate: deny if the actor cannot access the leader.- if !h.canEnqueueSquadLeader(ctx, squad.LeaderID, actorType, actorID, uuidToString(parent.WorkspaceID)) {+ // Private-leader gate: deny if the actor cannot invoke the leader. Member+ // actors are their own originator; agent/system child-done triggers have+ // no resolvable human here, so canInvokeAgent fails closed for member/team+ // targets while still admitting workspace-target leaders.+ leaderOriginator := ""+ if actorType == "member" {+ leaderOriginator = actorID+ }+ if !h.canEnqueueSquadLeader(ctx, squad.LeaderID, actorType, actorID, leaderOriginator, uuidToString(parent.WorkspaceID)) {return}diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.goindex 006e916f30..20f4334c6f 100644--- a/server/internal/handler/issue_trigger.go+++ b/server/internal/handler/issue_trigger.go@@ -35,13 +35,10 @@ func (h *Handler) issueTriggerWriteProbe(r *http.Request, actorType string, issu// readiness to a member who cannot see it — matching validateAssigneePair /// canEnqueueSquadLeader) and the same self-loop guard.func (h *Handler) issueTriggerPreviewProbe(r *http.Request, actorType, actorID, workspaceID string, issue db.Issue) service.IssueTriggerProbe {+ originatorUserID := h.invokeOriginatorFromRequest(r, actorType, actorID)return service.IssueTriggerProbe{CanAccessAgent: func(agent db.Agent) bool {- at := actorType- if at == "system" {- at = "agent"- }- return h.canAccessPrivateAgent(r.Context(), agent, at, actorID, workspaceID)+ return h.canInvokeAgent(r.Context(), agent, actorType, actorID, originatorUserID, workspaceID)},IsSelfLoop: func() bool {return h.isAgentRunningOnIssue(r, actorType, issue)diff --git a/server/internal/handler/mcp_overlay.go b/server/internal/handler/mcp_overlay.gonew file mode 100644index 0000000000..a6fe755fe2--- /dev/null+++ b/server/internal/handler/mcp_overlay.go@@ -0,0 +1,160 @@+package handler++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+)++// mergeMCPOverlay layers a per-task overlay on top of an agent's saved+// mcp_config and returns the merged JSON for the daemon claim wire shape.+//+// The merge contract (kept deliberately shallow):+//+// - Both inputs are expected to be the Claude-style+// `{"mcpServers": {<name>: <object>}}` shape every supported runtime+// consumes via execenv's cursor / openclaw / opencode / codex / hermes+// sidecar generators. Anything not under `mcpServers` is preserved from+// the AGENT side only — overlays today only carry server entries and+// should not silently introduce other top-level keys.+//+// - Merge is by SERVER NAME (the inner-map key under `mcpServers`).+// On a name collision the OVERLAY wins. This is on purpose: the overlay+// carries the live, user-scoped session URL (e.g. the user's own+// Composio MCP bearer), whereas the agent's saved entry under the same+// name — if any — would be a stale or admin-shared placeholder.+//+// - Either side may be empty / nil / the literal `null`. Empty-everywhere+// returns `nil` so the daemon's `hasManagedCursorMcpConfig` short-circuit+// keeps treating the task as "no managed MCP at all".+//+// Failure mode: on malformed input the agent config is returned unchanged+// (with the error). Callers must never silently drop the agent's saved+// servers because the overlay JSON was bad — that would surprise-disable+// existing MCP tools.+func mergeMCPOverlay(agentMcpConfig, overlay json.RawMessage) (json.RawMessage, error) {+ if !hasManagedJSON(overlay) {+ return passthroughAgentMcpConfig(agentMcpConfig), nil+ }+ if !hasManagedJSON(agentMcpConfig) {+ // Re-marshal the overlay alone so the daemon receives the exact+ // canonical shape (the input may have been stored with arbitrary+ // whitespace by Postgres' JSONB representation).+ var oCfg map[string]json.RawMessage+ if err := json.Unmarshal(overlay, &oCfg); err != nil {+ return nil, fmt.Errorf("merge mcp overlay: parse overlay: %w", err)+ }+ out, err := json.Marshal(oCfg)+ if err != nil {+ return nil, fmt.Errorf("merge mcp overlay: marshal overlay: %w", err)+ }+ return out, nil+ }++ var aCfg map[string]json.RawMessage+ if err := json.Unmarshal(agentMcpConfig, &aCfg); err != nil {+ // Agent config malformed: surface the error but return the original+ // bytes unchanged so the agent's setup behavior matches the no-overlay+ // path (which would also have shipped the bad bytes downstream).+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("merge mcp overlay: parse agent mcp_config: %w", err)+ }+ var oCfg map[string]json.RawMessage+ if err := json.Unmarshal(overlay, &oCfg); err != nil {+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("merge mcp overlay: parse overlay: %w", err)+ }++ // Pull each side's `mcpServers` sub-map, default to empty so a+ // well-formed top level with no servers is treated like absent.+ aServers, err := unmarshalServerMap(aCfg["mcpServers"])+ if err != nil {+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("merge mcp overlay: agent mcpServers: %w", err)+ }+ oServers, err := unmarshalServerMap(oCfg["mcpServers"])+ if err != nil {+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("merge mcp overlay: overlay mcpServers: %w", err)+ }++ merged := make(map[string]json.RawMessage, len(aServers)+len(oServers))+ for k, v := range aServers {+ merged[k] = v+ }+ // Overlay wins on collisions.+ for k, v := range oServers {+ merged[k] = v+ }++ // Rebuild: keep any non-mcpServers top-level keys from the agent config,+ // then write the merged mcpServers map back. This is the only place we+ // touch top-level keys; everything else is left alone.+ out := make(map[string]json.RawMessage, len(aCfg)+1)+ for k, v := range aCfg {+ if k == "mcpServers" {+ continue+ }+ out[k] = v+ }+ if len(merged) > 0 {+ serversBytes, err := json.Marshal(merged)+ if err != nil {+ return nil, fmt.Errorf("merge mcp overlay: marshal merged servers: %w", err)+ }+ out["mcpServers"] = serversBytes+ }+ if len(out) == 0 {+ return nil, nil+ }+ final, err := json.Marshal(out)+ if err != nil {+ return nil, fmt.Errorf("merge mcp overlay: marshal merged: %w", err)+ }+ return final, nil+}++// hasManagedJSON reports whether a raw JSON column carries an actual managed+// payload (non-empty and not the literal `null`). Matches the convention+// hasManagedCursorMcpConfig uses on the daemon side so the merge respects+// the same "absent" semantics every consumer already agrees on.+func hasManagedJSON(raw json.RawMessage) bool {+ trimmed := bytes.TrimSpace(raw)+ return len(trimmed) > 0 && !bytes.Equal(trimmed, []byte("null"))+}++// passthroughAgentMcpConfig returns the agent config unchanged, or nil when+// it is absent. Used on the early-return paths so a caller assigning the+// return value into a wire field gets the same nil/non-nil split as today.+func passthroughAgentMcpConfig(agentMcpConfig json.RawMessage) json.RawMessage {+ if !hasManagedJSON(agentMcpConfig) {+ return nil+ }+ return agentMcpConfig+}++// unmarshalServerMap decodes the `mcpServers` sub-object into a map keyed by+// server name. A nil/absent value returns an empty map (not an error) so the+// caller can compose without an extra nil-check.+func unmarshalServerMap(raw json.RawMessage) (map[string]json.RawMessage, error) {+ if !hasManagedJSON(raw) {+ return map[string]json.RawMessage{}, nil+ }+ var m map[string]json.RawMessage+ if err := json.Unmarshal(raw, &m); err != nil {+ return nil, err+ }+ if m == nil {+ return map[string]json.RawMessage{}, nil+ }+ // Reject non-object server entries early — every runtime expects the+ // inner value to be an object and would 500 in the sidecar generator+ // otherwise. Mirrors parseCursorManagedMcpServers' guard.+ for name, server := range m {+ if name == "" {+ return nil, errors.New("mcp server name must not be empty")+ }+ trimmed := bytes.TrimSpace(server)+ if len(trimmed) == 0 || trimmed[0] != '{' {+ return nil, fmt.Errorf("mcpServers.%s must be a JSON object", name)+ }+ }+ return m, nil+}diff --git a/server/internal/handler/mcp_overlay_test.go b/server/internal/handler/mcp_overlay_test.gonew file mode 100644index 0000000000..cd47a4fbcf--- /dev/null+++ b/server/internal/handler/mcp_overlay_test.go@@ -0,0 +1,196 @@+package handler++import (+ "encoding/json"+ "testing"+)++// TestMergeMCPOverlayAgentNilOverlayNil covers the "no managed MCP anywhere"+// branch: both inputs absent must return nil so the daemon's "managed+// mcp_config?" short-circuit treats the task as no-config — exactly the+// behavior tasks had before Stage 3 introduced the overlay column.+func TestMergeMCPOverlayAgentNilOverlayNil(t *testing.T) {+ cases := []struct {+ name string+ agent json.RawMessage+ overlay json.RawMessage+ }{+ {"both_nil", nil, nil},+ {"agent_null_overlay_nil", json.RawMessage("null"), nil},+ {"agent_nil_overlay_null", nil, json.RawMessage("null")},+ {"agent_empty_overlay_empty", json.RawMessage(""), json.RawMessage("")},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, err := mergeMCPOverlay(tc.agent, tc.overlay)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if got != nil {+ t.Errorf("expected nil result, got %s", string(got))+ }+ })+ }+}++// TestMergeMCPOverlayAgentOnly covers the "no Composio for this task" path:+// every existing agent.mcp_config must be passed through unchanged so+// Stage 3 cannot break MCP setup for tasks where the initiator has no+// connections.+func TestMergeMCPOverlayAgentOnly(t *testing.T) {+ agent := json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`)++ got, err := mergeMCPOverlay(agent, nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ // Pass-through preserves the exact bytes (no re-marshal) so the+ // existing trust-byte-identity tests upstream are unaffected.+ if string(got) != string(agent) {+ t.Errorf("expected pass-through, got %s", string(got))+ }+}++// TestMergeMCPOverlayOverlayOnly covers the "agent has no mcp_config" path:+// the overlay is canonicalized through json.Marshal so the daemon receives+// a deterministic shape regardless of how Postgres' JSONB serialized the+// stored value.+func TestMergeMCPOverlayOverlayOnly(t *testing.T) {+ overlay := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.composio.dev/s/abc","headers":{"Authorization":"Bearer mcp_xyz"}}}}`)++ got, err := mergeMCPOverlay(nil, overlay)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ var cfg map[string]any+ if err := json.Unmarshal(got, &cfg); err != nil {+ t.Fatalf("unmarshal result: %v", err)+ }+ servers, ok := cfg["mcpServers"].(map[string]any)+ if !ok {+ t.Fatalf("missing mcpServers, got %s", string(got))+ }+ if _, ok := servers["composio"]; !ok {+ t.Errorf("expected composio server, got %s", string(got))+ }+}++// TestMergeMCPOverlayMergesBothSides — the headline case: agent's saved+// servers must survive, and the overlay's composio entry must appear alongside.+func TestMergeMCPOverlayMergesBothSides(t *testing.T) {+ agent := json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx"},"github":{"command":"npx"}}}`)+ overlay := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.composio.dev/s/abc"}}}`)++ got, err := mergeMCPOverlay(agent, overlay)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ var cfg map[string]any+ if err := json.Unmarshal(got, &cfg); err != nil {+ t.Fatalf("unmarshal result: %v", err)+ }+ servers, ok := cfg["mcpServers"].(map[string]any)+ if !ok {+ t.Fatalf("missing mcpServers, got %s", string(got))+ }+ for _, want := range []string{"fetch", "github", "composio"} {+ if _, ok := servers[want]; !ok {+ t.Errorf("missing server %q in merged result %s", want, string(got))+ }+ }+}++// TestMergeMCPOverlayCollisionOverlayWins — the contract the comment on+// mergeMCPOverlay calls out explicitly. The overlay carries the live, user-+// scoped session URL; on a name collision it must win so the daemon's+// sidecar generator emits the live URL, not whatever placeholder the agent+// had saved.+func TestMergeMCPOverlayCollisionOverlayWins(t *testing.T) {+ agent := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://placeholder.example/old"}}}`)+ overlay := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.composio.dev/s/new"}}}`)++ got, err := mergeMCPOverlay(agent, overlay)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ var cfg map[string]map[string]map[string]any+ if err := json.Unmarshal(got, &cfg); err != nil {+ t.Fatalf("unmarshal result: %v", err)+ }+ gotURL, _ := cfg["mcpServers"]["composio"]["url"].(string)+ if gotURL != "https://mcp.composio.dev/s/new" {+ t.Errorf("collision: expected overlay URL to win, got %q", gotURL)+ }+}++// TestMergeMCPOverlayPreservesAgentTopLevelKeys — anything outside+// `mcpServers` on the agent side must be preserved. The overlay only+// carries server entries; it must not silently strip non-server top-level+// keys the agent admin saved.+func TestMergeMCPOverlayPreservesAgentTopLevelKeys(t *testing.T) {+ agent := json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx"}},"experimental":{"foo":"bar"}}`)+ overlay := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.composio.dev/s/abc"}}}`)++ got, err := mergeMCPOverlay(agent, overlay)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ var cfg map[string]json.RawMessage+ if err := json.Unmarshal(got, &cfg); err != nil {+ t.Fatalf("unmarshal result: %v", err)+ }+ if _, ok := cfg["experimental"]; !ok {+ t.Errorf("expected experimental key preserved, got %s", string(got))+ }+}++// TestMergeMCPOverlayBadOverlayFallsBackToAgent — a malformed overlay must+// not surprise-disable the agent's saved servers. The merge returns the+// agent config unchanged plus an error so the caller can log.+func TestMergeMCPOverlayBadOverlayFallsBackToAgent(t *testing.T) {+ agent := json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx"}}}`)+ overlay := json.RawMessage(`{ this is not json`)++ got, err := mergeMCPOverlay(agent, overlay)+ if err == nil {+ t.Fatalf("expected parse error, got nil")+ }+ if string(got) != string(agent) {+ t.Errorf("expected agent config preserved on overlay parse failure, got %s", string(got))+ }+}++// TestMergeMCPOverlayBadAgentReturnsBytesAndError — symmetric guard: a+// malformed agent.mcp_config must not panic the merger. We return the+// original bytes and surface the parse error so the daemon's downstream+// sidecar generator can give the existing error path (instead of a+// half-merged config).+func TestMergeMCPOverlayBadAgentReturnsBytesAndError(t *testing.T) {+ agent := json.RawMessage(`{ this is not json`)+ overlay := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.composio.dev/s/abc"}}}`)++ got, err := mergeMCPOverlay(agent, overlay)+ if err == nil {+ t.Fatalf("expected parse error, got nil")+ }+ if string(got) != string(agent) {+ t.Errorf("expected agent bytes returned unchanged, got %s", string(got))+ }+}++// TestMergeMCPOverlayRejectsNonObjectServer pins the type guard: an+// mcpServers map whose value is a primitive (or array) is rejected, so a+// future bug that wrote `mcpServers: {composio: "https://..."}` (a string+// instead of an object) doesn't quietly travel through the merge and blow+// up in execenv's sidecar generator. Same behavior as+// parseCursorManagedMcpServers.+func TestMergeMCPOverlayRejectsNonObjectServer(t *testing.T) {+ agent := json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx"}}}`)+ overlay := json.RawMessage(`{"mcpServers":{"composio":"not-an-object"}}`)++ if _, err := mergeMCPOverlay(agent, overlay); err == nil {+ t.Fatalf("expected error for non-object server, got nil")+ }+}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex d115d17a7b..ac7d6017d9 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -640,6 +640,13 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {}// Remove archived agents so the FK constraint (ON DELETE RESTRICT) won't block deletion.+ // First drop their invocation targets — agent_invocation_target has no+ // agent_id FK (MUL-3963), so cleanup is app-layer and MUST precede the+ // agent hard-delete to avoid orphan rows.+ if err := qtx.DeleteAgentInvocationTargetsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up agent invocation targets")+ return+ }if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rt.ID); err != nil {writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")return@@ -868,6 +875,10 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R// 4. Hard-delete the archived agents so the agent.runtime_id FK// (ON DELETE RESTRICT) no longer keeps the runtime alive.+ if err := qtx.DeleteAgentInvocationTargetsByArchivedRuntimeAgents(r.Context(), rt.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up agent invocation targets")+ return+ }if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rt.ID); err != nil {writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")returndiff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.goindex 4335e6efde..88cb6035f6 100644--- a/server/internal/handler/runtime_profile.go+++ b/server/internal/handler/runtime_profile.go@@ -437,6 +437,10 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to clean up squads referencing archived agents")return}+ if err := qtx.DeleteAgentInvocationTargetsByArchivedRuntimeAgents(r.Context(), rid); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up agent invocation targets")+ return+ }if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rid); err != nil {writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")returndiff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex 9f64926f18..a700e9a33e 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -960,7 +960,15 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, trreturn false}- if !h.canEnqueueSquadLeader(ctx, squad.LeaderID, authorType, authorID, uuidToString(issue.WorkspaceID)) {+ // Member authors are their own originator; agent-authored triggers have no+ // request context here, so the originator is left empty (canInvokeAgent+ // then fails closed for member/team targets — a workspace target still+ // admits the agent as a workspace principal).+ leaderOriginator := ""+ if authorType == "member" {+ leaderOriginator = authorID+ }+ if !h.canEnqueueSquadLeader(ctx, squad.LeaderID, authorType, authorID, leaderOriginator, uuidToString(issue.WorkspaceID)) {return false}diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.goindex b3118d6bc2..27dd629e40 100644--- a/server/internal/handler/squad_comment_trigger_test.go+++ b/server/internal/handler/squad_comment_trigger_test.go@@ -499,7 +499,7 @@ func TestCreateRetryTask_InheritsIsLeaderTask(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1 OR parent_task_id = $1`, parentID)})- child, err := testHandler.Queries.CreateRetryTask(ctx, util.MustParseUUID(parentID))+ child, err := testHandler.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: util.MustParseUUID(parentID)})if err != nil {t.Fatalf("CreateRetryTask: %v", err)}diff --git a/server/internal/handler/squad_id_enqueue_test.go b/server/internal/handler/squad_id_enqueue_test.goindex 057dbfa5d0..256a67cb4f 100644--- a/server/internal/handler/squad_id_enqueue_test.go+++ b/server/internal/handler/squad_id_enqueue_test.go@@ -7,6 +7,7 @@ import ("testing""github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// TestCreateComment_SquadMentionStampsSquadIDOnLeaderTask locks the enqueue@@ -116,7 +117,7 @@ func TestCreateRetryTask_InheritsSquadID(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1 OR parent_task_id = $1`, parentID)})- child, err := testHandler.Queries.CreateRetryTask(ctx, util.MustParseUUID(parentID))+ child, err := testHandler.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: util.MustParseUUID(parentID)})if err != nil {t.Fatalf("CreateRetryTask: %v", err)}diff --git a/server/internal/handler/squad_private_leader_test.go b/server/internal/handler/squad_private_leader_test.goindex 65a57d42cd..9001e08692 100644--- a/server/internal/handler/squad_private_leader_test.go+++ b/server/internal/handler/squad_private_leader_test.go@@ -98,7 +98,7 @@ func TestCreateIssue_SquadPrivateLeader_OwnerAllowed(t *testing.T) {}ctx := context.Background()- agentID, _, _ := privateAgentTestFixture(t)+ agentID, ownerID, _ := privateAgentTestFixture(t)var squadID stringif err := testPool.QueryRow(ctx, `@@ -112,9 +112,10 @@ func TestCreateIssue_SquadPrivateLeader_OwnerAllowed(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID)})- // testUserID is workspace owner — should succeed.+ // The AGENT OWNER assigns — allowed. (MUL-3963: workspace owner/admin no+ // longer bypasses a private leader's invocation gate.)w := httptest.NewRecorder()- r := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ r := newRequestAs(ownerID, "POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Owner assigns private-leader squad","assignee_type": "squad","assignee_id": squadID,@@ -205,7 +206,7 @@ func TestChildDone_SquadPrivateLeader_PlainMemberNoEnqueue(t *testing.T) {}ctx := context.Background()- agentID, _, memberID := privateAgentTestFixture(t)+ agentID, ownerID, memberID := privateAgentTestFixture(t)var squadID stringif err := testPool.QueryRow(ctx, `@@ -219,9 +220,10 @@ func TestChildDone_SquadPrivateLeader_PlainMemberNoEnqueue(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID)})- // Create parent issue assigned to the squad (as workspace owner).+ // Create parent issue assigned to the squad (as the AGENT OWNER, who is+ // allowed to invoke the private leader under MUL-3963).w := httptest.NewRecorder()- r := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ r := newRequestAs(ownerID, "POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "parent with private-leader squad","assignee_type": "squad","assignee_id": squadID,@@ -297,7 +299,7 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {}ctx := context.Background()- agentID, _, _ := privateAgentTestFixture(t)+ agentID, ownerID, _ := privateAgentTestFixture(t)otherAgentID := createHandlerTestAgent(t, "squad-private-leader-agent-actor", nil)var squadID string@@ -327,13 +329,16 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)})- // Create a task for the other agent so X-Agent-ID / X-Task-ID are valid.+ // Create a task for the other agent whose top-of-chain originator is the+ // private leader's OWNER. Under MUL-3963 A2A is judged by that originator,+ // so the agent-actor squad mention resolves to the owner and may invoke+ // the private leader.var taskID stringif err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id)- VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2)+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, originator_user_id)+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2, $3)RETURNING id- `, otherAgentID, issueID).Scan(&taskID); err != nil {+ `, otherAgentID, issueID, ownerID).Scan(&taskID); err != nil {t.Fatalf("create agent task: %v", err)}t.Cleanup(func() {@@ -353,8 +358,9 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())}- // The private leader SHOULD have a queued task — agents bypass private gate- // for explicit routing.+ // The private leader SHOULD have a queued task — the agent-actor mention's+ // top-of-chain originator is the leader's owner, so A2A-by-originator+ // admits it (MUL-3963).var count intif err := testPool.QueryRow(ctx,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,@@ -363,6 +369,6 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {t.Fatalf("count tasks: %v", err)}if count == 0 {- t.Fatalf("private leader got 0 queued tasks from agent actor squad mention; want >=1 (agents bypass private gate)")+ t.Fatalf("private leader got 0 queued tasks; want >=1 (A2A originator is the leader owner)")}}diff --git a/server/internal/handler/trigger_test.go b/server/internal/handler/trigger_test.goindex fc0dec1e4b..61295747d5 100644--- a/server/internal/handler/trigger_test.go+++ b/server/internal/handler/trigger_test.go@@ -113,5 +113,5 @@ func TestTriggerTasksForComment_NoteShortCircuits(t *testing.T) {}// Must not panic — the guard short-circuits before any DB access.- h.triggerTasksForComment(context.Background(), issue, comment, nil, "member", memberID, nil)+ h.triggerTasksForComment(context.Background(), issue, comment, nil, "member", memberID, memberID, nil)}diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex e58dfc6052..f474425892 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -125,6 +125,20 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userIDreturn empty, err}+ // agent_invocation_target carries member-target grants with NO database FK+ // (MUL-3963 keeps the new table FK-free, matching the MUL-3515 channel+ // generalization). Prune this leaving member's grants in the same tx as the+ // member-row delete so a re-invited user does not silently reclaim old+ // invocation permission on agents that had allow-listed them. SCOPED to+ // this workspace: the same user may belong to other workspaces, and+ // removing them here must not touch their grants on agents elsewhere.+ if err := qtx.DeleteAgentInvocationTargetsByMember(ctx, db.DeleteAgentInvocationTargetsByMemberParams{+ WorkspaceID: workspaceID,+ TargetID: userID,+ }); err != nil {+ return empty, err+ }+// Member row deletion lives inside the same tx so a successful revoke is// never followed by a failed member-delete (which would leave the user// still a member with a dead runtime), and a failed revoke never leavesdiff --git a/server/internal/integrations/composio/dispatch.go b/server/internal/integrations/composio/dispatch.gonew file mode 100644index 0000000000..f71707197c--- /dev/null+++ b/server/internal/integrations/composio/dispatch.go@@ -0,0 +1,249 @@+package composio++import (+ "context"+ "encoding/json"+ "fmt"+ "sort"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/runtimeapps"+ "github.com/multica-ai/multica/server/internal/util"+ sdk "github.com/multica-ai/multica/server/pkg/composio"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// mcpOverlayServerName is the deterministic key under `mcpServers` used to+// place the Composio session into the merged MCP config. Daemon-side merge+// is by server name, so this constant is the integration's namespace: a+// future provider adding its own overlay must pick a distinct name (e.g.+// "pipedream") to avoid collisions, and an agent's own `mcp_config` entry+// named "composio" is overridden by this overlay on purpose — the overlay+// carries the live user-scoped session URL, the agent config carries a+// generic service-wide entry at most.+const mcpOverlayServerName = "composio"++// composioMCPServer is the wire shape of one MCP server entry in the+// Claude-style `{"mcpServers": {...}}` config that every supported runtime+// (Cursor, Codex, Claude, OpenCode, OpenClaw, Hermes/Kiro) consumes.+//+// `type: http` is what marks the entry as a streamable HTTP MCP endpoint —+// the form Composio's session helper returns. Headers carry the Composio API+// key, so callers must NEVER log this struct without redacting Headers.+type composioMCPServer struct {+ Type string `json:"type"`+ URL string `json:"url"`+ Headers map[string]string `json:"headers,omitempty"`+}++// mcpOverlayPayload is the per-task overlay JSON written to+// agent_task_queue.runtime_mcp_overlay and read by the daemon claim handler+// at task dispatch.+//+// Shape is deliberately a subset of agent.mcp_config (Claude-style+// `mcpServers` map) so the daemon's merge is a flat dictionary union keyed+// by server name. Anything more elaborate (capability filtering, env+// injection, …) would force every sidecar generator to learn about overlays+// individually; keeping the shape identical lets the merge stay pure+// substitution.+type mcpOverlayPayload struct {+ MCPServers map[string]composioMCPServer `json:"mcpServers"`+}++// BuildTaskOverlay returns the overlay payload to write for a task dispatching+// `agent`, or a zero result when ANY of the gates below trip — meaning no+// Composio session is created and no token is provisioned.+//+// MUL-3963: Composio MCP now FOLLOWS the agent invocation permission instead+// of requiring originator == owner. The security boundary is upstream —+// canInvokeAgent decides who may enqueue a run for this agent at all — so any+// task that reaches dispatch has already been authorised to run the agent, and+// therefore to use the Composio apps the OWNER attached to it. The overlay is+// always built from the AGENT OWNER's connected-apps view: the owner shares+// those apps as part of the agent's capability with everyone allowed to invoke+// it (private -> only the owner; public_to -> the allow-list). The front-end+// warns the owner about this when a shared agent has Composio apps enabled.+//+// originatorUserID is retained only for audit logging (who triggered) — it no+// longer gates the overlay.+//+// Gates, in order:+//+// 1. agent has no owner — cannot resolve a connected-apps view. No overlay.+//+// 2. agent.composio_toolkit_allowlist is empty/NULL — the agent owner never+// opted into any toolkit. Default OFF: no overlay.+//+// 3. After intersecting the allowlist with the OWNER's currently-active+// Composio connections, no toolkit has an active connection. Nothing to+// mount.+//+// 4. Composio returns a session with no URL — defensive.+//+// CreateSession is called with the owner as the session user, and with BOTH+// the `toolkits.enable` allowlist filter and `connected_accounts` pinning so+// the session is narrowed to (owner allowlist ∩ owner active connections).+func (s *Service) BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.UUID, agent db.Agent) (runtimeapps.MCPOverlayResult, error) {+ // Gate 1: the overlay is the agent OWNER's connected-apps view. Without an+ // owner there is nothing to project.+ if !agent.OwnerID.Valid {+ return runtimeapps.MCPOverlayResult{}, nil+ }+ ownerUserID := agent.OwnerID+ // Gate 2: agent owner has not allowlisted any toolkit. NULL and empty+ // `{}` are treated identically — both mean "no overlay".+ allowSet := normaliseAllowlistToSet(agent.ComposioToolkitAllowlist)+ if len(allowSet) == 0 {+ return runtimeapps.MCPOverlayResult{}, nil+ }++ // Resolve the OWNER's active connections and intersect with the allowlist.+ // The intersection is the canonical input both for filtering the Composio+ // CreateSession call AND for the early bail-out below.+ rows, err := s.store.ListActiveUserComposioConnections(ctx, ownerUserID)+ if err != nil {+ return runtimeapps.MCPOverlayResult{}, fmt.Errorf("composio: build task overlay: list connections: %w", err)+ }+ pinned := pinConnectedAccounts(rows, allowSet)+ if len(pinned) == 0 {+ // Gate 3: owner allowlisted toolkits they have not connected — or have+ // revoked since.+ return runtimeapps.MCPOverlayResult{}, nil+ }+ // `toolkits.enable` narrows what the tool-router exposes; pair it with+ // the connected-account pin so the session can never surface an+ // account outside the (allowlist ∩ active connections) set.+ slugs := make([]string, 0, len(pinned))+ for slug := range pinned {+ slugs = append(slugs, slug)+ }+ sort.Strings(slugs)++ resp, err := s.sdk.CreateSession(ctx, sdk.CreateSessionRequest{+ UserID: util.UUIDToString(ownerUserID),+ Toolkits: map[string]any{"enable": slugs},+ ConnectedAccounts: pinned,+ })+ if err != nil {+ return runtimeapps.MCPOverlayResult{}, fmt.Errorf("composio: build task overlay: create session: %w", err)+ }+ // Gate 4: Composio answered 200 with no MCP URL. Treat as "no overlay"+ // rather than wire up a server with an empty URL — every runtime fails+ // noisily on that.+ if resp == nil || resp.MCP.URL == "" {+ return runtimeapps.MCPOverlayResult{}, nil+ }++ payload := mcpOverlayPayload{+ MCPServers: map[string]composioMCPServer{+ mcpOverlayServerName: {+ Type: "http",+ URL: resp.MCP.URL,+ Headers: s.sdk.MCPAuthHeaders(),+ },+ },+ }+ raw, err := json.Marshal(payload)+ if err != nil {+ return runtimeapps.MCPOverlayResult{}, fmt.Errorf("composio: marshal task overlay: %w", err)+ }+ apps := make([]runtimeapps.ConnectedApp, 0, len(slugs))+ for _, slug := range slugs {+ apps = append(apps, runtimeapps.ConnectedApp{+ Provider: "composio",+ ServerName: mcpOverlayServerName,+ ToolkitSlug: slug,+ ToolkitName: runtimeapps.DisplayNameForToolkitSlug(slug),+ })+ }+ return runtimeapps.MCPOverlayResult{MCPOverlay: raw, ConnectedApps: apps}, nil+}++// normaliseAllowlistToSet maps the agent.composio_toolkit_allowlist+// TEXT[] column into a slug→{} set. Each entry is lowercased + trimmed+// defensively (the API layer already normalises on write, but DB-level+// migrations / out-of-band writes might bypass that, and the cost of a+// re-normalise is one map walk). An empty result triggers gate 3 in+// BuildTaskOverlay, identically for NULL columns and `{}` arrays.+func normaliseAllowlistToSet(allow []string) map[string]struct{} {+ if len(allow) == 0 {+ return nil+ }+ out := make(map[string]struct{}, len(allow))+ for _, s := range allow {+ slug := lowerTrim(s)+ if slug == "" {+ continue+ }+ out[slug] = struct{}{}+ }+ return out+}++// pinConnectedAccounts intersects the originator's active connection rows+// with the allowlist set and returns the `connected_accounts` map shape the+// Composio /tool_router/session endpoint expects: one entry per allowlisted+// toolkit slug, value = array of the originator's connected account ids for+// that toolkit. The product currently permits one active account per toolkit,+// so each array has one element.+//+// Newest-wins on duplicates: rows arrive ordered by connected_at DESC+// (see ListActiveUserComposioConnections), so the first row seen for a+// given slug is the most recently connected account, matching the+// single-account-per-toolkit invariant CreateMCPSession already documents.+func pinConnectedAccounts(rows []db.UserComposioConnection, allowSet map[string]struct{}) map[string]any {+ pinned := make(map[string]any, len(rows))+ for _, row := range rows {+ slug := lowerTrim(row.ToolkitSlug)+ if slug == "" {+ continue+ }+ if _, allowed := allowSet[slug]; !allowed {+ continue+ }+ if _, dup := pinned[slug]; dup {+ continue+ }+ pinned[slug] = []string{row.ConnectedAccountID}+ }+ return pinned+}++// lowerTrim is the tiny inlined helper that keeps allowlist and connection+// slug comparison consistent without dragging the unicode lib for what is+// always an ASCII slug.+func lowerTrim(s string) string {+ // strings.ToLower + TrimSpace would do, but we avoid importing strings+ // just for two ASCII transforms in a hot path. Manual loop is+ // allocation-free for the common all-ASCII case.+ start, end := 0, len(s)+ for start < end && (s[start] == ' ' || s[start] == '\t' || s[start] == '\n' || s[start] == '\r') {+ start+++ }+ for end > start && (s[end-1] == ' ' || s[end-1] == '\t' || s[end-1] == '\n' || s[end-1] == '\r') {+ end--+ }+ if start == end {+ return ""+ }+ // Detect upper-case before allocating.+ upper := false+ for i := start; i < end; i++ {+ if s[i] >= 'A' && s[i] <= 'Z' {+ upper = true+ break+ }+ }+ if !upper {+ return s[start:end]+ }+ b := make([]byte, end-start)+ for i := start; i < end; i++ {+ c := s[i]+ if c >= 'A' && c <= 'Z' {+ c += 'a' - 'A'+ }+ b[i-start] = c+ }+ return string(b)+}diff --git a/server/internal/integrations/composio/dispatch_test.go b/server/internal/integrations/composio/dispatch_test.gonew file mode 100644index 0000000000..45bec4b835--- /dev/null+++ b/server/internal/integrations/composio/dispatch_test.go@@ -0,0 +1,545 @@+package composio++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/runtimeapps"+ sdk "github.com/multica-ai/multica/server/pkg/composio"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// seedActiveConnection writes a single active row for the user/toolkit pair+// so BuildTaskOverlay's "user has at least one active connection" branch is+// reachable in tests without touching the real Composio API or DB.+func seedActiveConnection(t *testing.T, store *fakeStore, userID pgtype.UUID, toolkit, connectedAccountID string) {+ t.Helper()+ if _, err := store.UpsertUserComposioConnection(context.Background(), db.UpsertUserComposioConnectionParams{+ UserID: userID,+ ToolkitSlug: toolkit,+ AuthConfigID: "ac_test",+ ConnectedAccountID: connectedAccountID,+ ComposioUserID: uuidToString(userID),+ }); err != nil {+ t.Fatalf("seed: %v", err)+ }+}++func uuidToString(u pgtype.UUID) string {+ if !u.Valid {+ return ""+ }+ b := u.Bytes+ const hex = "0123456789abcdef"+ out := make([]byte, 36)+ idx := 0+ for i, x := range b {+ out[idx] = hex[x>>4]+ out[idx+1] = hex[x&0xf]+ idx += 2+ if i == 3 || i == 5 || i == 7 || i == 9 {+ out[idx] = '-'+ idx+++ }+ }+ return string(out)+}++// makeAgent returns an Agent fixture with the given owner and optional+// allowlist. Other Agent fields are zero-valued because BuildTaskOverlay+// only reads OwnerID + ComposioToolkitAllowlist.+func makeAgent(owner pgtype.UUID, allowlist ...string) db.Agent {+ a := db.Agent{OwnerID: owner}+ if allowlist != nil {+ a.ComposioToolkitAllowlist = allowlist+ }+ return a+}++// --- Overlay follows the agent owner, not the run originator (MUL-3963) ---++// TestBuildTaskOverlay_FollowsOwnerRegardlessOfOriginator: with no human+// originator (autopilot / system run) the overlay is STILL built from the+// agent owner's connected apps, because the invocation-permission gate that+// decides who may run the agent lives upstream (canInvokeAgent /+// canCreatorInvokeAgent). BuildTaskOverlay no longer gates on the originator.+func TestBuildTaskOverlay_FollowsOwnerRegardlessOfOriginator(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{+ createSessResp: &sdk.CreateSessionResponse{+ MCP: sdk.MCPDescriptor{URL: "https://mcp.composio.dev/session/noorig"},+ },+ }+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)++ owner := mintUUID(7)+ agent := makeAgent(owner, "notion")+ seedActiveConnection(t, store, owner, "notion", "ca_owner_notion")++ result, err := svc.BuildTaskOverlay(context.Background(), pgtype.UUID{}, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(result.MCPOverlay) == 0 {+ t.Fatalf("expected overlay from owner connection even with no originator")+ }+ if sdkFake.lastSessReq.UserID != uuidToString(owner) {+ t.Errorf("CreateSession user id = %q, want owner %q", sdkFake.lastSessReq.UserID, uuidToString(owner))+ }+}++// --- Overlay uses the OWNER's connection, not the originator's -----------++// TestBuildTaskOverlay_UsesOwnerConnectionNotOriginator is the MUL-3963+// contract that replaced the old originator==owner gate: a non-owner+// originator who has passed the invoke gate gets the overlay built from the+// AGENT OWNER's connection, and never from their own. Seeding only the+// non-owner originator's connection (owner has none) produces no overlay.+func TestBuildTaskOverlay_UsesOwnerConnectionNotOriginator(t *testing.T) {+ t.Parallel()++ owner := mintUUID(11)+ other := mintUUID(12) // a different human who triggered the run++ // Case A: owner HAS the connection -> overlay built with OWNER identity,+ // even though the originator is a different user.+ t.Run("owner-connection-used", func(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{+ createSessResp: &sdk.CreateSessionResponse{+ MCP: sdk.MCPDescriptor{URL: "https://mcp.composio.dev/session/owner"},+ },+ }+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ agent := makeAgent(owner, "notion")+ seedActiveConnection(t, store, owner, "notion", "ca_owner_notion")+ // The originator also has a matching connection; it must NOT be used.+ seedActiveConnection(t, store, other, "notion", "ca_other_notion")++ result, err := svc.BuildTaskOverlay(context.Background(), other, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(result.MCPOverlay) == 0 {+ t.Fatalf("expected overlay built from owner connection")+ }+ if sdkFake.lastSessReq.UserID != uuidToString(owner) {+ t.Errorf("CreateSession user id = %q, want owner %q (not originator)", sdkFake.lastSessReq.UserID, uuidToString(owner))+ }+ assertPinnedAccount(t, sdkFake.lastSessReq, "notion", "ca_owner_notion")+ })++ // Case B: only the originator has the connection (owner has none) -> the+ // intersection with the OWNER's connections is empty, so no overlay.+ t.Run("originator-connection-ignored", func(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{}+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ agent := makeAgent(owner, "notion")+ seedActiveConnection(t, store, other, "notion", "ca_other_notion")++ result, err := svc.BuildTaskOverlay(context.Background(), other, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.MCPOverlay != nil {+ t.Errorf("expected nil overlay: owner has no connection, originator's must be ignored, got %s", string(result.MCPOverlay))+ }+ if sdkFake.createSessCalls != 0 {+ t.Errorf("CreateSession must not run when owner has no matching connection, got %d", sdkFake.createSessCalls)+ }+ })+}++// --- Gate 3: empty / NULL allowlist --------------------------------------++// TestBuildTaskOverlay_EmptyAllowlistIsNoOp covers both NULL and `{}`+// columns: until the agent owner has opted into specific toolkits, the+// dispatch decision is OFF — no overlay, no Composio call, no token.+func TestBuildTaskOverlay_EmptyAllowlistIsNoOp(t *testing.T) {+ t.Parallel()+ for name, allowlist := range map[string][]string{+ "nil-slice": nil,+ "empty-slice": {},+ "whitespace": {" ", "\t"},+ } {+ t.Run(name, func(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{}+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ owner := mintUUID(20)+ agent := makeAgent(owner, allowlist...)+ seedActiveConnection(t, store, owner, "notion", "ca_owner_notion")++ result, err := svc.BuildTaskOverlay(context.Background(), owner, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.MCPOverlay != nil {+ t.Errorf("expected nil overlay for empty allowlist, got %s", string(result.MCPOverlay))+ }+ if sdkFake.createSessCalls != 0 {+ t.Errorf("CreateSession must not run when allowlist is empty, got %d calls", sdkFake.createSessCalls)+ }+ })+ }+}++// --- Gate 4: allowlist non-empty but no matching active connection -------++// TestBuildTaskOverlay_NoMatchingConnectionIsNoOp — the owner allowlisted+// toolkits they have not connected (or revoked the connection for). The+// intersection is empty, so we have nothing to mount and must not pay for+// an empty Composio session.+func TestBuildTaskOverlay_NoMatchingConnectionIsNoOp(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{}+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ owner := mintUUID(30)+ agent := makeAgent(owner, "notion", "github")+ // Owner connected SLACK only — not in allowlist.+ seedActiveConnection(t, store, owner, "slack", "ca_owner_slack")++ result, err := svc.BuildTaskOverlay(context.Background(), owner, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.MCPOverlay != nil {+ t.Errorf("expected nil overlay for empty intersection, got %s", string(result.MCPOverlay))+ }+ if sdkFake.createSessCalls != 0 {+ t.Errorf("CreateSession must not run when intersection is empty, got %d calls", sdkFake.createSessCalls)+ }+}++// --- Happy path: allowlist ∩ active connections is non-empty -------------++// TestBuildTaskOverlay_HappyPath_FiltersBothWays — the canonical+// successful dispatch. Asserts:+// - CreateSession was called with the Multica user id verbatim+// - both filters were passed (toolkits.enable AND connected_accounts)+// - the slug set is exactly the intersection (allowlist ∩ active)+// - connected_accounts pins the correct connected_account_id per slug+// - the returned overlay JSON has the daemon-expected shape+// - connected app metadata is exactly the same intersection for prompt use+// - non-allowlisted active connections (slack here) do NOT leak through+func TestBuildTaskOverlay_HappyPath_FiltersBothWays(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{+ createSessResp: &sdk.CreateSessionResponse{+ MCP: sdk.MCPDescriptor{URL: "https://mcp.composio.dev/session/abc"},+ },+ }+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ owner := mintUUID(13)+ agent := makeAgent(owner, "notion", "github")+ // Three active connections; only the two in the allowlist should be+ // surfaced. The third (slack) is the proof that the filter is being+ // applied — without it, every active connection would leak into the+ // session even when the owner did not allowlist it.+ seedActiveConnection(t, store, owner, "notion", "ca_owner_notion")+ seedActiveConnection(t, store, owner, "github", "ca_owner_github")+ seedActiveConnection(t, store, owner, "slack", "ca_owner_slack")++ result, err := svc.BuildTaskOverlay(context.Background(), owner, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(result.MCPOverlay) == 0 {+ t.Fatalf("expected non-empty overlay, got nil")+ }++ // composio_user_id == Multica user id invariant+ if sdkFake.lastSessReq.UserID != uuidToString(owner) {+ t.Errorf("CreateSession user id: got %q, want %q", sdkFake.lastSessReq.UserID, uuidToString(owner))+ }+ // Toolkits.enable filter must be the intersection, not the agent's+ // full allowlist nor the user's full connection set.+ tk, _ := sdkFake.lastSessReq.Toolkits["enable"].([]string)+ if len(tk) != 2 || !containsString(tk, "notion") || !containsString(tk, "github") {+ t.Errorf("CreateSession toolkits.enable = %v, want exactly [notion github]", tk)+ }+ if containsString(tk, "slack") {+ t.Errorf("non-allowlisted slack leaked into toolkits.enable: %v", tk)+ }+ // connected_accounts pinning+ assertPinnedAccount(t, sdkFake.lastSessReq, "notion", "ca_owner_notion")+ assertPinnedAccount(t, sdkFake.lastSessReq, "github", "ca_owner_github")+ if _, leaked := sdkFake.lastSessReq.ConnectedAccounts["slack"]; leaked {+ t.Errorf("non-allowlisted slack leaked into connected_accounts")+ }+ assertConnectedApps(t, result.ConnectedApps, "github", "notion")++ var payload mcpOverlayPayload+ if err := json.Unmarshal(result.MCPOverlay, &payload); err != nil {+ t.Fatalf("unmarshal overlay: %v", err)+ }+ srv, ok := payload.MCPServers[mcpOverlayServerName]+ if !ok {+ t.Fatalf("overlay missing %q server, got %s", mcpOverlayServerName, string(result.MCPOverlay))+ }+ if srv.Type != "http" {+ t.Errorf("type: got %q, want \"http\"", srv.Type)+ }+ if srv.URL != "https://mcp.composio.dev/session/abc" {+ t.Errorf("url: got %q", srv.URL)+ }+ if srv.Headers["x-api-key"] != "secret" {+ t.Errorf("headers missing x-api-key: %v", srv.Headers)+ }+}++func TestBuildTaskOverlay_CreateSessionWireContract(t *testing.T) {+ t.Parallel()++ postedCh := make(chan map[string]any, 1)+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/tool_router/session" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ }+ if got := r.Header.Get("x-api-key"); got != "test-key" {+ t.Errorf("x-api-key header = %q", got)+ }+ var posted map[string]any+ if err := json.NewDecoder(r.Body).Decode(&posted); err != nil {+ t.Errorf("decode request body: %v", err)+ }+ postedCh <- posted+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusCreated)+ if err := json.NewEncoder(w).Encode(map[string]any{+ "session_id": "trs_wire",+ "mcp": map[string]any{"type": "http", "url": "https://mcp.example/session/wire"},+ }); err != nil {+ t.Errorf("write response: %v", err)+ }+ }))+ defer upstream.Close()++ client, err := sdk.NewClient(sdk.Options{APIKey: "test-key", BaseURL: upstream.URL})+ if err != nil {+ t.Fatalf("new client: %v", err)+ }+ store := newFakeStore()+ svc := newTestService(t, client, store)+ owner := mintUUID(17)+ agent := makeAgent(owner, "notion", "github")+ seedActiveConnection(t, store, owner, "notion", "ca_owner_notion")+ seedActiveConnection(t, store, owner, "github", "ca_owner_github")+ seedActiveConnection(t, store, owner, "slack", "ca_owner_slack")++ result, err := svc.BuildTaskOverlay(context.Background(), owner, agent)+ if err != nil {+ t.Fatalf("BuildTaskOverlay: %v", err)+ }+ if len(result.MCPOverlay) == 0 {+ t.Fatal("expected non-empty overlay")+ }+ var posted map[string]any+ select {+ case posted = <-postedCh:+ default:+ }+ if posted == nil {+ t.Fatal("upstream did not receive a request body")+ }+ if got := posted["user_id"]; got != uuidToString(owner) {+ t.Fatalf("user_id = %v, want %q", got, uuidToString(owner))+ }++ toolkits, ok := posted["toolkits"].(map[string]any)+ if !ok {+ t.Fatalf("toolkits = %T(%v), want object", posted["toolkits"], posted["toolkits"])+ }+ assertJSONStringArraySet(t, toolkits["enable"], "notion", "github")+ if _, wrong := toolkits["enabled"]; wrong {+ t.Fatalf("toolkits used unexpected key \"enabled\": %v", toolkits)+ }++ connected, ok := posted["connected_accounts"].(map[string]any)+ if !ok {+ t.Fatalf("connected_accounts = %T(%v), want object", posted["connected_accounts"], posted["connected_accounts"])+ }+ assertJSONStringArraySet(t, connected["notion"], "ca_owner_notion")+ assertJSONStringArraySet(t, connected["github"], "ca_owner_github")+ if _, leaked := connected["slack"]; leaked {+ t.Fatalf("non-allowlisted slack leaked into connected_accounts: %v", connected)+ }+}++// --- Gate 5: defensive empty-URL response --------------------------------++// TestBuildTaskOverlay_EmptyURL guards a defensive branch: Composio+// returning a 200 with an empty mcp.url must not produce a half-baked+// overlay — every runtime sidecar generator would emit a server with an+// empty URL, breaking the task.+func TestBuildTaskOverlay_EmptyURL(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{+ createSessResp: &sdk.CreateSessionResponse{+ MCP: sdk.MCPDescriptor{URL: ""},+ },+ }+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ owner := mintUUID(14)+ agent := makeAgent(owner, "github")+ seedActiveConnection(t, store, owner, "github", "ca_owner_github")++ result, err := svc.BuildTaskOverlay(context.Background(), owner, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.MCPOverlay != nil {+ t.Errorf("expected nil overlay when MCP URL is empty, got %s", string(result.MCPOverlay))+ }+}++// --- SDK error surfacing -------------------------------------------------++// TestBuildTaskOverlay_SDKError — an SDK failure (Composio outage, network+// blip, …) must surface as an error so the caller can log it. The caller+// (TaskService.buildRuntimeMCPOverlay) is responsible for swallowing the error+// and proceeding with no overlay — best-effort enqueue.+func TestBuildTaskOverlay_SDKError(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{createSessErr: errors.New("composio: 503 backend")}+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ owner := mintUUID(15)+ agent := makeAgent(owner, "slack")+ seedActiveConnection(t, store, owner, "slack", "ca_owner_slack")++ result, err := svc.BuildTaskOverlay(context.Background(), owner, agent)+ if err == nil {+ t.Fatalf("expected error from SDK failure, got nil")+ }+ if !strings.Contains(err.Error(), "create session") {+ t.Errorf("error should mention create session, got %v", err)+ }+ if result.MCPOverlay != nil {+ t.Errorf("expected nil overlay on SDK error, got %s", string(result.MCPOverlay))+ }+}++// --- Slug normalisation regression --------------------------------------++// TestBuildTaskOverlay_NormalisesAllowlistAndConnectionSlugs — a+// defensively normalised compare. The API write path lowers + trims slugs+// before persisting, but DB migrations or out-of-band writes can put+// uppercase / padded entries in the column. The dispatch path must still+// match against (lowercased, trimmed) Composio connection rows so a+// well-intentioned UI typo cannot silently disable the overlay.+func TestBuildTaskOverlay_NormalisesAllowlistAndConnectionSlugs(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{+ createSessResp: &sdk.CreateSessionResponse{+ MCP: sdk.MCPDescriptor{URL: "https://mcp.composio.dev/session/x"},+ },+ }+ store := newFakeStore()+ svc := newTestService(t, sdkFake, store)+ owner := mintUUID(40)+ // allowlist has whitespace-padded MIXED-case entries.+ agent := makeAgent(owner, " Notion ", "GITHUB")+ // connection rows arrive with the canonical lowercased slugs (which+ // is what the connect flow always writes).+ seedActiveConnection(t, store, owner, "notion", "ca_a")++ result, err := svc.BuildTaskOverlay(context.Background(), owner, agent)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.MCPOverlay == nil {+ t.Fatalf("expected non-empty overlay despite uppercase/padded allowlist")+ }+ assertPinnedAccount(t, sdkFake.lastSessReq, "notion", "ca_a")+}++// containsString reports whether haystack contains needle. Small local+// helper so the tests don't pull in slices.Contains and stay copy-paste-+// compatible with the existing tests in this package.+func containsString(haystack []string, needle string) bool {+ for _, h := range haystack {+ if h == needle {+ return true+ }+ }+ return false+}++func assertJSONStringArraySet(t *testing.T, raw any, want ...string) {+ t.Helper()+ arr, ok := raw.([]any)+ if !ok {+ t.Fatalf("value = %T(%v), want JSON string array %v", raw, raw, want)+ }+ got := make(map[string]struct{}, len(arr))+ for _, item := range arr {+ s, ok := item.(string)+ if !ok {+ t.Fatalf("array item = %T(%v), want string", item, item)+ }+ got[s] = struct{}{}+ }+ if len(got) != len(want) {+ t.Fatalf("array = %v, want set %v", arr, want)+ }+ for _, w := range want {+ if _, ok := got[w]; !ok {+ t.Fatalf("array = %v, missing %q", arr, w)+ }+ }+}++func assertPinnedAccount(t *testing.T, req sdk.CreateSessionRequest, slug, want string) {+ t.Helper()+ got, ok := req.ConnectedAccounts[slug].([]string)+ if !ok {+ t.Fatalf("connected_accounts[%s] = %T(%v), want []string{%q}", slug, req.ConnectedAccounts[slug], req.ConnectedAccounts[slug], want)+ }+ if len(got) != 1 || got[0] != want {+ t.Errorf("connected_accounts[%s] = %v, want [%s]", slug, got, want)+ }+}++func assertConnectedApps(t *testing.T, apps []runtimeapps.ConnectedApp, want ...string) {+ t.Helper()+ if len(apps) != len(want) {+ t.Fatalf("connected apps = %+v, want slugs %v", apps, want)+ }+ got := make(map[string]runtimeapps.ConnectedApp, len(apps))+ for _, app := range apps {+ got[app.ToolkitSlug] = app+ }+ for _, slug := range want {+ app, ok := got[slug]+ if !ok {+ t.Fatalf("connected apps = %+v, missing %q", apps, slug)+ }+ if app.Provider != "composio" {+ t.Errorf("%s provider = %q, want composio", slug, app.Provider)+ }+ if app.ServerName != mcpOverlayServerName {+ t.Errorf("%s server = %q, want %q", slug, app.ServerName, mcpOverlayServerName)+ }+ if app.ToolkitName == "" {+ t.Errorf("%s has empty display name", slug)+ }+ }+ if _, leaked := got["slack"]; leaked {+ t.Fatalf("non-allowlisted slack leaked into connected apps: %+v", apps)+ }+}diff --git a/server/internal/integrations/composio/service.go b/server/internal/integrations/composio/service.gonew file mode 100644index 0000000000..462094d35d--- /dev/null+++ b/server/internal/integrations/composio/service.go@@ -0,0 +1,700 @@+// Package composio is the Stage 2 business-integration glue between Multica and+// the standalone Composio SDK (server/pkg/composio). It owns Multica semantics:+// the signed-state connect handshake, the local user_composio_connection+// mirror, idempotent disconnect, and the per-user MCP session helper.+//+// It deliberately does NOT wrap the SDK in another HTTP client — it composes+// *sdk.Client directly through the SDK interface so tests can drop in a fake.+//+// MVP scope (MUL-3720): toolkits are discovered dynamically. The+// toolkit→auth-config mapping is resolved at request time from Composio's+// /auth_configs endpoint (cached briefly), so a toolkit becomes connectable the+// moment an auth config is enabled for it in the Composio dashboard — no env+// var and no redeploy. A toolkit with no enabled auth config is rejected.+package composio++import (+ "context"+ "errors"+ "fmt"+ "net/url"+ "sort"+ "strings"+ "sync"+ "time"++ sdk "github.com/multica-ai/multica/server/pkg/composio"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Service-level errors surfaced to the handler layer.+var (+ // ErrToolkitNotSupported is returned by BeginConnect when the requested+ // toolkit has no enabled auth config in the Composio project, so there is+ // no auth_config_id to start a connect link with.+ ErrToolkitNotSupported = errors.New("composio: toolkit not supported")+ // ErrConnectNotSuccessful is returned by CompleteCallback when Composio+ // reported a non-success status — no active row is written.+ ErrConnectNotSuccessful = errors.New("composio: connection was not successful")+ // ErrConnectionNotFound is returned by Disconnect when the connection id+ // does not belong to the user (or does not exist).+ ErrConnectionNotFound = errors.New("composio: connection not found")+ // ErrAccountVerification is returned by CompleteCallback when the+ // connected_account_id carried on the callback cannot be confirmed (with+ // Composio) to belong to the user/auth-config named in the signed state —+ // i.e. a tampered or unknown account id. No local row is written.+ ErrAccountVerification = errors.New("composio: connected account verification failed")+)++// defaultStateTTL bounds how long a connect handshake may sit between+// BeginConnect and the Composio callback. Five minutes is generous for a hosted+// OAuth flow while keeping the replay window small.+const defaultStateTTL = 5 * time.Minute++// defaultAuthCacheTTL bounds how long the resolved toolkit→auth-config map is+// cached before a re-fetch from Composio. Short enough that enabling an auth+// config in the dashboard reflects within minutes; long enough that a burst of+// connect/list requests does not hammer /auth_configs.+const defaultAuthCacheTTL = 5 * time.Minute++// maxAuthConfigPages / maxToolkitPages cap the paginated fetch-all loops so a+// pathological or buggy upstream cursor cannot spin forever. At limit=1000 per+// page these cover far more than any real project / catalog.+const (+ maxAuthConfigPages = 20+ maxToolkitPages = 20+ listPageLimit = 1000+ composioLogoBaseURL = "https://logos.composio.dev/api"+)++// SDK is the subset of *sdk.Client the service depends on. Declared as an+// interface so handler/service tests can inject a fake without hitting Composio.+// *sdk.Client satisfies it.+type SDK interface {+ CreateLink(ctx context.Context, req sdk.CreateLinkRequest) (*sdk.CreateLinkResponse, error)+ ListConnectedAccounts(ctx context.Context, req sdk.ListConnectedAccountsRequest) (*sdk.ListConnectedAccountsResponse, error)+ ListAuthConfigs(ctx context.Context, req sdk.ListAuthConfigsRequest) (*sdk.ListAuthConfigsResponse, error)+ ListToolkits(ctx context.Context, req sdk.ListToolkitsRequest) (*sdk.ListToolkitsResponse, error)+ RevokeConnection(ctx context.Context, connectedAccountID string) error+ DeleteConnectedAccount(ctx context.Context, connectedAccountID string) error+ CreateSession(ctx context.Context, req sdk.CreateSessionRequest) (*sdk.CreateSessionResponse, error)+ MCPAuthHeaders() map[string]string+}++// Store is the persistence seam for the local connection mirror. *db.Queries+// satisfies it; tests use an in-memory fake.+type Store interface {+ UpsertUserComposioConnection(ctx context.Context, arg db.UpsertUserComposioConnectionParams) (db.UserComposioConnection, error)+ ListActiveUserComposioConnections(ctx context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error)+ GetUserComposioConnection(ctx context.Context, arg db.GetUserComposioConnectionParams) (db.UserComposioConnection, error)+ MarkUserComposioConnectionRevoked(ctx context.Context, arg db.MarkUserComposioConnectionRevokedParams) error+}++// Config configures a Service.+type Config struct {+ // StateSecret signs the connect-state HMAC. Required (non-empty).+ StateSecret []byte+ // CallbackBaseURL is the absolute, public base URL of THIS API, with no+ // trailing slash (e.g. "https://app.multica.ai"). The Composio callback+ // URL is built as CallbackBaseURL + CallbackPath. Required.+ CallbackBaseURL string+ // FrontendBaseURL is the web app base used to build the post-callback+ // browser redirect (e.g. "https://app.multica.ai"). May be empty, in which+ // case CallbackRedirect returns a site-relative path.+ FrontendBaseURL string+ // StateTTL overrides the default connect-state lifetime. Zero uses+ // defaultStateTTL.+ StateTTL time.Duration+ // AuthConfigTTL overrides how long the resolved toolkit→auth-config map is+ // cached. Zero uses defaultAuthCacheTTL.+ AuthConfigTTL time.Duration+ // Now is overridable for deterministic tests. Nil uses time.Now.+ Now func() time.Time+}++// callbackPath is the API path Composio redirects the browser back to. It is a+// constant (not configurable) so the SDK callback URL and the router route+// cannot drift apart.+const callbackPath = "/api/integrations/composio/callback"++// Service is the Composio business-integration service.+type Service struct {+ sdk SDK+ store Store+ secret []byte+ callbackURL string+ frontendURL string+ stateTTL time.Duration+ now func() time.Time++ // authCache holds the resolved toolkit_slug → auth_config_id map for the+ // project. It is rebuilt from Composio's /auth_configs endpoint on first+ // use and whenever authCacheExp has passed; authCacheMu guards both fields.+ authCacheMu sync.Mutex+ authCache map[string]string+ authCacheExp time.Time+ authCacheTTL time.Duration+}++// NewService validates its inputs and returns a ready Service. It errors when a+// required dependency is missing so a misconfigured boot fails loudly instead+// of returning 500s at request time.+func NewService(client SDK, store Store, cfg Config) (*Service, error) {+ if client == nil {+ return nil, errors.New("composio: SDK client is required")+ }+ if store == nil {+ return nil, errors.New("composio: store is required")+ }+ if len(cfg.StateSecret) == 0 {+ return nil, errors.New("composio: StateSecret is required")+ }+ base := strings.TrimRight(strings.TrimSpace(cfg.CallbackBaseURL), "/")+ if base == "" {+ return nil, errors.New("composio: CallbackBaseURL is required")+ }++ ttl := cfg.StateTTL+ if ttl <= 0 {+ ttl = defaultStateTTL+ }+ authTTL := cfg.AuthConfigTTL+ if authTTL <= 0 {+ authTTL = defaultAuthCacheTTL+ }+ now := cfg.Now+ if now == nil {+ now = time.Now+ }++ return &Service{+ sdk: client,+ store: store,+ secret: cfg.StateSecret,+ callbackURL: base + callbackPath,+ frontendURL: strings.TrimRight(strings.TrimSpace(cfg.FrontendBaseURL), "/"),+ stateTTL: ttl,+ now: now,+ authCacheTTL: authTTL,+ }, nil+}++// Connection is the API-facing view of a local connection row. The Composio+// connected_account_id and auth_config_id are intentionally omitted — they are+// server-internal handles, not API surface.+type Connection struct {+ ID string `json:"id"`+ ToolkitSlug string `json:"toolkit_slug"`+ Status string `json:"status"`+ ConnectedAt string `json:"connected_at"`+ LastUsedAt *string `json:"last_used_at"`+}++// MCPSession is the result of CreateMCPSession: the streamable MCP URL plus the+// headers an MCP client must attach. Headers carry the Composio x-api-key, so+// callers must route them through the redact pipeline before logging.+type MCPSession struct {+ URL string+ Headers map[string]string+}++// ToolkitView is the API-facing descriptor for one Composio toolkit, carrying+// exactly the fields the Settings UI renders plus a Connectable flag.+//+// Connectable means the project has an enabled auth config for the toolkit, so+// BeginConnect would succeed. When false the UI must not offer a working+// "Connect" affordance — clicking it would 400 with ErrToolkitNotSupported.+type ToolkitView struct {+ Slug string `json:"slug"`+ Name string `json:"name"`+ LogoURL string `json:"logo,omitempty"`+ Category string `json:"category,omitempty"`+ Connectable bool `json:"connectable"`+}++func toolkitLogoURL(slug, upstreamLogoURL string) string {+ if upstreamLogoURL != "" {+ return upstreamLogoURL+ }+ slug = strings.ToLower(strings.TrimSpace(slug))+ if slug == "" {+ return ""+ }+ return composioLogoBaseURL + "/" + url.PathEscape(slug)+}++// BeginConnect validates the toolkit, mints a signed state, and asks Composio+// for a hosted Connect Link. The returned redirect URL is where the caller+// sends the user's browser.+//+// The auth_config_id is resolved dynamically from the project's enabled auth+// configs (cached), so a toolkit is connectable iff the dashboard has an auth+// config for it — no static env map. A toolkit with none yields+// ErrToolkitNotSupported.+//+// The composio_user_id sent to Composio is the Multica user id verbatim — the+// invariant the rest of the integration relies on.+func (s *Service) BeginConnect(ctx context.Context, userID pgtype.UUID, toolkitSlug string) (string, error) {+ slug := strings.ToLower(strings.TrimSpace(toolkitSlug))+ authConfigID, err := s.authConfigForToolkit(ctx, slug)+ if err != nil {+ return "", err+ }+ if authConfigID == "" {+ return "", ErrToolkitNotSupported+ }+ if !userID.Valid {+ return "", errors.New("composio: invalid user id")+ }+ composioUserID := util.UUIDToString(userID)++ state, err := signState(s.secret, stateClaims{+ UserID: composioUserID,+ ToolkitSlug: slug,+ AuthConfigID: authConfigID,+ Exp: s.now().Add(s.stateTTL).Unix(),+ })+ if err != nil {+ return "", fmt.Errorf("composio: sign state: %w", err)+ }++ // Composio appends its own status / connected_account_id query params to+ // the callback URL and preserves ours, so the signed state rides back to us+ // on the redirect.+ callbackURL := s.callbackURL + "?state=" + url.QueryEscape(state)++ resp, err := s.sdk.CreateLink(ctx, sdk.CreateLinkRequest{+ AuthConfigID: authConfigID,+ UserID: composioUserID,+ CallbackURL: callbackURL,+ })+ if err != nil {+ return "", fmt.Errorf("composio: create link: %w", err)+ }+ return resp.RedirectURL, nil+}++// CompleteCallback verifies the signed state and, on a successful Composio+// status, upserts the local connection row. It returns the toolkit slug from+// the state so the handler can build the right redirect even on the+// not-successful path.+//+// Idempotency: the upsert is keyed on (user_id, connected_account_id), so a+// duplicate callback re-activates the same row instead of creating a second.+func (s *Service) CompleteCallback(ctx context.Context, state, status, connectedAccountID string) (string, error) {+ claims, err := verifyState(s.secret, state, s.now())+ if err != nil {+ return "", err+ }++ if !strings.EqualFold(strings.TrimSpace(status), "success") {+ // Honor the state for the redirect slug, but do not write an active row.+ return claims.ToolkitSlug, ErrConnectNotSuccessful+ }+ if strings.TrimSpace(connectedAccountID) == "" {+ return claims.ToolkitSlug, errors.New("composio: callback missing connected_account_id")+ }++ userID, err := util.ParseUUID(claims.UserID)+ if err != nil {+ return claims.ToolkitSlug, fmt.Errorf("composio: state has invalid user id: %w", err)+ }++ // The auth_config_id was resolved at BeginConnect and signed into the state,+ // so we compare against THAT exact value rather than re-resolving here (a+ // re-resolve that failed or drifted would otherwise fail-open: a missing+ // expected auth config used to skip the check, letting another toolkit's+ // account id be bound under this toolkit's slug). An empty value fails+ // closed in verifyAccountOwnership.+ authConfigID := claims.AuthConfigID++ // Defense-in-depth (PR 4608 review): the signed state proves *who* started+ // the handshake and *which* toolkit, but connected_account_id rides back as+ // a plain query param Composio appends to our callback URL. A crafted+ // redirect could pair a valid, un-expired state with someone else's account+ // id and we would mirror it verbatim. Before writing, confirm with Composio+ // that this account actually belongs to the state's user (the+ // composio_user_id == multica user id invariant) and was created under the+ // toolkit's auth config. Any mismatch fails closed with ErrAccountVerification.+ if err := s.verifyAccountOwnership(ctx, connectedAccountID, claims.UserID, authConfigID); err != nil {+ return claims.ToolkitSlug, err+ }++ if _, err := s.store.UpsertUserComposioConnection(ctx, db.UpsertUserComposioConnectionParams{+ UserID: userID,+ ToolkitSlug: claims.ToolkitSlug,+ AuthConfigID: authConfigID,+ ConnectedAccountID: connectedAccountID,+ // Invariant: composio_user_id == Multica user id.+ ComposioUserID: claims.UserID,+ }); err != nil {+ return claims.ToolkitSlug, fmt.Errorf("composio: upsert connection: %w", err)+ }+ return claims.ToolkitSlug, nil+}++// ListConnections returns the user's active connections.+func (s *Service) ListConnections(ctx context.Context, userID pgtype.UUID) ([]Connection, error) {+ rows, err := s.store.ListActiveUserComposioConnections(ctx, userID)+ if err != nil {+ return nil, err+ }+ out := make([]Connection, 0, len(rows))+ for _, row := range rows {+ out = append(out, rowToConnection(row))+ }+ return out, nil+}++// Disconnect revokes and deletes the connection at Composio, then marks the+// local row revoked. It is idempotent: a Composio 404 (already gone) is treated+// as success, and re-revoking an already-revoked local row is a no-op.+//+// A connection id that does not belong to the user (or does not exist at all)+// returns ErrConnectionNotFound so the handler can 404 without leaking+// existence across users.+func (s *Service) Disconnect(ctx context.Context, userID, connectionID pgtype.UUID) error {+ row, err := s.store.GetUserComposioConnection(ctx, db.GetUserComposioConnectionParams{+ ID: connectionID,+ UserID: userID,+ })+ if err != nil {+ // pgx.ErrNoRows or fake "not found" — treat as not found for the owner.+ return ErrConnectionNotFound+ }++ // Already disconnected locally: a repeat DELETE is a pure no-op. Short-+ // circuiting here keeps disconnect idempotent even when the upstream now+ // answers revoke/delete with a NON-404 error (PR 4608 review): the account+ // is already gone, so re-hitting Composio could turn a second DELETE into a+ // 502 and break the 204-idempotent contract. The first disconnect already+ // revoked upstream and marked the row.+ if !strings.EqualFold(row.Status, "active") {+ return nil+ }++ // Revoke the upstream grant first, then delete the Composio record. Both are+ // made idempotent against a 404 so a repeated disconnect (or a connection+ // already removed at Composio) still resolves the local row.+ if err := s.sdk.RevokeConnection(ctx, row.ConnectedAccountID); err != nil && !isNotFound(err) {+ return fmt.Errorf("composio: revoke connection: %w", err)+ }+ // DeleteConnectedAccount already swallows 404 in the SDK, but guard anyway.+ if err := s.sdk.DeleteConnectedAccount(ctx, row.ConnectedAccountID); err != nil && !isNotFound(err) {+ return fmt.Errorf("composio: delete connected account: %w", err)+ }++ if err := s.store.MarkUserComposioConnectionRevoked(ctx, db.MarkUserComposioConnectionRevokedParams{+ ID: connectionID,+ UserID: userID,+ }); err != nil {+ return fmt.Errorf("composio: mark revoked: %w", err)+ }+ return nil+}++// CreateMCPSession opens a Composio tool-router (MCP) session scoped to the+// user's active connections. It returns (nil, nil) when the user has no active+// connections — callers treat that as "no MCP overlay for this user".+//+// connected_accounts is pinned per toolkit to the user's own connected account+// id array so the session cannot surface accounts the user did not connect. This+// helper is NOT yet wired into task dispatch (Stage 3); it exists so that wiring+// is a pure consumer of an already-tested seam.+//+// Single-account constraint (v1, PR 4608 review follow-up): the MVP connect+// flow assumes AT MOST ONE active connection per (user, toolkit) — there is no+// UI or API to hold several. Should duplicates ever exist, we must choose+// deterministically: rows arrive newest-first (ListActive orders by+// connected_at DESC), so we keep the FIRST occurrence per toolkit (the most+// recently connected account) instead of letting a later map write silently+// select an older one.+//+// Stage 3 owns the real decision before this is wired into dispatch: either+// enforce the single-active constraint at connect time (revoke the previous+// active row for the same toolkit on a new connect) or extend CreateSession to+// a multi-account request shape. Until then, newest-wins keeps behavior+// deterministic rather than order-dependent.+func (s *Service) CreateMCPSession(ctx context.Context, userID pgtype.UUID) (*MCPSession, error) {+ rows, err := s.store.ListActiveUserComposioConnections(ctx, userID)+ if err != nil {+ return nil, err+ }+ if len(rows) == 0 {+ return nil, nil+ }++ connectedAccounts := make(map[string]any, len(rows))+ for _, row := range rows {+ // Keep the first (newest) account per toolkit; ignore older duplicates.+ if _, exists := connectedAccounts[row.ToolkitSlug]; exists {+ continue+ }+ connectedAccounts[row.ToolkitSlug] = []string{row.ConnectedAccountID}+ }++ resp, err := s.sdk.CreateSession(ctx, sdk.CreateSessionRequest{+ UserID: util.UUIDToString(userID),+ ConnectedAccounts: connectedAccounts,+ })+ if err != nil {+ return nil, fmt.Errorf("composio: create session: %w", err)+ }+ return &MCPSession{+ URL: resp.MCP.URL,+ Headers: s.sdk.MCPAuthHeaders(),+ }, nil+}++// CallbackRedirect builds the browser redirect target for the callback handler.+// On success it points at the settings page (Integrations tab) with the+// connected toolkit slug; on failure it carries a stable error code. The path+// is the slug-less `/settings?tab=integrations&...` form on purpose: the web+// proxy's legacy-route redirect prepends the user's last workspace slug, so it+// resolves to the real `/{slug}/settings?tab=integrations` route that mounts+// the Composio tab. The older `/settings/integrations` path was NOT a real+// route and 404'd after the legacy rewrite. When FrontendBaseURL is unset it+// returns a site-relative path.+func (s *Service) CallbackRedirect(slug string, success bool) string {+ var path string+ if success {+ path = "/settings?tab=integrations&connected=" + url.QueryEscape(slug)+ } else {+ path = "/settings?tab=integrations&error=composio_connect_failed"+ }+ return s.frontendURL + path+}++// rowToConnection maps a DB row to the API-facing Connection view.+func rowToConnection(row db.UserComposioConnection) Connection {+ c := Connection{+ ID: util.UUIDToString(row.ID),+ ToolkitSlug: row.ToolkitSlug,+ Status: row.Status,+ }+ if row.ConnectedAt.Valid {+ c.ConnectedAt = row.ConnectedAt.Time.UTC().Format(time.RFC3339)+ }+ c.LastUsedAt = util.TimestampToPtr(row.LastUsedAt)+ return c+}++// ListToolkits returns the full Composio toolkit catalog annotated with a+// Connectable flag (whether the project has an enabled auth config for each).+// It fetches all pages (capped by maxToolkitPages) so the UI gets the complete+// list in one call; the catalog is a few hundred entries, well within a single+// JSON response. Connectable toolkits are surfaced first so the UI can lead+// with what actually works.+func (s *Service) ListToolkits(ctx context.Context) ([]ToolkitView, error) {+ // connectable is the project's enabled toolkit_slug → auth_config_id map.+ // On a transient resolver error we still render the catalog, just with+ // everything marked not-connectable, rather than failing the whole list.+ connectable, err := s.authConfigMap(ctx)+ if err != nil {+ connectable = map[string]string{}+ }++ out := []ToolkitView{}+ seen := make(map[string]struct{})+ cursor := ""+ for page := 0; page < maxToolkitPages; page++ {+ resp, err := s.sdk.ListToolkits(ctx, sdk.ListToolkitsRequest{+ Limit: listPageLimit,+ Cursor: cursor,+ SortBy: "usage",+ })+ if err != nil {+ return nil, fmt.Errorf("composio: list toolkits: %w", err)+ }+ for _, tk := range resp.Items {+ slug := strings.ToLower(strings.TrimSpace(tk.Slug))+ if slug == "" {+ continue+ }+ if _, dup := seen[slug]; dup {+ continue+ }+ seen[slug] = struct{}{}+ category := ""+ if len(tk.Categories) > 0 {+ category = tk.Categories[0]+ }+ _, canConnect := connectable[slug]+ out = append(out, ToolkitView{+ Slug: tk.Slug,+ Name: tk.Name,+ LogoURL: toolkitLogoURL(slug, tk.LogoURL),+ Category: category,+ Connectable: canConnect,+ })+ }+ if resp.NextCursor == "" {+ break+ }+ cursor = resp.NextCursor+ }++ // Stable sort: connectable toolkits first, preserving Composio's usage+ // order within each group.+ sort.SliceStable(out, func(i, j int) bool {+ if out[i].Connectable != out[j].Connectable {+ return out[i].Connectable+ }+ return false+ })+ return out, nil+}++// authConfigForToolkit returns the chosen auth_config_id for a toolkit slug, or+// "" when the project has no enabled auth config for it. It reads the cached+// project-wide map (refreshed on TTL).+func (s *Service) authConfigForToolkit(ctx context.Context, slug string) (string, error) {+ slug = strings.ToLower(strings.TrimSpace(slug))+ if slug == "" {+ return "", nil+ }+ m, err := s.authConfigMap(ctx)+ if err != nil {+ return "", err+ }+ return m[slug], nil+}++// authConfigMap returns the toolkit_slug → auth_config_id map for the project,+// rebuilding it from Composio when the cache is empty or expired. Concurrent+// callers serialize on authCacheMu; the fetch runs under the lock, which is+// acceptable for a short-TTL map that is cheap to build and read by a+// low-traffic settings surface. A new map is assigned on refresh (never mutated+// in place), so a reference handed to a caller stays safe to read.+func (s *Service) authConfigMap(ctx context.Context) (map[string]string, error) {+ s.authCacheMu.Lock()+ defer s.authCacheMu.Unlock()+ if s.authCache != nil && s.now().Before(s.authCacheExp) {+ return s.authCache, nil+ }+ m, err := s.fetchAuthConfigMap(ctx)+ if err != nil {+ // Serve a stale snapshot if we have one — a transient /auth_configs+ // blip should not make every toolkit suddenly un-connectable.+ if s.authCache != nil {+ return s.authCache, nil+ }+ return nil, err+ }+ s.authCache = m+ s.authCacheExp = s.now().Add(s.authCacheTTL)+ return m, nil+}++// authCandidate is one project auth config in contention to represent a toolkit+// during resolution.+type authCandidate struct {+ id string+ managed bool+ updated string+}++// fetchAuthConfigMap pages through the project's ENABLED auth configs and+// reduces them to one chosen auth_config_id per toolkit slug. When a toolkit+// has several (e.g. a Composio-managed one plus a custom white-label one),+// betterAuthConfig picks the winner.+func (s *Service) fetchAuthConfigMap(ctx context.Context) (map[string]string, error) {+ best := make(map[string]authCandidate)+ cursor := ""+ for page := 0; page < maxAuthConfigPages; page++ {+ resp, err := s.sdk.ListAuthConfigs(ctx, sdk.ListAuthConfigsRequest{+ ShowDisabled: false,+ Limit: listPageLimit,+ Cursor: cursor,+ })+ if err != nil {+ return nil, fmt.Errorf("composio: list auth configs: %w", err)+ }+ for _, ac := range resp.Items {+ if ac.ID == "" || strings.EqualFold(ac.Status, "DISABLED") {+ continue+ }+ slug := strings.ToLower(strings.TrimSpace(ac.Toolkit.Slug))+ if slug == "" {+ continue+ }+ cand := authCandidate{id: ac.ID, managed: ac.IsComposioManaged, updated: ac.LastUpdatedAt}+ if cur, ok := best[slug]; !ok || betterAuthConfig(cand, cur) {+ best[slug] = cand+ }+ }+ if resp.NextCursor == "" {+ break+ }+ cursor = resp.NextCursor+ }+ out := make(map[string]string, len(best))+ for slug, c := range best {+ out[slug] = c.id+ }+ return out, nil+}++// betterAuthConfig reports whether candidate a should win over the currently+// selected b for the same toolkit. A custom (bring-your-own OAuth) config beats+// a Composio-managed one — it is the white-label path the product wants — and+// among configs of the same kind the most recently updated wins.+func betterAuthConfig(a, b authCandidate) bool {+ if a.managed != b.managed {+ return !a.managed+ }+ return a.updated > b.updated+}++// verifyAccountOwnership confirms with Composio that connectedAccountID really+// belongs to expectedUserID and was created under expectedAuthConfigID, so a+// tampered or cross-toolkit connected_account_id on the callback cannot smuggle+// another account into the local mirror. It fails closed: an upstream error, an+// unknown account, an owner mismatch, an EMPTY expected auth config, or an+// auth-config mismatch all return ErrAccountVerification. Requiring a non-empty,+// exactly-matching auth config is what closes the cross-toolkit binding gap —+// the expected value is the auth_config_id signed into the state at+// BeginConnect, which is toolkit-specific.+func (s *Service) verifyAccountOwnership(ctx context.Context, connectedAccountID, expectedUserID, expectedAuthConfigID string) error {+ resp, err := s.sdk.ListConnectedAccounts(ctx, sdk.ListConnectedAccountsRequest{+ ConnectedAccountIDs: []string{connectedAccountID},+ })+ if err != nil {+ return fmt.Errorf("composio: verify connected account: %w", err)+ }+ var acct *sdk.ConnectedAccount+ for i := range resp.Items {+ if resp.Items[i].ID == connectedAccountID {+ acct = &resp.Items[i]+ break+ }+ }+ if acct == nil {+ return ErrAccountVerification+ }+ if acct.UserID != expectedUserID {+ return ErrAccountVerification+ }+ // Fail closed: the account MUST have been created under the exact auth+ // config the connect link used. An empty expected value (state missing it,+ // or a resolver gap) is rejected rather than skipped — skipping is the+ // fail-open hole that let a cross-toolkit account id be bound here.+ accountAuthConfigID := acct.AuthConfigID+ if accountAuthConfigID == "" {+ accountAuthConfigID = acct.AuthConfig.ID+ }+ if expectedAuthConfigID == "" || accountAuthConfigID != expectedAuthConfigID {+ return ErrAccountVerification+ }+ return nil+}++// isNotFound reports whether err is a Composio 404 APIError, used to make+// revoke/delete idempotent.+func isNotFound(err error) bool {+ var apiErr *sdk.APIError+ return errors.As(err, &apiErr) && apiErr.IsNotFound()+}diff --git a/server/internal/integrations/composio/service_test.go b/server/internal/integrations/composio/service_test.gonew file mode 100644index 0000000000..2f981ac101--- /dev/null+++ b/server/internal/integrations/composio/service_test.go@@ -0,0 +1,722 @@+package composio++import (+ "context"+ "errors"+ "net/http"+ "net/url"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ sdk "github.com/multica-ai/multica/server/pkg/composio"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// ---- fakes ---------------------------------------------------------------++type fakeSDK struct {+ createLinkResp *sdk.CreateLinkResponse+ createLinkErr error+ lastCreateLink sdk.CreateLinkRequest+ revoked []string+ revokeErr error+ deleted []string+ deleteErr error+ createSessResp *sdk.CreateSessionResponse+ createSessErr error+ lastSessReq sdk.CreateSessionRequest+ createSessCalls int+ // account-ownership verification (CompleteCallback). By default+ // ListConnectedAccounts echoes the requested id with acctUserID /+ // acctAuthConfigID so success-path tests can opt in to a matching account;+ // acctMissing returns no items, listAccountsErr forces a transport error.+ acctUserID string+ acctAuthConfigID string+ acctNestedAuthConfigID string+ acctMissing bool+ listAccountsErr error+ lastListAccounts sdk.ListConnectedAccountsRequest+ // auth-config resolution (BeginConnect / ListToolkits connectable flag).+ // authConfigs nil => a default single notion→ac_notion ENABLED config so+ // existing connect tests keep resolving; set explicitly to override.+ authConfigs []sdk.AuthConfig+ authConfigsSet bool+ listAuthErr error+ // toolkit catalog (ListToolkits).+ toolkits []sdk.Toolkit+ listToolkitsErr error+}++func (f *fakeSDK) CreateLink(_ context.Context, req sdk.CreateLinkRequest) (*sdk.CreateLinkResponse, error) {+ f.lastCreateLink = req+ if f.createLinkErr != nil {+ return nil, f.createLinkErr+ }+ if f.createLinkResp != nil {+ return f.createLinkResp, nil+ }+ return &sdk.CreateLinkResponse{RedirectURL: "https://composio.example/redirect", ConnectedAccountID: "ca_pending"}, nil+}++func (f *fakeSDK) ListConnectedAccounts(_ context.Context, req sdk.ListConnectedAccountsRequest) (*sdk.ListConnectedAccountsResponse, error) {+ f.lastListAccounts = req+ if f.listAccountsErr != nil {+ return nil, f.listAccountsErr+ }+ if f.acctMissing {+ return &sdk.ListConnectedAccountsResponse{}, nil+ }+ id := ""+ if len(req.ConnectedAccountIDs) > 0 {+ id = req.ConnectedAccountIDs[0]+ }+ return &sdk.ListConnectedAccountsResponse{Items: []sdk.ConnectedAccount{{+ ID: id,+ UserID: f.acctUserID,+ AuthConfigID: f.acctAuthConfigID,+ AuthConfig: sdk.AuthConfigRef{ID: f.acctNestedAuthConfigID},+ }}}, nil+}++func (f *fakeSDK) ListAuthConfigs(_ context.Context, _ sdk.ListAuthConfigsRequest) (*sdk.ListAuthConfigsResponse, error) {+ if f.listAuthErr != nil {+ return nil, f.listAuthErr+ }+ items := f.authConfigs+ if !f.authConfigsSet && items == nil {+ items = []sdk.AuthConfig{{+ ID: "ac_notion",+ Toolkit: sdk.Toolkit{Slug: "notion"},+ Status: "ENABLED",+ IsComposioManaged: true,+ }}+ }+ return &sdk.ListAuthConfigsResponse{Items: items}, nil+}++func (f *fakeSDK) ListToolkits(_ context.Context, _ sdk.ListToolkitsRequest) (*sdk.ListToolkitsResponse, error) {+ if f.listToolkitsErr != nil {+ return nil, f.listToolkitsErr+ }+ return &sdk.ListToolkitsResponse{Items: f.toolkits}, nil+}++func (f *fakeSDK) RevokeConnection(_ context.Context, id string) error {+ f.revoked = append(f.revoked, id)+ return f.revokeErr+}++func (f *fakeSDK) DeleteConnectedAccount(_ context.Context, id string) error {+ f.deleted = append(f.deleted, id)+ return f.deleteErr+}++func (f *fakeSDK) CreateSession(_ context.Context, req sdk.CreateSessionRequest) (*sdk.CreateSessionResponse, error) {+ f.createSessCalls+++ f.lastSessReq = req+ if f.createSessErr != nil {+ return nil, f.createSessErr+ }+ if f.createSessResp != nil {+ return f.createSessResp, nil+ }+ return &sdk.CreateSessionResponse{MCP: sdk.MCPDescriptor{URL: "https://mcp.example/session"}}, nil+}++func (f *fakeSDK) MCPAuthHeaders() map[string]string {+ return map[string]string{"x-api-key": "secret"}+}++// fakeStore is an in-memory implementation of Store with the same+// (user_id, connected_account_id) uniqueness as the real table.+type fakeStore struct {+ rows []db.UserComposioConnection+ nextID byte+}++func newFakeStore() *fakeStore { return &fakeStore{nextID: 1} }++func (s *fakeStore) UpsertUserComposioConnection(_ context.Context, arg db.UpsertUserComposioConnectionParams) (db.UserComposioConnection, error) {+ for i := range s.rows {+ if uuidEqual(s.rows[i].UserID, arg.UserID) && s.rows[i].ConnectedAccountID == arg.ConnectedAccountID {+ s.rows[i].ToolkitSlug = arg.ToolkitSlug+ s.rows[i].AuthConfigID = arg.AuthConfigID+ s.rows[i].ComposioUserID = arg.ComposioUserID+ s.rows[i].Status = "active"+ s.rows[i].UpdatedAt = pgtype.Timestamptz{Time: time.Now(), Valid: true}+ return s.rows[i], nil+ }+ }+ row := db.UserComposioConnection{+ ID: mintUUID(s.nextID),+ UserID: arg.UserID,+ ToolkitSlug: arg.ToolkitSlug,+ AuthConfigID: arg.AuthConfigID,+ ConnectedAccountID: arg.ConnectedAccountID,+ ComposioUserID: arg.ComposioUserID,+ Status: "active",+ ConnectedAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ }+ s.nextID+++ s.rows = append(s.rows, row)+ return row, nil+}++func (s *fakeStore) ListActiveUserComposioConnections(_ context.Context, userID pgtype.UUID) ([]db.UserComposioConnection, error) {+ out := []db.UserComposioConnection{}+ for _, r := range s.rows {+ if uuidEqual(r.UserID, userID) && r.Status == "active" {+ out = append(out, r)+ }+ }+ return out, nil+}++func (s *fakeStore) GetUserComposioConnection(_ context.Context, arg db.GetUserComposioConnectionParams) (db.UserComposioConnection, error) {+ for _, r := range s.rows {+ if uuidEqual(r.ID, arg.ID) && uuidEqual(r.UserID, arg.UserID) {+ return r, nil+ }+ }+ return db.UserComposioConnection{}, pgx.ErrNoRows+}++func (s *fakeStore) MarkUserComposioConnectionRevoked(_ context.Context, arg db.MarkUserComposioConnectionRevokedParams) error {+ for i := range s.rows {+ if uuidEqual(s.rows[i].ID, arg.ID) && uuidEqual(s.rows[i].UserID, arg.UserID) {+ s.rows[i].Status = "revoked"+ }+ }+ return nil+}++func uuidEqual(a, b pgtype.UUID) bool { return a.Valid && b.Valid && a.Bytes == b.Bytes }++func mintUUID(n byte) pgtype.UUID {+ var b [16]byte+ b[15] = n+ return pgtype.UUID{Bytes: b, Valid: true}+}++func newTestService(t *testing.T, client SDK, store Store) *Service {+ t.Helper()+ svc, err := NewService(client, store, Config{+ StateSecret: testSecret,+ CallbackBaseURL: "https://app.multica.ai",+ FrontendBaseURL: "https://app.multica.ai",+ Now: func() time.Time { return time.Unix(1_700_000_000, 0) },+ })+ if err != nil {+ t.Fatalf("NewService: %v", err)+ }+ return svc+}++// ---- tests ---------------------------------------------------------------++func TestNewService_Validation(t *testing.T) {+ t.Parallel()+ if _, err := NewService(nil, newFakeStore(), Config{StateSecret: testSecret, CallbackBaseURL: "x"}); err == nil {+ t.Error("expected error for nil client")+ }+ if _, err := NewService(&fakeSDK{}, nil, Config{StateSecret: testSecret, CallbackBaseURL: "x"}); err == nil {+ t.Error("expected error for nil store")+ }+ if _, err := NewService(&fakeSDK{}, newFakeStore(), Config{CallbackBaseURL: "x"}); err == nil {+ t.Error("expected error for empty secret")+ }+ if _, err := NewService(&fakeSDK{}, newFakeStore(), Config{StateSecret: testSecret}); err == nil {+ t.Error("expected error for empty callback base")+ }+}++func TestBeginConnect_MappingAndState(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{}+ svc := newTestService(t, sdkFake, newFakeStore())+ userID := mintUUID(7)++ redirect, err := svc.BeginConnect(context.Background(), userID, "Notion")+ if err != nil {+ t.Fatalf("BeginConnect: %v", err)+ }+ if redirect != "https://composio.example/redirect" {+ t.Errorf("redirect = %q", redirect)+ }+ // toolkit → auth_config mapping+ if sdkFake.lastCreateLink.AuthConfigID != "ac_notion" {+ t.Errorf("auth config = %q", sdkFake.lastCreateLink.AuthConfigID)+ }+ // composio_user_id == multica user id+ if sdkFake.lastCreateLink.UserID != util.UUIDToString(userID) {+ t.Errorf("composio user id = %q, want %q", sdkFake.lastCreateLink.UserID, util.UUIDToString(userID))+ }+ // callback URL carries the signed state and points at our callback path+ cb := sdkFake.lastCreateLink.CallbackURL+ if !strings.HasPrefix(cb, "https://app.multica.ai"+callbackPath+"?state=") {+ t.Fatalf("callback url = %q", cb)+ }+ u, _ := url.Parse(cb)+ state := u.Query().Get("state")+ claims, err := verifyState(testSecret, state, time.Unix(1_700_000_000, 0))+ if err != nil {+ t.Fatalf("state did not verify: %v", err)+ }+ if claims.ToolkitSlug != "notion" || claims.UserID != util.UUIDToString(userID) {+ t.Errorf("claims = %+v", claims)+ }+ // The resolved auth_config_id is signed into the state so the callback can+ // verify the returned account against it exactly (no fail-open re-resolve).+ if claims.AuthConfigID != "ac_notion" {+ t.Errorf("state auth config = %q, want ac_notion", claims.AuthConfigID)+ }+}++func TestBeginConnect_UnsupportedToolkit(t *testing.T) {+ t.Parallel()+ svc := newTestService(t, &fakeSDK{}, newFakeStore())+ if _, err := svc.BeginConnect(context.Background(), mintUUID(1), "github"); !errors.Is(err, ErrToolkitNotSupported) {+ t.Fatalf("expected ErrToolkitNotSupported, got %v", err)+ }+}++// TestBeginConnect_UnsupportedWhenNoAuthConfig: with the project reporting no+// enabled auth configs at all, even notion is not connectable.+func TestBeginConnect_UnsupportedWhenNoAuthConfig(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{authConfigsSet: true, authConfigs: []sdk.AuthConfig{}}+ svc := newTestService(t, sdkFake, newFakeStore())+ if _, err := svc.BeginConnect(context.Background(), mintUUID(1), "notion"); !errors.Is(err, ErrToolkitNotSupported) {+ t.Fatalf("expected ErrToolkitNotSupported with no auth configs, got %v", err)+ }+}++// TestBeginConnect_PrefersCustomAuthConfig: when a toolkit has both a+// Composio-managed and a custom (white-label) auth config, the custom one wins.+func TestBeginConnect_PrefersCustomAuthConfig(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{authConfigsSet: true, authConfigs: []sdk.AuthConfig{+ {ID: "ac_managed", Toolkit: sdk.Toolkit{Slug: "notion"}, Status: "ENABLED", IsComposioManaged: true},+ {ID: "ac_custom", Toolkit: sdk.Toolkit{Slug: "notion"}, Status: "ENABLED", IsComposioManaged: false},+ }}+ svc := newTestService(t, sdkFake, newFakeStore())+ if _, err := svc.BeginConnect(context.Background(), mintUUID(1), "notion"); err != nil {+ t.Fatalf("BeginConnect: %v", err)+ }+ if sdkFake.lastCreateLink.AuthConfigID != "ac_custom" {+ t.Errorf("auth config = %q, want ac_custom (custom preferred over managed)", sdkFake.lastCreateLink.AuthConfigID)+ }+}++// TestListToolkits_ConnectableFlagAndOrder: every toolkit is listed, but only+// those with an enabled auth config are connectable, and connectable ones sort+// first.+func TestListToolkits_ConnectableFlagAndOrder(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{+ authConfigsSet: true,+ authConfigs: []sdk.AuthConfig{+ {ID: "ac_notion", Toolkit: sdk.Toolkit{Slug: "notion"}, Status: "ENABLED"},+ },+ toolkits: []sdk.Toolkit{+ {Slug: "github", Name: "GitHub", LogoURL: "https://logo/gh", Categories: []string{"dev"}},+ {Slug: "notion", Name: "Notion", LogoURL: "https://logo/notion", Categories: []string{"productivity"}},+ {Slug: "slack", Name: "Slack"},+ },+ }+ svc := newTestService(t, sdkFake, newFakeStore())+ tks, err := svc.ListToolkits(context.Background())+ if err != nil {+ t.Fatalf("ListToolkits: %v", err)+ }+ if len(tks) != 3 {+ t.Fatalf("expected 3 toolkits, got %d", len(tks))+ }+ // Connectable (notion) sorts first.+ if tks[0].Slug != "notion" || !tks[0].Connectable {+ t.Errorf("first toolkit = %+v, want connectable notion", tks[0])+ }+ if tks[0].Name != "Notion" || tks[0].LogoURL != "https://logo/notion" || tks[0].Category != "productivity" {+ t.Errorf("notion fields not mapped: %+v", tks[0])+ }+ for _, tk := range tks[1:] {+ if tk.Connectable {+ t.Errorf("toolkit %q should not be connectable", tk.Slug)+ }+ }+ for _, tk := range tks {+ if tk.Slug == "slack" && tk.LogoURL != "https://logos.composio.dev/api/slack" {+ t.Errorf("slack default logo = %q", tk.LogoURL)+ }+ }+}++// TestListToolkits_PaginatesAndResolverErrorIsSoft: a paginated catalog is+// fully drained, and an /auth_configs failure degrades to "nothing+// connectable" instead of failing the whole list.+func TestListToolkits_ResolverErrorMarksNoneConnectable(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{+ listAuthErr: errors.New("upstream blip"),+ toolkits: []sdk.Toolkit{{Slug: "notion", Name: "Notion"}},+ }+ svc := newTestService(t, sdkFake, newFakeStore())+ tks, err := svc.ListToolkits(context.Background())+ if err != nil {+ t.Fatalf("ListToolkits should not fail on auth-config error, got %v", err)+ }+ if len(tks) != 1 || tks[0].Connectable {+ t.Fatalf("expected 1 non-connectable toolkit, got %+v", tks)+ }+}++func TestCompleteCallback_SuccessAndIdempotent(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ userID := mintUUID(3)+ // The account Composio reports for ca_123 belongs to this user under the+ // notion auth config, so ownership verification passes.+ sdkFake := &fakeSDK{acctUserID: util.UUIDToString(userID), acctAuthConfigID: "ac_notion"}+ svc := newTestService(t, sdkFake, store)+ state, _ := signState(testSecret, stateClaims{+ UserID: util.UUIDToString(userID),+ ToolkitSlug: "notion",+ AuthConfigID: "ac_notion",+ Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),+ })++ slug, err := svc.CompleteCallback(context.Background(), state, "success", "ca_123")+ if err != nil {+ t.Fatalf("CompleteCallback: %v", err)+ }+ if slug != "notion" {+ t.Errorf("slug = %q", slug)+ }+ // Duplicate callback (same connected account) must not create a 2nd row.+ if _, err := svc.CompleteCallback(context.Background(), state, "success", "ca_123"); err != nil {+ t.Fatalf("second CompleteCallback: %v", err)+ }+ if len(store.rows) != 1 {+ t.Fatalf("expected 1 row after duplicate callback, got %d", len(store.rows))+ }+ row := store.rows[0]+ if row.ComposioUserID != util.UUIDToString(userID) {+ t.Errorf("composio_user_id invariant broken: %q", row.ComposioUserID)+ }+ if row.AuthConfigID != "ac_notion" || row.ToolkitSlug != "notion" || row.Status != "active" {+ t.Errorf("row = %+v", row)+ }+}++func TestCompleteCallback_AcceptsNestedAuthConfig(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ userID := mintUUID(30)+ // Composio v3.1 returns connected-account auth config under auth_config.id,+ // not always as a top-level auth_config_id.+ sdkFake := &fakeSDK{acctUserID: util.UUIDToString(userID), acctNestedAuthConfigID: "ac_notion"}+ svc := newTestService(t, sdkFake, store)+ state, _ := signState(testSecret, stateClaims{+ UserID: util.UUIDToString(userID),+ ToolkitSlug: "notion",+ AuthConfigID: "ac_notion",+ Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),+ })++ if _, err := svc.CompleteCallback(context.Background(), state, "success", "ca_nested"); err != nil {+ t.Fatalf("CompleteCallback: %v", err)+ }+ if len(store.rows) != 1 {+ t.Fatalf("expected 1 row, got %d", len(store.rows))+ }+}++func TestCompleteCallback_NonSuccessNoRow(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ svc := newTestService(t, &fakeSDK{}, store)+ state, _ := signState(testSecret, stateClaims{+ UserID: util.UUIDToString(mintUUID(4)),+ ToolkitSlug: "notion",+ Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),+ })+ slug, err := svc.CompleteCallback(context.Background(), state, "failed", "ca_x")+ if !errors.Is(err, ErrConnectNotSuccessful) {+ t.Fatalf("expected ErrConnectNotSuccessful, got %v", err)+ }+ if slug != "notion" {+ t.Errorf("slug = %q (should still be returned for redirect)", slug)+ }+ if len(store.rows) != 0 {+ t.Fatalf("expected no row written on non-success, got %d", len(store.rows))+ }+}++func TestCompleteCallback_BadState(t *testing.T) {+ t.Parallel()+ svc := newTestService(t, &fakeSDK{}, newFakeStore())+ if _, err := svc.CompleteCallback(context.Background(), "garbage", "success", "ca_1"); err == nil {+ t.Fatal("expected error for malformed state")+ }+}++// TestCompleteCallback_TamperedAccountRejected covers the PR 4608 blocker:+// a valid, un-expired state paired with a connected_account_id that Composio+// reports as belonging to a DIFFERENT user must be rejected, and no row written.+func TestCompleteCallback_TamperedAccountRejected(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ userID := mintUUID(20)+ // Composio says ca_evil belongs to someone else, not our state's user.+ sdkFake := &fakeSDK{acctUserID: util.UUIDToString(mintUUID(99)), acctAuthConfigID: "ac_notion"}+ svc := newTestService(t, sdkFake, store)+ state, _ := signState(testSecret, stateClaims{+ UserID: util.UUIDToString(userID),+ ToolkitSlug: "notion",+ AuthConfigID: "ac_notion",+ Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),+ })+ if _, err := svc.CompleteCallback(context.Background(), state, "success", "ca_evil"); !errors.Is(err, ErrAccountVerification) {+ t.Fatalf("expected ErrAccountVerification for foreign account, got %v", err)+ }+ if len(store.rows) != 0 {+ t.Fatalf("no row should be written when ownership fails, got %d", len(store.rows))+ }+}++// TestCompleteCallback_WrongAuthConfigRejected is the cross-toolkit proof: the+// account belongs to the right user but was created under a DIFFERENT toolkit's+// auth config (e.g. the user pasting their slack account id into a notion+// callback). The state-signed auth_config_id must not match, so it is rejected.+func TestCompleteCallback_WrongAuthConfigRejected(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ userID := mintUUID(21)+ // Account is owned by the user but lives under ac_other (another toolkit).+ sdkFake := &fakeSDK{acctUserID: util.UUIDToString(userID), acctAuthConfigID: "ac_other"}+ svc := newTestService(t, sdkFake, store)+ state, _ := signState(testSecret, stateClaims{+ UserID: util.UUIDToString(userID),+ ToolkitSlug: "notion",+ AuthConfigID: "ac_notion",+ Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),+ })+ if _, err := svc.CompleteCallback(context.Background(), state, "success", "ca_x"); !errors.Is(err, ErrAccountVerification) {+ t.Fatalf("expected ErrAccountVerification for wrong auth config, got %v", err)+ }+ if len(store.rows) != 0 {+ t.Fatalf("no row should be written, got %d", len(store.rows))+ }+}++// TestCompleteCallback_MissingAuthConfigFailsClosed is the regression for the+// re-review blocker: a state with no signed auth_config_id (the old fail-open+// path) plus an account owned by the user must STILL be rejected — the empty+// expected auth config now fails closed instead of skipping the check.+func TestCompleteCallback_MissingAuthConfigFailsClosed(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ userID := mintUUID(25)+ // Account genuinely belongs to the user — only the missing auth-config+ // binding should trip the rejection.+ sdkFake := &fakeSDK{acctUserID: util.UUIDToString(userID), acctAuthConfigID: "ac_notion"}+ svc := newTestService(t, sdkFake, store)+ state, _ := signState(testSecret, stateClaims{+ UserID: util.UUIDToString(userID),+ ToolkitSlug: "notion",+ // AuthConfigID deliberately omitted (empty) — must fail closed.+ Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),+ })+ if _, err := svc.CompleteCallback(context.Background(), state, "success", "ca_owned"); !errors.Is(err, ErrAccountVerification) {+ t.Fatalf("expected ErrAccountVerification when state carries no auth config, got %v", err)+ }+ if len(store.rows) != 0 {+ t.Fatalf("no row should be written, got %d", len(store.rows))+ }+}++// TestCompleteCallback_UnknownAccountRejected ensures an account id Composio+// does not know about fails closed rather than being mirrored verbatim.+func TestCompleteCallback_UnknownAccountRejected(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ userID := mintUUID(22)+ sdkFake := &fakeSDK{acctMissing: true}+ svc := newTestService(t, sdkFake, store)+ state, _ := signState(testSecret, stateClaims{+ UserID: util.UUIDToString(userID),+ ToolkitSlug: "notion",+ Exp: time.Unix(1_700_000_000, 0).Add(time.Minute).Unix(),+ })+ if _, err := svc.CompleteCallback(context.Background(), state, "success", "ca_ghost"); !errors.Is(err, ErrAccountVerification) {+ t.Fatalf("expected ErrAccountVerification for unknown account, got %v", err)+ }+ if len(store.rows) != 0 {+ t.Fatalf("no row should be written, got %d", len(store.rows))+ }+}++func TestListConnections(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ svc := newTestService(t, &fakeSDK{}, store)+ userID := mintUUID(5)+ seedActive(store, userID, "notion", "ca_a")++ conns, err := svc.ListConnections(context.Background(), userID)+ if err != nil {+ t.Fatalf("ListConnections: %v", err)+ }+ if len(conns) != 1 || conns[0].ToolkitSlug != "notion" || conns[0].Status != "active" {+ t.Fatalf("conns = %+v", conns)+ }+}++func TestDisconnect_OwnerRevokeIdempotentAndFilter(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ sdkFake := &fakeSDK{}+ svc := newTestService(t, sdkFake, store)+ userID := mintUUID(6)+ row := seedActive(store, userID, "notion", "ca_z")++ if err := svc.Disconnect(context.Background(), userID, row.ID); err != nil {+ t.Fatalf("Disconnect: %v", err)+ }+ if len(sdkFake.revoked) != 1 || sdkFake.revoked[0] != "ca_z" {+ t.Errorf("revoked = %v", sdkFake.revoked)+ }+ // Local row should now be filtered out of the active list.+ conns, _ := svc.ListConnections(context.Background(), userID)+ if len(conns) != 0 {+ t.Errorf("expected 0 active after disconnect, got %d", len(conns))+ }+ // Second disconnect is idempotent (row still owned, marks revoked again).+ if err := svc.Disconnect(context.Background(), userID, row.ID); err != nil {+ t.Fatalf("idempotent Disconnect: %v", err)+ }+}++// TestDisconnect_RevokedRowNoOp covers the PR 4608 blocker: once a row is+// locally revoked, a second DELETE must be a pure no-op and must NOT call+// upstream again — otherwise a non-404 upstream error on the repeat would be+// surfaced as a 502 and break idempotency.+func TestDisconnect_RevokedRowNoOp(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ sdkFake := &fakeSDK{}+ svc := newTestService(t, sdkFake, store)+ userID := mintUUID(30)+ row := seedActive(store, userID, "notion", "ca_noop")++ // First disconnect revokes upstream and marks the row revoked.+ if err := svc.Disconnect(context.Background(), userID, row.ID); err != nil {+ t.Fatalf("first Disconnect: %v", err)+ }+ if len(sdkFake.revoked) != 1 {+ t.Fatalf("expected 1 upstream revoke, got %d", len(sdkFake.revoked))+ }++ // Now make the upstream fail with a NON-404 error. A correct no-op must not+ // touch upstream, so this error must never surface.+ sdkFake.revokeErr = &sdk.APIError{HTTPStatus: http.StatusInternalServerError}+ sdkFake.deleteErr = &sdk.APIError{HTTPStatus: http.StatusInternalServerError}+ if err := svc.Disconnect(context.Background(), userID, row.ID); err != nil {+ t.Fatalf("second Disconnect on already-revoked row should be a no-op, got %v", err)+ }+ if len(sdkFake.revoked) != 1 {+ t.Errorf("second disconnect must not call upstream revoke again, revoked=%v", sdkFake.revoked)+ }+}++func TestDisconnect_UpstreamNotFoundIsIdempotent(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ sdkFake := &fakeSDK{revokeErr: &sdk.APIError{HTTPStatus: http.StatusNotFound}}+ svc := newTestService(t, sdkFake, store)+ userID := mintUUID(8)+ row := seedActive(store, userID, "notion", "ca_404")++ if err := svc.Disconnect(context.Background(), userID, row.ID); err != nil {+ t.Fatalf("Disconnect should treat upstream 404 as success, got %v", err)+ }+}++func TestDisconnect_NotOwner(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ svc := newTestService(t, &fakeSDK{}, store)+ owner := mintUUID(9)+ row := seedActive(store, owner, "notion", "ca_o")+ attacker := mintUUID(10)+ if err := svc.Disconnect(context.Background(), attacker, row.ID); !errors.Is(err, ErrConnectionNotFound) {+ t.Fatalf("expected ErrConnectionNotFound for non-owner, got %v", err)+ }+}++func TestCreateMCPSession_NoOpWhenEmpty(t *testing.T) {+ t.Parallel()+ sdkFake := &fakeSDK{}+ svc := newTestService(t, sdkFake, newFakeStore())+ sess, err := svc.CreateMCPSession(context.Background(), mintUUID(11))+ if err != nil {+ t.Fatalf("CreateMCPSession: %v", err)+ }+ if sess != nil {+ t.Fatalf("expected nil session when no connections, got %+v", sess)+ }+ if sdkFake.createSessCalls != 0 {+ t.Errorf("CreateSession should not be called when there are no connections")+ }+}++func TestCreateMCPSession_PinsConnectedAccounts(t *testing.T) {+ t.Parallel()+ store := newFakeStore()+ sdkFake := &fakeSDK{}+ svc := newTestService(t, sdkFake, store)+ userID := mintUUID(12)+ seedActive(store, userID, "notion", "ca_pin")++ sess, err := svc.CreateMCPSession(context.Background(), userID)+ if err != nil {+ t.Fatalf("CreateMCPSession: %v", err)+ }+ if sess == nil || sess.URL != "https://mcp.example/session" {+ t.Fatalf("session = %+v", sess)+ }+ if sess.Headers["x-api-key"] != "secret" {+ t.Errorf("headers = %+v", sess.Headers)+ }+ if sdkFake.lastSessReq.UserID != util.UUIDToString(userID) {+ t.Errorf("session user id = %q", sdkFake.lastSessReq.UserID)+ }+ assertPinnedAccount(t, sdkFake.lastSessReq, "notion", "ca_pin")+}++func TestCallbackRedirect(t *testing.T) {+ t.Parallel()+ svc := newTestService(t, &fakeSDK{}, newFakeStore())+ if got := svc.CallbackRedirect("notion", true); got != "https://app.multica.ai/settings?tab=integrations&connected=notion" {+ t.Errorf("success redirect = %q", got)+ }+ if got := svc.CallbackRedirect("notion", false); got != "https://app.multica.ai/settings?tab=integrations&error=composio_connect_failed" {+ t.Errorf("failure redirect = %q", got)+ }+}++// seedActive inserts an active connection through the store and returns the row.+func seedActive(store *fakeStore, userID pgtype.UUID, slug, caID string) db.UserComposioConnection {+ row, _ := store.UpsertUserComposioConnection(context.Background(), db.UpsertUserComposioConnectionParams{+ UserID: userID,+ ToolkitSlug: slug,+ AuthConfigID: "ac_notion",+ ConnectedAccountID: caID,+ ComposioUserID: util.UUIDToString(userID),+ })+ return row+}diff --git a/server/internal/integrations/composio/state.go b/server/internal/integrations/composio/state.gonew file mode 100644index 0000000000..3c23b7b9af--- /dev/null+++ b/server/internal/integrations/composio/state.go@@ -0,0 +1,92 @@+package composio++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "errors"+ "strings"+ "time"+)++// Signed-state errors. The handler maps all of them to a generic+// "connect failed" redirect so a tampered/expired state never leaks which+// check failed.+var (+ // ErrStateMalformed is returned when the state token is not the expected+ // "<payload>.<sig>" base64url shape.+ ErrStateMalformed = errors.New("composio: state malformed")+ // ErrStateSignature is returned when the HMAC signature does not match —+ // the state was tampered with or signed by a different secret.+ ErrStateSignature = errors.New("composio: state signature mismatch")+ // ErrStateExpired is returned when the state's exp claim is in the past.+ ErrStateExpired = errors.New("composio: state expired")+)++// stateClaims is the payload embedded in the signed connect-state. It carries+// exactly what CompleteCallback needs to attribute the callback to a user and+// toolkit without a server-side session table — the signature is what makes it+// trustworthy, the short exp is what bounds replay.+//+// Field names are single letters to keep the encoded token compact; they are+// an internal wire format, never exposed to clients.+type stateClaims struct {+ UserID string `json:"u"`+ ToolkitSlug string `json:"t"`+ // AuthConfigID is the exact Composio auth_config_id resolved at BeginConnect+ // and used to create the connect link. Signing it into the state lets+ // CompleteCallback verify the returned account was created under THIS+ // toolkit's auth config without re-resolving (which could fail-open). It is+ // an opaque config handle (ac_…), not a credential.+ AuthConfigID string `json:"a"`+ Exp int64 `json:"e"`+}++// signState produces a URL-safe "<payload>.<sig>" token. payload is the+// base64url-encoded JSON claims; sig is the base64url-encoded HMAC-SHA256 of+// the payload under the service secret. We sign the encoded payload (not the+// raw struct) so verification re-derives the exact bytes that were signed.+func signState(secret []byte, claims stateClaims) (string, error) {+ raw, err := json.Marshal(claims)+ if err != nil {+ return "", err+ }+ payload := base64.RawURLEncoding.EncodeToString(raw)+ sig := signPayload(secret, payload)+ return payload + "." + sig, nil+}++// verifyState validates the signature and expiry of a token produced by+// signState and returns the embedded claims. Signature is checked with a+// constant-time compare before the payload is trusted; expiry is checked+// against now.+func verifyState(secret []byte, token string, now time.Time) (stateClaims, error) {+ payload, sig, found := strings.Cut(token, ".")+ if !found || payload == "" || sig == "" {+ return stateClaims{}, ErrStateMalformed+ }+ expected := signPayload(secret, payload)+ if !hmac.Equal([]byte(sig), []byte(expected)) {+ return stateClaims{}, ErrStateSignature+ }+ raw, err := base64.RawURLEncoding.DecodeString(payload)+ if err != nil {+ return stateClaims{}, ErrStateMalformed+ }+ var claims stateClaims+ if err := json.Unmarshal(raw, &claims); err != nil {+ return stateClaims{}, ErrStateMalformed+ }+ if now.Unix() > claims.Exp {+ return stateClaims{}, ErrStateExpired+ }+ return claims, nil+}++// signPayload returns the base64url HMAC-SHA256 of payload under secret.+func signPayload(secret []byte, payload string) string {+ mac := hmac.New(sha256.New, secret)+ mac.Write([]byte(payload))+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))+}diff --git a/server/internal/integrations/composio/state_test.go b/server/internal/integrations/composio/state_test.gonew file mode 100644index 0000000000..cdbea774ea--- /dev/null+++ b/server/internal/integrations/composio/state_test.go@@ -0,0 +1,97 @@+package composio++import (+ "errors"+ "strings"+ "testing"+ "time"+)++var testSecret = []byte("test-state-secret-0123456789")++func TestSignVerifyState_RoundTrip(t *testing.T) {+ t.Parallel()+ now := time.Unix(1_700_000_000, 0)+ tok, err := signState(testSecret, stateClaims{+ UserID: "11111111-1111-1111-1111-111111111111",+ ToolkitSlug: "notion",+ AuthConfigID: "ac_notion",+ Exp: now.Add(5 * time.Minute).Unix(),+ })+ if err != nil {+ t.Fatalf("signState: %v", err)+ }+ got, err := verifyState(testSecret, tok, now)+ if err != nil {+ t.Fatalf("verifyState: %v", err)+ }+ if got.UserID != "11111111-1111-1111-1111-111111111111" {+ t.Errorf("user id = %q", got.UserID)+ }+ if got.ToolkitSlug != "notion" {+ t.Errorf("toolkit slug = %q", got.ToolkitSlug)+ }+ if got.AuthConfigID != "ac_notion" {+ t.Errorf("auth config id = %q", got.AuthConfigID)+ }+}++func TestVerifyState_Expired(t *testing.T) {+ t.Parallel()+ now := time.Unix(1_700_000_000, 0)+ tok, err := signState(testSecret, stateClaims{+ UserID: "u",+ ToolkitSlug: "notion",+ Exp: now.Add(-time.Second).Unix(),+ })+ if err != nil {+ t.Fatalf("signState: %v", err)+ }+ if _, err := verifyState(testSecret, tok, now); !errors.Is(err, ErrStateExpired) {+ t.Fatalf("expected ErrStateExpired, got %v", err)+ }+}++func TestVerifyState_Tampered(t *testing.T) {+ t.Parallel()+ now := time.Unix(1_700_000_000, 0)+ tok, err := signState(testSecret, stateClaims{UserID: "u", ToolkitSlug: "notion", Exp: now.Add(time.Minute).Unix()})+ if err != nil {+ t.Fatalf("signState: %v", err)+ }+ // Flip a byte in the payload segment.+ payload, sig, _ := strings.Cut(tok, ".")+ tampered := payload[:len(payload)-1] + flipLastChar(payload) + "." + sig+ if _, err := verifyState(testSecret, tampered, now); !errors.Is(err, ErrStateSignature) && !errors.Is(err, ErrStateMalformed) {+ t.Fatalf("expected signature/malformed error, got %v", err)+ }+}++func TestVerifyState_WrongSecret(t *testing.T) {+ t.Parallel()+ now := time.Unix(1_700_000_000, 0)+ tok, _ := signState(testSecret, stateClaims{UserID: "u", ToolkitSlug: "notion", Exp: now.Add(time.Minute).Unix()})+ if _, err := verifyState([]byte("a-different-secret"), tok, now); !errors.Is(err, ErrStateSignature) {+ t.Fatalf("expected ErrStateSignature, got %v", err)+ }+}++func TestVerifyState_Malformed(t *testing.T) {+ t.Parallel()+ now := time.Unix(1_700_000_000, 0)+ for _, tok := range []string{"", "nodot", ".", "a.", ".b"} {+ if _, err := verifyState(testSecret, tok, now); !errors.Is(err, ErrStateMalformed) {+ t.Errorf("token %q: expected ErrStateMalformed, got %v", tok, err)+ }+ }+}++// flipLastChar returns a single replacement char different from the payload's+// last character so the tampered payload is guaranteed to differ.+func flipLastChar(payload string) string {+ last := payload[len(payload)-1]+ if last == 'A' {+ return "B"+ }+ return "A"+}diff --git a/server/internal/runtimeapps/connected_app.go b/server/internal/runtimeapps/connected_app.gonew file mode 100644index 0000000000..ec9307e4ec--- /dev/null+++ b/server/internal/runtimeapps/connected_app.go@@ -0,0 +1,61 @@+package runtimeapps++import (+ "encoding/json"+ "strings"+)++// ConnectedApp is non-secret task-scoped metadata that tells the daemon which+// external app capabilities were actually mounted for a run.+type ConnectedApp struct {+ Provider string `json:"provider"`+ ServerName string `json:"server_name"`+ ToolkitSlug string `json:"toolkit_slug"`+ ToolkitName string `json:"toolkit_name,omitempty"`+}++// MCPOverlayResult carries both the secret-bearing MCP config overlay and the+// non-secret app list used to brief the agent.+type MCPOverlayResult struct {+ MCPOverlay json.RawMessage+ ConnectedApps []ConnectedApp+}++// DisplayNameForToolkitSlug returns a compact human-readable label without+// making a catalog call in the enqueue path. Brand casing here is intentionally+// best-effort; the slug remains the functional identifier in every brief.+func DisplayNameForToolkitSlug(slug string) string {+ slug = strings.TrimSpace(slug)+ if slug == "" {+ return ""+ }+ switch slug {+ case "github":+ return "GitHub"+ case "gmail":+ return "Gmail"+ case "linkedin":+ return "LinkedIn"+ }+ words := strings.FieldsFunc(slug, func(r rune) bool {+ return r == '_' || r == '-'+ })+ if len(words) == 0 {+ return slug+ }+ for i, word := range words {+ words[i] = titleASCII(word)+ }+ return strings.Join(words, " ")+}++func titleASCII(s string) string {+ if s == "" {+ return ""+ }+ b := []byte(strings.ToLower(s))+ if b[0] >= 'a' && b[0] <= 'z' {+ b[0] -= 'a' - 'A'+ }+ return string(b)+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex f2dbfcbecd..9d022a3c0f 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -402,10 +402,11 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi// MUL-2429); agent-assigned autopilots go through the standard issue// path. Both code paths land in agent_task_queue with agent_id = leader.if ap.AssigneeType == "squad" {- // Fail-closed private-leader gate: if the leader is private, verify- // the autopilot creator still has access. This catches illegitimate- // configs that were saved before the save-time gate was added.- if leader.Visibility == "private" && !s.canCreatorAccessPrivateLeader(ctx, ap, leader) {+ // Fail-closed invocation gate: verify the autopilot creator may still+ // invoke the leader under the permission model. Catches configs that+ // predate the save-time gate, and admin-created configs that no longer+ // pass (MUL-3963).+ if !s.canCreatorInvokeAgent(ctx, ap, leader) {return fmt.Errorf("autopilot creator cannot access private squad leader")}if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}); err != nil {@@ -549,8 +550,8 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,return &errDispatchSkipped{reason: formatAdmissionReason(ap, reason)}}- // Fail-closed private-leader gate for squad autopilots.- if ap.AssigneeType == "squad" && agent.Visibility == "private" && !s.canCreatorAccessPrivateLeader(ctx, ap, agent) {+ // Fail-closed invocation gate for squad autopilots.+ if ap.AssigneeType == "squad" && !s.canCreatorInvokeAgent(ctx, ap, agent) {return &errDispatchSkipped{reason: formatAdmissionReason(ap, "creator cannot access private squad leader")}}@@ -883,31 +884,14 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopilreturn formatAdmissionReason(ap, reason), true}}- // Private-agent gate at the autopilot layer. Caller identity = the- // autopilot's creator: if the creator no longer has access to the- // (now-private) target agent, the dispatch is recorded as `skipped`.- // Agent-created autopilots bypass the gate to preserve A2A- // collaboration. Errors loading the workspace member fail closed —- // without an authoritative role the gate cannot grant access.- //- // For squad autopilots the gate runs against the resolved leader.- // Leader visibility is the right thing to check — if the human creator- // can no longer reach the leader, the autopilot would silently fail- // even though the squad itself looks intact.- if agent.Visibility == "private" && ap.CreatedByType == "member" {- creatorID := util.UUIDToString(ap.CreatedByID)- if util.UUIDToString(agent.OwnerID) != creatorID {- member, err := s.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{- UserID: ap.CreatedByID,- WorkspaceID: ap.WorkspaceID,- })- if err != nil {- return "autopilot creator no longer in workspace", true- }- if member.Role != "owner" && member.Role != "admin" {- return "autopilot creator lacks access to private assignee agent", true- }- }+ // Invocation gate at the autopilot layer (MUL-3963). Effective user = the+ // autopilot's creator: if the creator may not invoke the target agent+ // under the permission model, the dispatch is recorded as `skipped`.+ // Admins do NOT bypass a private agent they do not own; agent-created+ // autopilots are judged as workspace principals. For squad autopilots the+ // gate runs against the resolved leader.+ if !s.canCreatorInvokeAgent(ctx, ap, agent) {+ return "autopilot creator lacks access to private assignee agent", true}return "", false}@@ -1389,24 +1373,52 @@ func (s *AutopilotService) getIssuePrefix(workspaceID pgtype.UUID) string {return ws.IssuePrefix}-// canCreatorAccessPrivateLeader checks whether the autopilot's creator still-// has access to a private leader agent. Mirrors handler.canAccessPrivateAgent-// logic: agent creators always pass; member creators must be the agent owner-// or a workspace owner/admin. Returns false (fail-closed) on any lookup error.-func (s *AutopilotService) canCreatorAccessPrivateLeader(ctx context.Context, ap db.Autopilot, leader db.Agent) bool {- if ap.CreatedByType == "agent" {- return true- }+// canCreatorInvokeAgent checks whether the autopilot's creator may invoke the+// target agent under the invocation-permission model (MUL-3963). It mirrors+// handler.canInvokeAgent with the autopilot creator as the effective user:+// - member creator who owns the agent -> always+// - private agent -> only the owner (NO admin bypass, NO agent-created bypass)+// - public_to agent -> workspace target admits any workspace-member creator+// (and agent-created autopilots as workspace principals); member target+// admits the matching creator; team targets are inert.+// Fail-closed on any lookup error.+func (s *AutopilotService) canCreatorInvokeAgent(ctx context.Context, ap db.Autopilot, agent db.Agent) bool {creatorID := util.UUIDToString(ap.CreatedByID)- if util.UUIDToString(leader.OwnerID) == creatorID {+ if ap.CreatedByType == "member" && util.UUIDToString(agent.OwnerID) == creatorID {return true}- member, err := s.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{- UserID: ap.CreatedByID,- WorkspaceID: ap.WorkspaceID,- })+ if agent.PermissionMode != "public_to" {+ // private (or unknown mode): deny-by-default; only the owner branch+ // above passes. Admins and agent-created autopilots do not bypass.+ return false+ }+ targets, err := s.Queries.ListAgentInvocationTargets(ctx, agent.ID)if err != nil {return false}- return member.Role == "owner" || member.Role == "admin"+ // Agent-created autopilots are workspace-internal principals: a workspace+ // target admits them. Member creators must be workspace members.+ workspaceBroad := ap.CreatedByType == "agent"+ isWorkspaceMember := false+ if ap.CreatedByType == "member" {+ if _, err := s.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{+ UserID: ap.CreatedByID,+ WorkspaceID: ap.WorkspaceID,+ }); err == nil {+ isWorkspaceMember = true+ }+ }+ for _, t := range targets {+ switch t.TargetType {+ case "workspace":+ if isWorkspaceMember || workspaceBroad {+ return true+ }+ case "member":+ if ap.CreatedByType == "member" && util.UUIDToString(t.TargetID) == creatorID {+ return true+ }+ }+ }+ return false}diff --git a/server/internal/service/resolve_originator_test.go b/server/internal/service/resolve_originator_test.gonew file mode 100644index 0000000000..4b2e052ce2--- /dev/null+++ b/server/internal/service/resolve_originator_test.go@@ -0,0 +1,444 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/internal/runtimeapps"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/featureflag"+)++// newResolveOriginatorPool mirrors the local-postgres pattern used in+// task_claim_race_test.go: skip when the test database is unreachable+// instead of failing, so `go test ./...` stays usable in CI / clean+// developer setups that don't run Postgres.+func newResolveOriginatorPool(t *testing.T) *pgxpool.Pool {+ t.Helper()+ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ t.Skipf("database unavailable: %v", err)+ }+ if err := pool.Ping(ctx); err != nil {+ pool.Close()+ t.Skipf("database unreachable: %v", err)+ }+ t.Cleanup(pool.Close)+ return pool+}++type stubOverlayBuilder struct {+ calls int+ lastUser pgtype.UUID+ lastAgent db.Agent+ resp json.RawMessage+ apps []runtimeapps.ConnectedApp+ err error+ respIsNil bool+}++func (s *stubOverlayBuilder) BuildTaskOverlay(_ context.Context, originatorUserID pgtype.UUID, agent db.Agent) (runtimeapps.MCPOverlayResult, error) {+ s.calls+++ s.lastUser = originatorUserID+ s.lastAgent = agent+ if s.err != nil {+ return runtimeapps.MCPOverlayResult{}, s.err+ }+ if s.respIsNil {+ return runtimeapps.MCPOverlayResult{}, nil+ }+ return runtimeapps.MCPOverlayResult{MCPOverlay: s.resp, ConnectedApps: s.apps}, nil+}++func composioMCPAppsTestFlags(enabled bool) *featureflag.Service {+ provider := featureflag.NewStaticProvider()+ provider.Set(featureflags.ComposioMCPApps, featureflag.Rule{Default: enabled})+ return featureflag.NewService(provider)+}++func TestBuildRuntimeMCPOverlaySkipsBuilderWhenComposioFlagDisabled(t *testing.T) {+ builder := &stubOverlayBuilder{+ resp: json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.example/session"}}}`),+ apps: []runtimeapps.ConnectedApp{{+ Provider: "composio",+ ServerName: "composio",+ ToolkitSlug: "notion",+ ToolkitName: "Notion",+ }},+ }+ svc := &TaskService{+ Composio: builder,+ FeatureFlags: composioMCPAppsTestFlags(false),+ }+ var userBytes [16]byte+ userBytes[15] = 1+ var agentBytes [16]byte+ agentBytes[15] = 2+ got := svc.buildRuntimeMCPOverlay(context.Background(), pgtype.UUID{Bytes: userBytes, Valid: true}, db.Agent{+ ID: pgtype.UUID{Bytes: agentBytes, Valid: true},+ })+ if builder.calls != 0 {+ t.Fatalf("BuildTaskOverlay calls = %d, want 0", builder.calls)+ }+ if len(got.Overlay) != 0 || len(got.ConnectedApps) != 0 {+ t.Fatalf("flag-off overlay = %+v; want empty", got)+ }+}++// seedOriginatorFanout builds the minimal fixture for an agent→agent+// fanout chain:+//+// human U → (member-authored comment on issue I) →+// agent A handles task T_A with originator_user_id = U →+// agent A posts a reply comment C (author_type=agent, source_task_id=T_A) →+// agent B picks up C as its trigger+//+// Returns: member-authored comment id (C0), agent-authored comment id (C1, with+// source_task_id=T_A), T_A's task id, and U as pgtype.UUID. T_A's+// originator_user_id is U so the fanout / quick-create branches can prove the+// inheritance.+func seedOriginatorFanout(t *testing.T, pool *pgxpool.Pool) (memberCommentID, agentCommentID, taskAID, userID pgtype.UUID) {+ t.Helper()+ ctx := context.Background()++ var workspaceID, agentAID, agentBID, runtimeID, issueID, taskAIDStr, userIDStr, commentMemberID, commentAgentID string++ if err := pool.QueryRow(ctx, `+ INSERT INTO "user" (name, email)+ VALUES ('Resolve Originator User', '[email protected]')+ RETURNING id+ `).Scan(&userIDStr); err != nil {+ t.Fatalf("seed user: %v", err)+ }+ t.Cleanup(func() {+ pool.Exec(context.Background(),+ `DELETE FROM "user" WHERE email = '[email protected]'`)+ })++ if err := pool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug)+ VALUES ('resolve-orig-ws', 'resolve-orig-ws-' || gen_random_uuid())+ RETURNING id+ `).Scan(&workspaceID); err != nil {+ t.Fatalf("seed workspace: %v", err)+ }+ t.Cleanup(func() {+ pool.Exec(context.Background(),+ `DELETE FROM workspace WHERE id = $1`, workspaceID)+ })++ if _, err := pool.Exec(ctx, `+ INSERT INTO member (workspace_id, user_id, role)+ VALUES ($1, $2, 'owner')+ `, workspaceID, userIDStr); err != nil {+ t.Fatalf("seed member: %v", err)+ }++ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id+ ) VALUES ($1, 'r', 'cloud', 'codex', 'online', '', '{}'::jsonb, $2)+ RETURNING id+ `, workspaceID, userIDStr).Scan(&runtimeID); err != nil {+ t.Fatalf("seed runtime: %v", err)+ }++ if err := pool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id,+ instructions, custom_env, custom_args+ )+ VALUES ($1, 'agent-A', 'cloud', '{}'::jsonb,+ $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb)+ RETURNING id+ `, workspaceID, runtimeID, userIDStr).Scan(&agentAID); err != nil {+ t.Fatalf("seed agent A: %v", err)+ }++ if err := pool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id,+ instructions, custom_env, custom_args+ )+ VALUES ($1, 'agent-B', 'cloud', '{}'::jsonb,+ $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb)+ RETURNING id+ `, workspaceID, runtimeID, userIDStr).Scan(&agentBID); err != nil {+ t.Fatalf("seed agent B: %v", err)+ }++ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, creator_type, creator_id)+ VALUES ($1, 'fanout-issue', 'member', $2)+ RETURNING id+ `, workspaceID, userIDStr).Scan(&issueID); err != nil {+ t.Fatalf("seed issue: %v", err)+ }++ // Agent A's task carries the originator (the human U). This is the+ // row the resolver must follow back through comment.source_task_id.+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, originator_user_id+ )+ VALUES ($1, $2, $3, 'completed', 0, $4)+ RETURNING id+ `, agentAID, runtimeID, issueID, userIDStr).Scan(&taskAIDStr); err != nil {+ t.Fatalf("seed task A: %v", err)+ }++ // Member-authored comment (no source_task_id).+ if err := pool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'human comment')+ RETURNING id+ `, issueID, workspaceID, userIDStr).Scan(&commentMemberID); err != nil {+ t.Fatalf("seed member comment: %v", err)+ }++ // Agent-authored comment whose source_task_id points at task A.+ // resolveOriginatorFromTriggerComment must inherit task A's originator.+ if err := pool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, source_task_id)+ VALUES ($1, $2, 'agent', $3, 'agent comment', $4)+ RETURNING id+ `, issueID, workspaceID, agentAID, taskAIDStr).Scan(&commentAgentID); err != nil {+ t.Fatalf("seed agent comment: %v", err)+ }++ memberCommentID = util.MustParseUUID(commentMemberID)+ agentCommentID = util.MustParseUUID(commentAgentID)+ taskAID = util.MustParseUUID(taskAIDStr)+ userID = util.MustParseUUID(userIDStr)+ return+}++// TestResolveOriginatorFromTriggerComment_MemberAuthored — the base case:+// a comment authored by a workspace member IS the top-of-chain. The+// originator is the comment's own author_id.+func TestResolveOriginatorFromTriggerComment_MemberAuthored(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ memberCommentID, _, _, userID := seedOriginatorFanout(t, pool)+ svc := &TaskService{Queries: db.New(pool)}++ got := svc.resolveOriginatorFromTriggerComment(context.Background(), memberCommentID)+ if !got.Valid {+ t.Fatalf("expected valid originator for member-authored comment, got invalid")+ }+ if got.Bytes != userID.Bytes {+ t.Errorf("originator = %s, want %s", util.UUIDToString(got), util.UUIDToString(userID))+ }+}++// TestResolveOriginatorFromTriggerComment_AgentAuthoredInheritsFromParent+// — the load-bearing fanout case. Agent A finished a task it ran on+// behalf of human U; A then posts a comment that triggers agent B. The+// trigger comment's author is A (not a human), but resolving the+// originator must walk comment.source_task_id → parent task →+// parent.originator_user_id, yielding U.+func TestResolveOriginatorFromTriggerComment_AgentAuthoredInheritsFromParent(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ _, agentCommentID, _, userID := seedOriginatorFanout(t, pool)+ svc := &TaskService{Queries: db.New(pool)}++ got := svc.resolveOriginatorFromTriggerComment(context.Background(), agentCommentID)+ if !got.Valid {+ t.Fatalf("expected valid originator inherited from parent task, got invalid")+ }+ if got.Bytes != userID.Bytes {+ t.Errorf("originator = %s, want %s (parent task's originator_user_id)",+ util.UUIDToString(got), util.UUIDToString(userID))+ }+}++// TestResolveOriginatorForIssueTask_MemberCreatedNoComment covers direct issue+// assignment/creation: there is no trigger comment to inspect, but the issue's+// human creator is still the run originator for Composio overlay gating.+func TestResolveOriginatorForIssueTask_MemberCreatedNoComment(t *testing.T) {+ userID := util.MustParseUUID("11111111-1111-1111-1111-111111111111")+ svc := &TaskService{}+ issue := db.Issue{CreatorType: "member", CreatorID: userID}++ got := svc.resolveOriginatorForIssueTask(context.Background(), issue, pgtype.UUID{})+ if !got.Valid {+ t.Fatalf("expected valid originator for member-created issue, got invalid")+ }+ if got.Bytes != userID.Bytes {+ t.Errorf("originator = %s, want %s", util.UUIDToString(got), util.UUIDToString(userID))+ }+}++// TestResolveOriginatorForIssueTask_QuickCreateIssueInheritsParentTask covers+// agent-created issues that have an explicit quick-create origin stamp. The+// issue creator is the agent, but the top-of-chain human is stored on the+// parent quick-create task and must be inherited for downstream dispatch.+func TestResolveOriginatorForIssueTask_QuickCreateIssueInheritsParentTask(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ _, _, parentTaskID, userID := seedOriginatorFanout(t, pool)+ svc := &TaskService{Queries: db.New(pool)}+ issue := db.Issue{+ CreatorType: "agent",+ OriginType: pgtype.Text{String: "quick_create", Valid: true},+ OriginID: parentTaskID,+ }++ got := svc.resolveOriginatorForIssueTask(context.Background(), issue, pgtype.UUID{})+ if !got.Valid {+ t.Fatalf("expected quick-create issue to inherit originator, got invalid")+ }+ if got.Bytes != userID.Bytes {+ t.Errorf("originator = %s, want %s", util.UUIDToString(got), util.UUIDToString(userID))+ }+}++// TestEnqueueTaskForIssueStoresRuntimeMCPOverlayInQueuedRow guards the race+// where the daemon could poll-claim a newly inserted queued task while the old+// post-insert overlay updater was still making the outbound Composio session+// call. The overlay must be computed before INSERT and returned on the queued+// row.+func TestEnqueueTaskForIssueStoresRuntimeMCPOverlayInQueuedRow(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ suffix := time.Now().UnixNano()+ email := fmt.Sprintf("runtime-overlay-insert-%[email protected]", suffix)+ workspaceSlug := fmt.Sprintf("runtime-overlay-insert-%d", suffix)++ var userIDStr, workspaceIDStr, runtimeIDStr, agentIDStr, issueIDStr string+ if err := pool.QueryRow(ctx, `+ INSERT INTO "user" (name, email)+ VALUES ('Runtime Overlay Insert User', $1)+ RETURNING id+ `, email).Scan(&userIDStr); err != nil {+ t.Fatalf("seed user: %v", err)+ }+ t.Cleanup(func() {+ pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userIDStr)+ })+ if err := pool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug)+ VALUES ('runtime overlay insert ws', $1)+ RETURNING id+ `, workspaceSlug).Scan(&workspaceIDStr); err != nil {+ t.Fatalf("seed workspace: %v", err)+ }+ t.Cleanup(func() {+ pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceIDStr)+ })+ if _, err := pool.Exec(ctx, `+ INSERT INTO member (workspace_id, user_id, role)+ VALUES ($1, $2, 'owner')+ `, workspaceIDStr, userIDStr); err != nil {+ t.Fatalf("seed member: %v", err)+ }+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id+ ) VALUES ($1, 'runtime-overlay-r', 'cloud', 'codex', 'online', '', '{}'::jsonb, $2)+ RETURNING id+ `, workspaceIDStr, userIDStr).Scan(&runtimeIDStr); err != nil {+ t.Fatalf("seed runtime: %v", err)+ }+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id,+ instructions, custom_env, custom_args, composio_toolkit_allowlist+ )+ VALUES ($1, 'runtime-overlay-agent', 'cloud', '{}'::jsonb,+ $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb, ARRAY['notion'])+ RETURNING id+ `, workspaceIDStr, runtimeIDStr, userIDStr).Scan(&agentIDStr); err != nil {+ t.Fatalf("seed agent: %v", err)+ }+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority+ )+ VALUES ($1, 'runtime overlay issue', 'member', $2, 'agent', $3, 'medium')+ RETURNING id+ `, workspaceIDStr, userIDStr, agentIDStr).Scan(&issueIDStr); err != nil {+ t.Fatalf("seed issue: %v", err)+ }++ overlay := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.example/session"}}}`)+ builder := &stubOverlayBuilder{+ resp: overlay,+ apps: []runtimeapps.ConnectedApp{{+ Provider: "composio",+ ServerName: "composio",+ ToolkitSlug: "notion",+ ToolkitName: "Notion",+ }},+ }+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New(), Composio: builder, FeatureFlags: composioMCPAppsTestFlags(true)}+ userID := util.MustParseUUID(userIDStr)+ task, err := svc.EnqueueTaskForIssue(ctx, db.Issue{+ ID: util.MustParseUUID(issueIDStr),+ AssigneeID: util.MustParseUUID(agentIDStr),+ Priority: "medium",+ CreatorType: "member",+ CreatorID: userID,+ WorkspaceID: util.MustParseUUID(workspaceIDStr),+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ })+ if err != nil {+ t.Fatalf("EnqueueTaskForIssue: %v", err)+ }+ if builder.calls != 1 {+ t.Fatalf("BuildTaskOverlay calls = %d, want 1", builder.calls)+ }+ if len(task.RuntimeMcpOverlay) == 0 {+ t.Fatalf("returned queued task has empty runtime_mcp_overlay")+ }+ if len(task.RuntimeConnectedApps) == 0 {+ t.Fatalf("returned queued task has empty runtime_connected_apps")+ }+ var storedOverlay []byte+ var storedApps []byte+ if err := pool.QueryRow(ctx, `SELECT runtime_mcp_overlay, runtime_connected_apps FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&storedOverlay, &storedApps); err != nil {+ t.Fatalf("read stored overlay: %v", err)+ }+ if len(storedOverlay) == 0 {+ t.Fatal("stored queued task has empty runtime_mcp_overlay")+ }+ if len(storedApps) == 0 {+ t.Fatal("stored queued task has empty runtime_connected_apps")+ }+ var apps []runtimeapps.ConnectedApp+ if err := json.Unmarshal(storedApps, &apps); err != nil {+ t.Fatalf("unmarshal stored connected apps: %v", err)+ }+ if len(apps) != 1 || apps[0].ToolkitSlug != "notion" {+ t.Fatalf("stored connected apps = %+v; want notion", apps)+ }+}++// TestResolveOriginatorFromTriggerComment_InvalidCommentID — defensive+// branch. An invalid pgtype.UUID must short-circuit before any DB query+// and return invalid.+func TestResolveOriginatorFromTriggerComment_InvalidCommentID(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ svc := &TaskService{Queries: db.New(pool)}+ got := svc.resolveOriginatorFromTriggerComment(context.Background(), pgtype.UUID{})+ if got.Valid {+ t.Errorf("invalid comment id must yield invalid originator, got %s", util.UUIDToString(got))+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 884b1e931e..a7b7c440b9 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -15,10 +15,13 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/featureflags"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/runtimeapps""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/featureflag""github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/redact""github.com/multica-ai/multica/server/pkg/skillbundle"@@ -33,18 +36,50 @@ type TaskService struct {Analytics analytics.ClientMetrics *obsmetrics.BusinessMetricsWakeup TaskWakeupNotifier+ // FeatureFlags is the server-side toggle router. Nil is valid and returns+ // each call site's default.+ FeatureFlags *featureflag.Service// EmptyClaim caches "this runtime has no queued task" so the daemon// poll path can skip a Postgres scan on the steady-state empty case.// Optional — a nil cache disables the fast path and every claim// goes through the DB. Wired in router.go from the shared Redis// client.EmptyClaim *EmptyClaimCache+ // Composio computes the per-task MCP overlay (Stage 3 of the Composio+ // epic, MUL-3721) — the integration's "current user's connected apps+ // → MCP session URL" hook called from each Enqueue* path. Optional: a+ // nil ComposioOverlayBuilder turns the overlay step into a no-op so+ // every Multica deployment that hasn't enabled Composio behaves+ // exactly as before. Wired in router.go after composiointeg.NewService+ // succeeds; the concrete type is *composio.Service.+ Composio ComposioOverlayBuilderanalyticsContextMu sync.MutexanalyticsContextCache map[string]analytics.TaskContextanalyticsContextOrder []string}+// ComposioOverlayBuilder is the seam TaskService uses to build the per-task+// MCP overlay at enqueue time. Implemented by+// internal/integrations/composio.Service.BuildTaskOverlay; tests provide an+// inline fake so they don't have to spin a fake Composio SDK.+//+// Contract: a zero MCPOverlayResult means "no overlay for this run" — covers+// all gates the implementation enforces (no owner / empty allowlist / empty+// intersection with active connections / empty session URL). Any non-empty+// MCPOverlay is the exact value to store in agent_task_queue.runtime_mcp_overlay;+// ConnectedApps is non-secret metadata to store alongside it for daemon brief+// injection. A non-nil error is surfaced to the caller but treated as+// best-effort — failed overlay computation must not fail the enqueue.+//+// agent is passed by value so the builder can inspect OwnerID and+// ComposioToolkitAllowlist without re-querying the DB; every enqueue path+// already loaded the agent for runtime/archive checks, so passing it is+// free and avoids a second GetAgent round-trip in the hot path.+type ComposioOverlayBuilder interface {+ BuildTaskOverlay(ctx context.Context, originatorUserID pgtype.UUID, agent db.Agent) (runtimeapps.MCPOverlayResult, error)+}+type TaskWakeupNotifier interface {NotifyTaskAvailable(runtimeID, taskID string)}@@ -144,6 +179,130 @@ func (s *TaskService) captureTaskQueued(ctx context.Context, task db.AgentTaskQu}}+type runtimeMCPOverlayData struct {+ Overlay json.RawMessage+ ConnectedApps json.RawMessage+}++// buildRuntimeMCPOverlay computes the optional per-task Composio MCP overlay.+// Enqueue paths call this BEFORE inserting the queued row so the daemon cannot+// claim a task during the network round-trip to Composio and miss the overlay.+func (s *TaskService) buildRuntimeMCPOverlay(ctx context.Context, originatorUserID pgtype.UUID, agent db.Agent) runtimeMCPOverlayData {+ if s == nil || s.Composio == nil {+ return runtimeMCPOverlayData{}+ }+ if !featureflags.ComposioMCPAppsEnabled(ctx, s.FeatureFlags) {+ return runtimeMCPOverlayData{}+ }+ result, err := s.Composio.BuildTaskOverlay(ctx, originatorUserID, agent)+ if err != nil {+ slog.Warn("runtime mcp overlay: BuildTaskOverlay failed; task will run without composio overlay",+ "originator_user_id", util.UUIDToString(originatorUserID),+ "agent_id", util.UUIDToString(agent.ID),+ "error", err,+ )+ return runtimeMCPOverlayData{}+ }+ if len(result.MCPOverlay) == 0 {+ slog.Debug("runtime mcp overlay: no composio overlay for task",+ "originator_user_id", util.UUIDToString(originatorUserID),+ "agent_id", util.UUIDToString(agent.ID),+ )+ return runtimeMCPOverlayData{}+ }+ data := runtimeMCPOverlayData{Overlay: result.MCPOverlay}+ if len(result.ConnectedApps) > 0 {+ raw, err := json.Marshal(result.ConnectedApps)+ if err != nil {+ slog.Warn("runtime mcp overlay: marshal connected app metadata failed",+ "originator_user_id", util.UUIDToString(originatorUserID),+ "agent_id", util.UUIDToString(agent.ID),+ "error", err,+ )+ return data+ }+ data.ConnectedApps = raw+ }+ return data+}++// resolveOriginatorFromTriggerComment returns the top-of-chain HUMAN user+// id for a comment that triggered an Enqueue* path. The chain rules+// (MUL-3869):+//+// - trigger comment authored by a member → originator = author_id (that+// member IS the top-of-chain human).+// - trigger comment authored by an agent → read the parent task via+// comment.source_task_id and inherit its originator_user_id. This is+// the load-bearing case for agent fan-out: agent A @-mentions agent B,+// comment author is A, but we MUST surface the human who originally+// told A to run, not lose the originator at the first agent hop.+// - missing comment / unknown source task / NULL parent originator →+// invalid pgtype.UUID. BuildTaskOverlay treats that as "no overlay"+// (gate 1).+//+// A nil receiver / nil Queries falls through to invalid so unit-test+// setups that don't wire a DB stay safe.+func (s *TaskService) resolveOriginatorFromTriggerComment(ctx context.Context, commentID pgtype.UUID) pgtype.UUID {+ if s == nil || s.Queries == nil {+ return pgtype.UUID{}+ }+ if !commentID.Valid {+ return pgtype.UUID{}+ }+ comment, err := s.Queries.GetComment(ctx, commentID)+ if err != nil {+ return pgtype.UUID{}+ }+ switch comment.AuthorType {+ case "member":+ return comment.AuthorID+ case "agent":+ // Inherit from the agent's own triggering task. comment.source_task_id+ // is set by every agent comment-write path (see migration 120), so a+ // NULL here means either the comment predates that migration or it+ // was authored out-of-band — both fall through to "no overlay".+ if !comment.SourceTaskID.Valid {+ return pgtype.UUID{}+ }+ parent, err := s.Queries.GetAgentTask(ctx, comment.SourceTaskID)+ if err != nil {+ return pgtype.UUID{}+ }+ return parent.OriginatorUserID+ default:+ return pgtype.UUID{}+ }+}++// resolveOriginatorForIssueTask returns the top-of-chain human for issue-backed+// dispatches. Comment-triggered runs keep the existing comment-chain semantics;+// direct issue assignment/creation falls back to the issue's member creator.+// Agent-created quick-create issues have an explicit origin link back to the+// quick-create task, so they can inherit that task's originator safely. Other+// agent/system origins, including autopilot, deliberately remain unattributed.+func (s *TaskService) resolveOriginatorForIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID) pgtype.UUID {+ if triggerCommentID.Valid {+ return s.resolveOriginatorFromTriggerComment(ctx, triggerCommentID)+ }+ if issue.CreatorType == "member" && issue.CreatorID.Valid {+ return issue.CreatorID+ }+ if s == nil || s.Queries == nil || !issue.OriginType.Valid || !issue.OriginID.Valid {+ return pgtype.UUID{}+ }+ switch issue.OriginType.String {+ case "quick_create":+ task, err := s.Queries.GetAgentTask(ctx, issue.OriginID)+ if err != nil {+ return pgtype.UUID{}+ }+ return task.OriginatorUserID+ default:+ return pgtype.UUID{}+ }+}+func (s *TaskService) captureTaskDispatched(ctx context.Context, task db.AgentTaskQueue) {if s.Metrics != nil {source, runtimeMode, _ := s.taskMetricsContext(ctx, task)@@ -513,15 +672,20 @@ func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, trigreturn db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")}+ originatorUserID := s.resolveOriginatorForIssueTask(ctx, issue, triggerCommentID)+ runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{- AgentID: issue.AssigneeID,- RuntimeID: agent.RuntimeID,- IssueID: issue.ID,- Priority: priorityToInt(issue.Priority),- TriggerCommentID: triggerCommentID,- TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),- ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},- HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},+ AgentID: issue.AssigneeID,+ RuntimeID: agent.RuntimeID,+ IssueID: issue.ID,+ Priority: priorityToInt(issue.Priority),+ TriggerCommentID: triggerCommentID,+ TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),+ ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},+ HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},+ OriginatorUserID: originatorUserID,+ RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,+ RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,// Stamp the reviewed head so dedup can distinguish this run's target// from a later request against a new HEAD (TEN-356).HeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, issue.ID)),@@ -598,17 +762,22 @@ func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agreturn db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")}+ originatorUserID := s.resolveOriginatorForIssueTask(ctx, issue, triggerCommentID)+ runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{- AgentID: agentID,- RuntimeID: agent.RuntimeID,- IssueID: issue.ID,- Priority: priorityToInt(issue.Priority),- TriggerCommentID: triggerCommentID,- TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),- IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},- ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},- HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},- SquadID: squadID,+ AgentID: agentID,+ RuntimeID: agent.RuntimeID,+ IssueID: issue.ID,+ Priority: priorityToInt(issue.Priority),+ TriggerCommentID: triggerCommentID,+ TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),+ IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},+ ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},+ HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},+ SquadID: squadID,+ OriginatorUserID: originatorUserID,+ RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,+ RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,// Stamp the reviewed head so dedup can distinguish this run's target// from a later request against a new HEAD (TEN-356).HeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, issue.ID)),@@ -764,11 +933,15 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, rreturn db.AgentTaskQueue{}, fmt.Errorf("marshal quick-create context: %w", err)}+ runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, requesterID, agent)task, err := s.Queries.CreateQuickCreateTask(ctx, db.CreateQuickCreateTaskParams{- AgentID: agentID,- RuntimeID: agent.RuntimeID,- Priority: priorityToInt("high"),- Context: contextJSON,+ AgentID: agentID,+ RuntimeID: agent.RuntimeID,+ Priority: priorityToInt("high"),+ Context: contextJSON,+ OriginatorUserID: requesterID,+ RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,+ RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,})if err != nil {return db.AgentTaskQueue{}, fmt.Errorf("create quick-create task: %w", err)@@ -846,16 +1019,20 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSereturn db.AgentTaskQueue{}, ErrChatTaskAgentNoRuntime}+ runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, initiatorUserID, agent)task, err := s.Queries.CreateChatTask(ctx, db.CreateChatTaskParams{- AgentID: chatSession.AgentID,- RuntimeID: agent.RuntimeID,- Priority: 2, // medium priority for chat- ChatSessionID: chatSession.ID,- InitiatorUserID: initiatorUserID,+ AgentID: chatSession.AgentID,+ RuntimeID: agent.RuntimeID,+ Priority: 2, // medium priority for chat+ ChatSessionID: chatSession.ID,+ InitiatorUserID: initiatorUserID,+ OriginatorUserID: initiatorUserID,ForceFreshSession: pgtype.Bool{Bool: forceFreshSession,Valid: true,},+ RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,+ RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,})if err != nil {slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)@@ -1786,7 +1963,25 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentTreturn nil, nil}- child, err := s.Queries.CreateRetryTask(ctx, parent.ID)+ var runtimeMCPOverlay runtimeMCPOverlayData+ agent, agentErr := s.Queries.GetAgent(ctx, parent.AgentID)+ if agentErr != nil {+ // Best-effort: failing to resolve the agent for the overlay is not+ // retry-fatal. Log and continue — the daemon will reject the claim+ // later if the agent is genuinely gone.+ slog.Warn("task auto-retry: load agent for overlay failed",+ "parent_task_id", util.UUIDToString(parent.ID),+ "agent_id", util.UUIDToString(parent.AgentID),+ "error", agentErr,+ )+ } else {+ runtimeMCPOverlay = s.buildRuntimeMCPOverlay(ctx, parent.OriginatorUserID, agent)+ }+ child, err := s.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{+ ID: parent.ID,+ RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,+ RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,+ })if err != nil {slog.Warn("task auto-retry failed","parent_task_id", util.UUIDToString(parent.ID),@@ -1805,6 +2000,7 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT// Retry creates a fresh queued row, same status transition (∅ → queued)// as EnqueueTaskFor*. Broadcast queued first, then notify the daemon —// see EnqueueTaskForIssue for ordering rationale.+ //s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, child)s.NotifyTaskEnqueued(ctx, child)return &child, nildiff --git a/server/migrations/127_user_composio_connection.down.sql b/server/migrations/127_user_composio_connection.down.sqlnew file mode 100644index 0000000000..ff0819f308--- /dev/null+++ b/server/migrations/127_user_composio_connection.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS user_composio_connection;diff --git a/server/migrations/127_user_composio_connection.up.sql b/server/migrations/127_user_composio_connection.up.sqlnew file mode 100644index 0000000000..51193a5a3a--- /dev/null+++ b/server/migrations/127_user_composio_connection.up.sql@@ -0,0 +1,38 @@+-- Composio integration (Stage 2 MVP): one row per user-connected Composio+-- account. The row is the local mirror of a Composio "connected account" so the+-- product can list / disconnect connections and build per-user MCP sessions+-- without round-tripping Composio on every read.+--+-- No foreign keys / cascades by design: Multica enforces cross-table+-- relationships at the application layer (see migration 118 dropping the+-- agent_task_queue.initiator_user_id FK). user_id is a "user".id but is left+-- unconstrained here so a user delete does not require a migration-ordered+-- cascade across integration tables.+--+-- composio_user_id always equals the Multica user_id.String() — the+-- application keeps that mapping as an invariant so a Composio session can be+-- created from the Multica user id alone. It is stored explicitly so a future+-- change to the mapping does not silently break already-connected accounts.+CREATE TABLE user_composio_connection (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL,+ toolkit_slug TEXT NOT NULL,+ auth_config_id TEXT NOT NULL,+ connected_account_id TEXT NOT NULL,+ composio_user_id TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'active',+ connected_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_used_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (user_id, connected_account_id)+);++-- The hot read path is "active connections for this user" (list endpoint and+-- MCP session builder both filter on user_id + status).+CREATE INDEX user_composio_connection_user_status_idx+ ON user_composio_connection(user_id, status);++-- Webhook / callback paths look a row up by its Composio connected_account_id.+CREATE INDEX user_composio_connection_account_idx+ ON user_composio_connection(connected_account_id);diff --git a/server/migrations/128_agent_task_queue_runtime_mcp_overlay.down.sql b/server/migrations/128_agent_task_queue_runtime_mcp_overlay.down.sqlnew file mode 100644index 0000000000..f3aa0193b4--- /dev/null+++ b/server/migrations/128_agent_task_queue_runtime_mcp_overlay.down.sql@@ -0,0 +1,3 @@+DROP TRIGGER IF EXISTS trg_clear_runtime_mcp_overlay ON agent_task_queue;+DROP FUNCTION IF EXISTS clear_runtime_mcp_overlay_on_terminal_state();+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS runtime_mcp_overlay;diff --git a/server/migrations/128_agent_task_queue_runtime_mcp_overlay.up.sql b/server/migrations/128_agent_task_queue_runtime_mcp_overlay.up.sqlnew file mode 100644index 0000000000..2951a3a43b--- /dev/null+++ b/server/migrations/128_agent_task_queue_runtime_mcp_overlay.up.sql@@ -0,0 +1,53 @@+-- Per-task MCP overlay computed at task enqueue (dispatch) time, layered on+-- top of agent.mcp_config when the daemon prepares the execution environment.+--+-- Stage 3 of the Composio epic (MUL-3721 / MUL-3715): the Composio integration+-- writes a fresh `{"mcpServers": {"composio": {"type": "http", "url": "...",+-- "headers": {"Authorization": "Bearer ..."}}}}` here for every task whose+-- initiator user has at least one active connection. The daemon claim+-- handler merges this on top of agent.mcp_config (overlay wins on name+-- collisions because it carries the live, user-scoped MCP session URL).+--+-- The value is short-lived: it carries a bearer token that becomes useless+-- once the task ends, so we wipe it on every terminal state transition via+-- the trigger below. Worst case a still-active task row keeps the token for+-- the duration of the run, mode-0600 in DB and never logged.+ALTER TABLE agent_task_queue+ ADD COLUMN runtime_mcp_overlay JSONB NULL;++COMMENT ON COLUMN agent_task_queue.runtime_mcp_overlay IS+ 'Per-task MCP servers computed at dispatch time, merged on top of agent.mcp_config. Currently used by Composio integration to inject the initiator user''s session URL. Cleared after task completes via trg_clear_runtime_mcp_overlay.';++-- Auto-clear the overlay the moment the task enters any terminal state, so+-- the row in the queue never keeps a stale bearer beyond the live run. This+-- is a defense-in-depth measure on top of how short the Composio session+-- token already is — clearing here means a future audit of the table never+-- finds bearers attached to rows that finished hours/days ago.+--+-- Trigger-based rather than per-query SET clauses because the terminal+-- transitions live in ~12 different sqlc queries (CompleteAgentTask,+-- FailAgentTask, FailStaleTasks, ExpireStaleQueuedTasks, FailTasksFor+-- OfflineRuntimes, RecoverOrphanedTasksForRuntime, plus six Cancel*+-- variants); a trigger is a single source of truth that future queries+-- can't bypass.+CREATE OR REPLACE FUNCTION clear_runtime_mcp_overlay_on_terminal_state()+RETURNS TRIGGER AS $$+BEGIN+ -- Only act on actual transitions INTO a terminal state from a non-terminal+ -- one, and only when there is something to wipe. Re-touching an already-+ -- terminal row (or a row whose overlay is already NULL) leaves the+ -- column unchanged and the trigger is a cheap no-op.+ IF NEW.status IN ('completed', 'failed', 'cancelled')+ AND OLD.status IS DISTINCT FROM NEW.status+ AND NEW.runtime_mcp_overlay IS NOT NULL THEN+ NEW.runtime_mcp_overlay := NULL;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS trg_clear_runtime_mcp_overlay ON agent_task_queue;+CREATE TRIGGER trg_clear_runtime_mcp_overlay+ BEFORE UPDATE OF status ON agent_task_queue+ FOR EACH ROW+ EXECUTE FUNCTION clear_runtime_mcp_overlay_on_terminal_state();diff --git a/server/migrations/129_agent_composio_allowlist_and_task_originator.down.sql b/server/migrations/129_agent_composio_allowlist_and_task_originator.down.sqlnew file mode 100644index 0000000000..febe836424--- /dev/null+++ b/server/migrations/129_agent_composio_allowlist_and_task_originator.down.sql@@ -0,0 +1,3 @@+DROP INDEX IF EXISTS agent_task_queue_originator_user_id_idx;+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS originator_user_id;+ALTER TABLE agent DROP COLUMN IF EXISTS composio_toolkit_allowlist;diff --git a/server/migrations/129_agent_composio_allowlist_and_task_originator.up.sql b/server/migrations/129_agent_composio_allowlist_and_task_originator.up.sqlnew file mode 100644index 0000000000..358557fde3--- /dev/null+++ b/server/migrations/129_agent_composio_allowlist_and_task_originator.up.sql@@ -0,0 +1,52 @@+-- Stage 3.1 of the Composio epic (MUL-3869, parent MUL-3721): turn the default+-- behaviour from "all-on" into "Composio MCP is only mounted when (a) the+-- agent's owner has explicitly allowlisted toolkits AND (b) the run originator+-- at the top of the trigger chain is that same owner".+--+-- Two columns ship together because the dispatch decision needs both:+-- * agent.composio_toolkit_allowlist — which toolkits the agent is allowed+-- to surface; NULL or [] = no MCP overlay regardless of who triggers.+-- * agent_task_queue.originator_user_id — the top-of-chain human originator+-- for THIS task, inherited across agent @-mention fanout. The dispatch+-- hook gates on (originator == agent.owner_id) so an agent never gets+-- another user's Composio session even if that other user @-mentions it.++-- ----------------------------------------------------------------------------+-- agent.composio_toolkit_allowlist+-- ----------------------------------------------------------------------------+ALTER TABLE agent+ ADD COLUMN composio_toolkit_allowlist TEXT[] NULL;++COMMENT ON COLUMN agent.composio_toolkit_allowlist IS+ 'Composio toolkit slugs this agent is allowed to mount as MCP. NULL or empty array = no MCP. Only effective when the run originator matches agent.owner_id; see migration 129 + MUL-3869 / MUL-3721. Stored as TEXT[] so the dispatch path can intersect against the originator''s active connections with a single SQL ANY() filter, no JSON parse on the hot path.';++-- ----------------------------------------------------------------------------+-- agent_task_queue.originator_user_id+-- ----------------------------------------------------------------------------+--+-- Distinct from initiator_user_id (migration 117): initiator is whoever+-- physically sent the triggering message — which for an agent fan-out is+-- ANOTHER AGENT, not a human — and is set today only for chat tasks. The+-- Composio overlay decision needs the HUMAN at the top of the chain so we+-- never inadvertently project a human's connected apps into a run that+-- person did not start. Hence a dedicated column whose contract is "the+-- originator is always a 'user' row (or NULL when none can be attributed,+-- e.g. autopilot/system runs)".+--+-- No FK to "user" by design (matches initiator_user_id and the+-- comment.source_task_id pattern): foreign keys on hot-path queue tables+-- have lock implications on busy production deploys, and the column only+-- feeds best-effort overlay decisions — a stale id simply degrades to "no+-- overlay", never a corrupt run.+ALTER TABLE agent_task_queue+ ADD COLUMN originator_user_id UUID NULL;++COMMENT ON COLUMN agent_task_queue.originator_user_id IS+ 'Top-of-chain human originator for this run. For human-triggered tasks (comment by a member, chat, quick-create) equals that member. For agent-fanout tasks (agent A @-mentions agent B) inherited from the parent task''s originator_user_id via comment.source_task_id. NULL when no human is in the chain (autopilot, system-driven). Used by the Composio MCP overlay dispatch to require originator == agent.owner_id; see migration 129 + MUL-3869.';++-- Dispatch reads originator_user_id for every overlay decision; a partial+-- index on the non-NULL subset keeps the working set small (autopilot and+-- pre-stage-3.1 rows stay out of the index entirely).+CREATE INDEX agent_task_queue_originator_user_id_idx+ ON agent_task_queue(originator_user_id)+ WHERE originator_user_id IS NOT NULL;diff --git a/server/migrations/130_agent_invocation_permission.down.sql b/server/migrations/130_agent_invocation_permission.down.sqlnew file mode 100644index 0000000000..149eab2f5b--- /dev/null+++ b/server/migrations/130_agent_invocation_permission.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS agent_invocation_target;+ALTER TABLE agent DROP COLUMN IF EXISTS permission_mode;diff --git a/server/migrations/130_agent_invocation_permission.up.sql b/server/migrations/130_agent_invocation_permission.up.sqlnew file mode 100644index 0000000000..b9c716d666--- /dev/null+++ b/server/migrations/130_agent_invocation_permission.up.sql@@ -0,0 +1,102 @@+-- Agent invocation permission system, V1 (MUL-3963, parent MUL-3715 Composio epic).+--+-- Splits "who may TRIGGER/INVOKE an agent" out of the overloaded `visibility`+-- column into an explicit, extensible model:+--+-- * agent.permission_mode: 'private' | 'public_to'+-- - private -> only the agent owner may invoke. Workspace admin does+-- NOT bypass this any more (that was the privacy hole described in the+-- issue: an admin could invoke someone's private agent and read their+-- mailbox via that agent's Composio connections).+-- - public_to -> an owner-configured allow-list of invocation targets+-- (see agent_invocation_target) decides who may invoke. Targets stack:+-- one agent may combine a workspace target + specific members + (future)+-- teams; canInvokeAgent admits an actor matching ANY target (OR).+--+-- * agent_invocation_target: the allow-list rows for public_to agents.+-- - target_type = 'workspace' -> every workspace member may invoke.+-- - target_type = 'member' -> only the specific user may invoke.+-- - target_type = 'team' -> reserved for the future team concept;+-- stored but NOT effective in V1 (no team membership source yet).+--+-- `visibility` is intentionally left in place and kept in sync as a DERIVED+-- legacy field by the API layer (private/public_to-member-only -> 'private',+-- public_to-workspace -> 'workspace'), so old clients never see a permission+-- WIDENING. All new trigger/dispatch decisions read permission_mode + targets+-- via canInvokeAgent; visibility is no longer an authorization source.++-- ----------------------------------------------------------------------------+-- agent.permission_mode+-- ----------------------------------------------------------------------------+ALTER TABLE agent+ ADD COLUMN permission_mode TEXT NOT NULL DEFAULT 'private'+ CHECK (permission_mode IN ('private', 'public_to'));++COMMENT ON COLUMN agent.permission_mode IS+ 'Agent invocation permission mode (MUL-3963). private = owner only; public_to = allow-list in agent_invocation_target. Replaces visibility as the authorization source for triggering runs; visibility is now a derived legacy field. Default private = deny-by-default.';++-- ----------------------------------------------------------------------------+-- agent_invocation_target+-- ----------------------------------------------------------------------------+--+-- NO foreign keys by design (Multica migration rule, matching the MUL-3515 §4+-- channel_* generalization): relationships are maintained in the application+-- layer, not by the database. Concretely:+-- * agent_id — cleaned up alongside agent hard-deletes+-- (DeleteAgentInvocationTargetsByArchivedRuntimeAgents runs before+-- DeleteArchivedAgentsByRuntime in the runtime-delete tx). Agents are+-- normally soft-archived, so rows persist across archive/restore.+-- * created_by / member target_id — pruned on member removal via+-- DeleteAgentInvocationTargetsByMember inside the revoke-member tx, so a+-- re-invited user does not inherit stale invocation grants.+--+-- target_id is polymorphic (workspace_id / user_id / future team_id) so it+-- carries NO FK anyway. For 'workspace' rows we store the agent's workspace_id+-- (rather than NULL) so the UNIQUE(agent_id, target_type, target_id) constraint+-- dedups cleanly — Postgres treats NULLs as distinct, which would otherwise+-- allow duplicate workspace rows. member/team rows must carry a target_id.+CREATE TABLE agent_invocation_target (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL,+ target_type TEXT NOT NULL CHECK (target_type IN ('workspace', 'member', 'team')),+ target_id UUID NOT NULL,+ created_by UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (agent_id, target_type, target_id)+);++COMMENT ON TABLE agent_invocation_target IS+ 'Allow-list of who may invoke a public_to agent (MUL-3963). One row per (agent, target_type, target); targets stack and canInvokeAgent OR-matches. workspace rows store the agent workspace_id in target_id; member rows store the user id; team rows are reserved and inert in V1. Rows only matter when agent.permission_mode = public_to. No DB foreign keys: agent_id / created_by / member target_id relationships are maintained in the application layer (see migration comment).';++CREATE INDEX agent_invocation_target_agent_id_idx+ ON agent_invocation_target(agent_id);++-- Reverse lookup: member-target cleanup on user removal, and "which agents can+-- this member invoke" style filters.+CREATE INDEX agent_invocation_target_target_idx+ ON agent_invocation_target(target_type, target_id);++-- ----------------------------------------------------------------------------+-- Backfill from legacy visibility (lossless migration)+-- ----------------------------------------------------------------------------+-- visibility = 'private' -> permission_mode = 'private' (column default), no target+-- visibility = 'workspace' -> permission_mode = 'public_to' + one workspace target+UPDATE agent SET permission_mode = 'public_to' WHERE visibility = 'workspace';++INSERT INTO agent_invocation_target (agent_id, target_type, target_id, created_by)+SELECT id, 'workspace', workspace_id, NULL+FROM agent+WHERE visibility = 'workspace'+ON CONFLICT (agent_id, target_type, target_id) DO NOTHING;++-- ----------------------------------------------------------------------------+-- Refresh two Composio-era column comments to the MUL-3963 rules (the overlay+-- now FOLLOWS invocation permission and uses the agent OWNER's connection; the+-- old "originator must equal owner" gate is gone). These COMMENT ON COLUMN+-- statements also drive the sqlc-generated doc comments in models.go.+-- ----------------------------------------------------------------------------+COMMENT ON COLUMN agent.composio_toolkit_allowlist IS+ 'Composio toolkit slugs this agent is allowed to mount as MCP. NULL or empty array = no MCP overlay. Mounted for any run that passes the agent invocation-permission gate (MUL-3963); the overlay uses the agent OWNER''s active Composio connection, so sharing the agent (public_to) shares these apps with whoever may invoke it. No longer gated on originator == owner. Stored as TEXT[] so the dispatch path can intersect against the owner''s active connections with a single SQL ANY() filter.';++COMMENT ON COLUMN agent_task_queue.originator_user_id IS+ 'Top-of-chain human originator for this run. For human-triggered tasks (comment by a member, chat, quick-create) equals that member. For agent-fanout tasks inherited from the parent task''s originator_user_id via comment.source_task_id. NULL when no human is in the chain (autopilot, system-driven). Used by canInvokeAgent to judge A2A by the originator; the Composio overlay now follows invocation permission and uses the agent owner''s connection, so this is audit/attribution + A2A gating, NOT a Composio owner==originator gate (MUL-3963).';diff --git a/server/migrations/132_agent_task_queue_runtime_connected_apps.down.sql b/server/migrations/132_agent_task_queue_runtime_connected_apps.down.sqlnew file mode 100644index 0000000000..962655d3a5--- /dev/null+++ b/server/migrations/132_agent_task_queue_runtime_connected_apps.down.sql@@ -0,0 +1,13 @@+CREATE OR REPLACE FUNCTION clear_runtime_mcp_overlay_on_terminal_state()+RETURNS TRIGGER AS $$+BEGIN+ IF NEW.status IN ('completed', 'failed', 'cancelled')+ AND OLD.status IS DISTINCT FROM NEW.status+ AND NEW.runtime_mcp_overlay IS NOT NULL THEN+ NEW.runtime_mcp_overlay := NULL;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS runtime_connected_apps;diff --git a/server/migrations/132_agent_task_queue_runtime_connected_apps.up.sql b/server/migrations/132_agent_task_queue_runtime_connected_apps.up.sqlnew file mode 100644index 0000000000..acde5a2594--- /dev/null+++ b/server/migrations/132_agent_task_queue_runtime_connected_apps.up.sql@@ -0,0 +1,24 @@+-- Non-secret task-scoped metadata for MCP overlays. runtime_mcp_overlay holds+-- the actual server URL/headers; this column holds the semantic app mapping+-- the daemon can render into the agent brief, e.g. "Notion via MCP server+-- composio".+ALTER TABLE agent_task_queue+ ADD COLUMN runtime_connected_apps JSONB NULL;++COMMENT ON COLUMN agent_task_queue.runtime_connected_apps IS+ 'Non-secret per-task connected app metadata corresponding to runtime_mcp_overlay, used by the daemon brief to tell agents which app capabilities are mounted. Cleared with runtime_mcp_overlay after task completion.';++-- Extend the existing cleanup trigger so completed rows do not retain either+-- the secret overlay or the owner integration footprint.+CREATE OR REPLACE FUNCTION clear_runtime_mcp_overlay_on_terminal_state()+RETURNS TRIGGER AS $$+BEGIN+ IF NEW.status IN ('completed', 'failed', 'cancelled')+ AND OLD.status IS DISTINCT FROM NEW.status+ AND (NEW.runtime_mcp_overlay IS NOT NULL OR NEW.runtime_connected_apps IS NOT NULL) THEN+ NEW.runtime_mcp_overlay := NULL;+ NEW.runtime_connected_apps := NULL;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 099bc787f7..1c45fea91a 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -312,9 +312,10 @@ func ensureCodexMcpConfig(configPath string, mcpConfig json.RawMessage, logger *// servers to render (empty/null mcp_config) and the caller should only// strip the prior managed block.//-// Claude-style camelCase keys (`args`, `env`, `command`, `url`) pass-// through verbatim — Codex's config schema happens to use the same-// names today. If they ever diverge, rename here rather than in the UI.+// Stdio server keys (`args`, `env`, `command`) pass through verbatim —+// Codex's config schema happens to use the same names today. Remote HTTP+// servers use Codex-specific keys, so they are normalised here rather than+// leaking provider details into the UI/dispatch layer.func renderCodexMcpServersBlock(raw json.RawMessage) (string, bool, error) {if len(raw) == 0 {return "", false, nil@@ -349,6 +350,7 @@ func renderCodexMcpServersBlock(raw json.RawMessage) (string, bool, error) {if serverVal == nil {return "", false, fmt.Errorf("mcp_servers.%s must be a JSON object", name)}+ serverVal = normalizeCodexMcpServerConfig(serverVal)if i > 0 {sb.WriteString("\n")}@@ -376,6 +378,37 @@ func renderCodexMcpServersBlock(raw json.RawMessage) (string, bool, error) {return sb.String(), true, nil}+func normalizeCodexMcpServerConfig(server map[string]any) map[string]any {+ if !isCodexRemoteMcpServer(server) {+ return server+ }++ normalized := make(map[string]any, len(server)+1)+ for k, v := range server {+ switch k {+ case "type":+ continue+ case "headers":+ if _, ok := server["http_headers"]; !ok {+ normalized["http_headers"] = v+ }+ default:+ normalized[k] = v+ }+ }+ normalized["experimental_use_rmcp_client"] = true+ return normalized+}++func isCodexRemoteMcpServer(server map[string]any) bool {+ if typ, ok := server["type"].(string); ok && strings.EqualFold(typ, "http") {+ return true+ }+ _, hasURL := server["url"]+ _, hasCommand := server["command"]+ return hasURL && !hasCommand+}+// stripCodexUserMcpServerTables removes every `[mcp_servers.*]` table// (header + body lines until the next top-level table header or EOF) from// a TOML config string. Sub-tables like `[mcp_servers.fetch.env]` countdiff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 21eb5327cd..6011392021 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -1654,7 +1654,6 @@ func TestCodexExecuteCleansUpWhenScannerOverflowsOnResume(t *testing.T) {}}-func TestCodexExecuteSurfacesUnsupportedServerRequestOnInterruptedTurn(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {@@ -2243,6 +2242,14 @@ func TestEnsureCodexMcpConfigWritesManagedBlock(t *testing.T) {t.Fatalf("expected %q in:\n%s", want, got)}}+ for _, unexpected := range []string{+ `experimental_use_rmcp_client`,+ `http_headers`,+ } {+ if strings.Contains(got, unexpected) {+ t.Fatalf("stdio servers should not get remote MCP key %q, got:\n%s", unexpected, got)+ }+ }fi, err := os.Stat(tmp)if err != nil {@@ -2253,6 +2260,65 @@ func TestEnsureCodexMcpConfigWritesManagedBlock(t *testing.T) {}}+func TestEnsureCodexMcpConfigTranslatesRemoteHTTPServer(t *testing.T) {+ t.Parallel()++ tmp := filepath.Join(t.TempDir(), "config.toml")+ if err := os.WriteFile(tmp, []byte("sandbox_mode = \"workspace-write\"\n"), 0o600); err != nil {+ t.Fatalf("seed: %v", err)+ }++ raw := json.RawMessage(`{"mcpServers":{"composio":{"type":"http","url":"https://mcp.example.test/notion","headers":{"Authorization":"Bearer test-token","x-api-key":"secret"}}}}`)+ if err := ensureCodexMcpConfig(tmp, raw, slog.Default()); err != nil {+ t.Fatalf("ensure: %v", err)+ }+ data, err := os.ReadFile(tmp)+ if err != nil {+ t.Fatalf("read after: %v", err)+ }+ got := string(data)++ for _, want := range []string{+ `[mcp_servers.composio]`,+ `url = "https://mcp.example.test/notion"`,+ `http_headers = { Authorization = "Bearer test-token", x-api-key = "secret" }`,+ `experimental_use_rmcp_client = true`,+ } {+ if !strings.Contains(got, want) {+ t.Fatalf("expected %q in:\n%s", want, got)+ }+ }+ for _, unexpected := range []string{+ `type = "http"`,+ "\nheaders = ",+ } {+ if strings.Contains(got, unexpected) {+ t.Fatalf("remote HTTP server should not render %q, got:\n%s", unexpected, got)+ }+ }+}++func TestRenderCodexMcpServersBlockTreatsURLOnlyServerAsRemote(t *testing.T) {+ t.Parallel()++ block, hasServers, err := renderCodexMcpServersBlock(json.RawMessage(`{"mcpServers":{"remote":{"url":"https://mcp.example.test/session"}}}`))+ if err != nil {+ t.Fatalf("render: %v", err)+ }+ if !hasServers {+ t.Fatal("expected server to render")+ }+ for _, want := range []string{+ `[mcp_servers.remote]`,+ `url = "https://mcp.example.test/session"`,+ `experimental_use_rmcp_client = true`,+ } {+ if !strings.Contains(block, want) {+ t.Fatalf("expected %q in:\n%s", want, block)+ }+ }+}+func TestEnsureCodexMcpConfigForces0600OnPreexistingFile(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {diff --git a/server/pkg/composio/auth_configs.go b/server/pkg/composio/auth_configs.gonew file mode 100644index 0000000000..9d607c5705--- /dev/null+++ b/server/pkg/composio/auth_configs.go@@ -0,0 +1,92 @@+package composio++import (+ "context"+ "net/http"+ "net/url"+ "strconv"+ "strings"+)++// AuthConfig mirrors a subset of a Composio auth config — the project-level+// record that defines HOW users authenticate with a toolkit (the OAuth client,+// API-key scheme, etc.). The connect-link flow needs its opaque `id` (ac_…);+// the other fields drive selection when a toolkit has more than one.+//+// Spec: https://docs.composio.dev/reference/v3/api-reference/auth-configs/getAuthConfigs+type AuthConfig struct {+ ID string `json:"id"`+ Name string `json:"name,omitempty"`+ // Toolkit carries at least the slug (and a logo) the config belongs to.+ Toolkit Toolkit `json:"toolkit"`+ AuthScheme string `json:"auth_scheme,omitempty"`+ // IsComposioManaged is true for Composio's managed OAuth app and false for a+ // custom (bring-your-own client_id/secret) config — the white-label case.+ IsComposioManaged bool `json:"is_composio_managed"`+ // Status is "ENABLED" or "DISABLED". The list endpoint hides disabled+ // configs by default (show_disabled=false).+ Status string `json:"status,omitempty"`+ CreatedAt string `json:"created_at,omitempty"`+ LastUpdatedAt string `json:"last_updated_at,omitempty"`+}++// ListAuthConfigsRequest collects the optional filters of GET /auth_configs.+// Zero values are omitted from the query string.+type ListAuthConfigsRequest struct {+ // ToolkitSlugs filters to specific toolkits; sent as a single+ // comma-separated `toolkit_slug` query param per the v3 spec.+ ToolkitSlugs []string+ // IsComposioManaged, when non-nil, filters by managed vs custom configs.+ IsComposioManaged *bool+ // ShowDisabled includes disabled configs (default false = enabled only).+ ShowDisabled bool+ // Search matches auth configs by name or id.+ Search string+ // Limit is the page size (max 1000 upstream). 0 = upstream default.+ Limit int+ // Cursor pages through results.+ Cursor string+}++// ListAuthConfigsResponse is the typed paginated response.+type ListAuthConfigsResponse struct {+ Items []AuthConfig `json:"items"`+ NextCursor string `json:"next_cursor,omitempty"`+ TotalItems int `json:"total_items,omitempty"`+}++// ListAuthConfigs returns the auth configs registered in the project, with+// optional filters. The project is resolved from the x-api-key (a project API+// key authenticates to exactly one project), so no project id is passed.+func (c *Client) ListAuthConfigs(ctx context.Context, req ListAuthConfigsRequest) (*ListAuthConfigsResponse, error) {+ q := url.Values{}+ if len(req.ToolkitSlugs) > 0 {+ q.Set("toolkit_slug", strings.Join(req.ToolkitSlugs, ","))+ }+ if req.IsComposioManaged != nil {+ q.Set("is_composio_managed", strconv.FormatBool(*req.IsComposioManaged))+ }+ if req.ShowDisabled {+ q.Set("show_disabled", "true")+ }+ if req.Search != "" {+ q.Set("search", req.Search)+ }+ if req.Limit > 0 {+ q.Set("limit", strconv.Itoa(req.Limit))+ }+ if req.Cursor != "" {+ q.Set("cursor", req.Cursor)+ }++ path := "/auth_configs"+ if encoded := q.Encode(); encoded != "" {+ path += "?" + encoded+ }++ var out ListAuthConfigsResponse+ if err := c.do(c.newRequest(ctx), http.MethodGet, path, &out); err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/server/pkg/composio/client_test.go b/server/pkg/composio/client_test.goindex b5ecc85990..93feeb906d 100644--- a/server/pkg/composio/client_test.go+++ b/server/pkg/composio/client_test.go@@ -288,6 +288,48 @@ func TestListConnectedAccounts_QueryString(t *testing.T) {}}+func TestListConnectedAccounts_ParsesNestedAuthConfig(t *testing.T) {+ c, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(t, w, http.StatusOK, map[string]any{+ "items": []map[string]any{+ {+ "id": "ca_nested",+ "user_id": "u_1",+ "auth_config": map[string]any{+ "id": "ac_nested",+ "auth_scheme": "OAUTH2",+ "is_composio_managed": true,+ },+ "toolkit": map[string]any{"slug": "notion"},+ "status": "ACTIVE",+ },+ {+ "id": "ca_top_level",+ "user_id": "u_1",+ "auth_config_id": "ac_top_level",+ "auth_config": map[string]any{"id": "ac_nested_ignored"},+ "toolkit": map[string]any{"slug": "gmail"},+ "status": "ACTIVE",+ },+ },+ })+ })++ resp, err := c.ListConnectedAccounts(context.Background(), composio.ListConnectedAccountsRequest{})+ if err != nil {+ t.Fatalf("ListConnectedAccounts: %v", err)+ }+ if got := resp.Items[0].AuthConfig.ID; got != "ac_nested" {+ t.Errorf("nested auth config id = %q, want ac_nested", got)+ }+ if got := resp.Items[0].AuthConfig.AuthScheme; got != "OAUTH2" {+ t.Errorf("nested auth scheme = %q, want OAUTH2", got)+ }+ if got := resp.Items[1].AuthConfigID; got != "ac_top_level" {+ t.Errorf("top-level auth config id = %q, want ac_top_level", got)+ }+}+func TestRevokeConnection_Success(t *testing.T) {c, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost || r.URL.Path != "/connected_accounts/ca_42/revoke" {diff --git a/server/pkg/composio/connected_accounts.go b/server/pkg/composio/connected_accounts.goindex 5c8a912e31..47fdc74b49 100644--- a/server/pkg/composio/connected_accounts.go+++ b/server/pkg/composio/connected_accounts.go@@ -91,6 +91,7 @@ type ConnectedAccount struct {ID string `json:"id"`UserID string `json:"user_id"`AuthConfigID string `json:"auth_config_id"`+ AuthConfig AuthConfigRef `json:"auth_config"`Toolkit Toolkit `json:"toolkit"`Status string `json:"status"`StatusReason string `json:"status_reason,omitempty"`@@ -100,6 +101,15 @@ type ConnectedAccount struct {Extra map[string]any `json:"-"`}+// AuthConfigRef is the nested auth_config object Composio returns on connected+// accounts. Some responses also include the older top-level auth_config_id.+type AuthConfigRef struct {+ ID string `json:"id"`+ AuthScheme string `json:"auth_scheme,omitempty"`+ IsComposioManaged bool `json:"is_composio_managed,omitempty"`+ IsDisabled bool `json:"is_disabled,omitempty"`+}+// ListConnectedAccountsResponse is the typed paginated response.type ListConnectedAccountsResponse struct {Items []ConnectedAccount `json:"items"`diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 797e9748bd..be529b7b42 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -14,7 +14,7 @@ import (const archiveAgent = `-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`type ArchiveAgentParams struct {@@ -48,6 +48,8 @@ func (q *Queries) ArchiveAgent(ctx context.Context, arg ArchiveAgentParams) (Age&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -56,7 +58,7 @@ const archiveAgentsByIDs = `-- name: ArchiveAgentsByIDs :manyUPDATE agentSET archived_at = now(), archived_by = $1, updated_at = now()WHERE id = ANY($2::uuid[]) AND archived_at IS NULL-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`type ArchiveAgentsByIDsParams struct {@@ -104,6 +106,8 @@ func (q *Queries) ArchiveAgentsByIDs(ctx context.Context, arg ArchiveAgentsByIDs&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,); err != nil {return nil, err}@@ -119,7 +123,7 @@ const archiveAgentsByRuntime = `-- name: ArchiveAgentsByRuntime :manyUPDATE agentSET archived_at = now(), archived_by = $1, updated_at = now()WHERE runtime_id = ANY($2::uuid[]) AND archived_at IS NULL-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`type ArchiveAgentsByRuntimeParams struct {@@ -163,6 +167,8 @@ func (q *Queries) ArchiveAgentsByRuntime(ctx context.Context, arg ArchiveAgentsB&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,); err != nil {return nil, err}@@ -178,7 +184,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {@@ -215,8 +221,11 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -225,7 +234,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`// Bulk-cancel every active (queued/dispatched/running) task for an agent.@@ -273,8 +282,11 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -290,7 +302,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :mUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`// Cancels active tasks belonging to a chat session. Called from@@ -338,8 +350,11 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -355,7 +370,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`// Cancels every active task on the issue and returns the affected rows so the@@ -403,8 +418,11 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -420,7 +438,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgenUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CancelAgentTasksByIssueAndAgentParams struct {@@ -472,8 +490,11 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -489,7 +510,7 @@ const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerCommUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`// Cancels active tasks whose trigger is the given comment. Called when a@@ -537,8 +558,11 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -559,9 +583,9 @@ WITH cancelled AS (AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')AND primary_task.issue_id = $1AND primary_task.agent_id = $2- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.escalation_for_task_id, fallback.fire_at+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps)-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at FROM cancelled+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM cancelled`type CancelDeferredEscalationsForIssueAgentParams struct {@@ -600,8 +624,11 @@ type CancelDeferredEscalationsForIssueAgentRow struct {HandoffNote pgtype.Text `json:"handoff_note"`PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`SquadID pgtype.UUID `json:"squad_id"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`FireAt pgtype.Timestamptz `json:"fire_at"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`}func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {@@ -644,8 +671,11 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -662,7 +692,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE escalation_for_task_id = $1AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {@@ -705,8 +735,11 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -747,7 +780,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type ClaimAgentTaskParams struct {@@ -798,8 +831,55 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ )+ return i, err+}++const clearAgentComposioToolkitAllowlist = `-- name: ClearAgentComposioToolkitAllowlist :one+UPDATE agent SET composio_toolkit_allowlist = NULL, updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode+`++// Explicit NULL-clear for composio_toolkit_allowlist. The COALESCE-based+// UpdateAgent cannot set the column back to NULL — sending an empty array+// through there would persist `{}` (still a non-NULL, equivalent to "no+// toolkits" but distinct from "field never configured"). The API uses this+// dedicated query when the agent owner removes every toolkit; subsequent+// dispatch decisions treat NULL identically to `{}` (both -> no overlay).+func (q *Queries) ClearAgentComposioToolkitAllowlist(ctx context.Context, id pgtype.UUID) (Agent, error) {+ row := q.db.QueryRow(ctx, clearAgentComposioToolkitAllowlist, id)+ var i Agent+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.AvatarUrl,+ &i.RuntimeMode,+ &i.RuntimeConfig,+ &i.Visibility,+ &i.Status,+ &i.MaxConcurrentTasks,+ &i.OwnerID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Description,+ &i.RuntimeID,+ &i.Instructions,+ &i.ArchivedAt,+ &i.ArchivedBy,+ &i.CustomEnv,+ &i.CustomArgs,+ &i.McpConfig,+ &i.Model,+ &i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -807,7 +887,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)const clearAgentMcpConfig = `-- name: ClearAgentMcpConfig :oneUPDATE agent SET mcp_config = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -836,6 +916,8 @@ func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agen&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -843,7 +925,7 @@ func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agenconst clearAgentThinkingLevel = `-- name: ClearAgentThinkingLevel :oneUPDATE agent SET thinking_level = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`// Explicit NULL-clear for thinking_level. COALESCE-based UpdateAgent cannot@@ -875,6 +957,8 @@ func (q *Queries) ClearAgentThinkingLevel(ctx context.Context, id pgtype.UUID) (&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -883,7 +967,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :oneUPDATE agent_task_queueSET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULLWHERE id = $1 AND status = 'running'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CompleteAgentTaskParams struct {@@ -932,8 +1016,11 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -954,28 +1041,37 @@ const createAgent = `-- name: CreateAgent :oneINSERT INTO agent (workspace_id, name, description, avatar_url, runtime_mode,runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id,- instructions, custom_env, custom_args, mcp_config, model, thinking_level-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+ instructions, custom_env, custom_args, mcp_config, model, thinking_level,+ composio_toolkit_allowlist, permission_mode+) VALUES (+ $1, $2, $3, $4, $5,+ $6, $7, $8, $9, $10,+ $11, $12, $13, $14, $15, $16,+ $17::text[],+ COALESCE($18, 'private')+)+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`type CreateAgentParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Name string `json:"name"`- Description string `json:"description"`- AvatarUrl pgtype.Text `json:"avatar_url"`- RuntimeMode string `json:"runtime_mode"`- RuntimeConfig []byte `json:"runtime_config"`- RuntimeID pgtype.UUID `json:"runtime_id"`- Visibility string `json:"visibility"`- MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`- OwnerID pgtype.UUID `json:"owner_id"`- Instructions string `json:"instructions"`- CustomEnv []byte `json:"custom_env"`- CustomArgs []byte `json:"custom_args"`- McpConfig []byte `json:"mcp_config"`- Model pgtype.Text `json:"model"`- ThinkingLevel pgtype.Text `json:"thinking_level"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ Description string `json:"description"`+ AvatarUrl pgtype.Text `json:"avatar_url"`+ RuntimeMode string `json:"runtime_mode"`+ RuntimeConfig []byte `json:"runtime_config"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ Visibility string `json:"visibility"`+ MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`+ OwnerID pgtype.UUID `json:"owner_id"`+ Instructions string `json:"instructions"`+ CustomEnv []byte `json:"custom_env"`+ CustomArgs []byte `json:"custom_args"`+ McpConfig []byte `json:"mcp_config"`+ Model pgtype.Text `json:"model"`+ ThinkingLevel pgtype.Text `json:"thinking_level"`+ ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist"`+ PermissionMode interface{} `json:"permission_mode"`}func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) {@@ -996,6 +1092,8 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agentarg.McpConfig,arg.Model,arg.ThinkingLevel,+ arg.ComposioToolkitAllowlist,+ arg.PermissionMode,)var i Agenterr := row.Scan(@@ -1021,6 +1119,8 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -1029,7 +1129,7 @@ const createAgentTask = `-- name: CreateAgentTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context+ squad_id, context, originator_user_id, runtime_mcp_overlay, runtime_connected_apps)VALUES ($1, $2, $3, 'queued', $4, $5,@@ -1042,23 +1142,29 @@ VALUES (WHEN COALESCE($11::text, '') <> ''THEN jsonb_build_object('head_sha', $11::text)ELSE NULL- END+ END,+ $12,+ $13,+ $14)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CreateAgentTaskParams struct {- AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`- IssueID pgtype.UUID `json:"issue_id"`- Priority int32 `json:"priority"`- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`- TriggerSummary pgtype.Text `json:"trigger_summary"`- ForceFreshSession pgtype.Bool `json:"force_fresh_session"`- IsLeaderTask pgtype.Bool `json:"is_leader_task"`- HandoffNote pgtype.Text `json:"handoff_note"`- SquadID pgtype.UUID `json:"squad_id"`- HeadSha pgtype.Text `json:"head_sha"`+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Priority int32 `json:"priority"`+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`+ HandoffNote pgtype.Text `json:"handoff_note"`+ SquadID pgtype.UUID `json:"squad_id"`+ HeadSha pgtype.Text `json:"head_sha"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`}// head_sha stamps the commit under review into the task's context JSONB so the@@ -1081,6 +1187,9 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsarg.HandoffNote,arg.SquadID,arg.HeadSha,+ arg.OriginatorUserID,+ arg.RuntimeMcpOverlay,+ arg.RuntimeConnectedApps,)var i AgentTaskQueueerr := row.Scan(@@ -1114,8 +1223,11 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -1134,7 +1246,7 @@ VALUES ($9,$10)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CreateDeferredAgentTaskParams struct {@@ -1198,23 +1310,37 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}const createQuickCreateTask = `-- name: CreateQuickCreateTask :one-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context)-VALUES ($1, $2, NULL, 'queued', $3, $4)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,+ runtime_mcp_overlay, runtime_connected_apps+)+VALUES (+ $1, $2, NULL, 'queued', $3, $4,+ $5,+ $6,+ $7+)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CreateQuickCreateTaskParams struct {- AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`- Priority int32 `json:"priority"`- Context []byte `json:"context"`+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ Priority int32 `json:"priority"`+ Context []byte `json:"context"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`}// Quick-create tasks have no issue / chat / autopilot link; the entire job@@ -1226,6 +1352,9 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCreaarg.RuntimeID,arg.Priority,arg.Context,+ arg.OriginatorUserID,+ arg.RuntimeMcpOverlay,+ arg.RuntimeConnectedApps,)var i AgentTaskQueueerr := row.Scan(@@ -1259,8 +1388,11 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -1271,7 +1403,7 @@ INSERT INTO agent_task_queue (status, priority, trigger_comment_id, trigger_summary, context,session_id, work_dir,attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,- squad_id+ squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,@@ -1281,12 +1413,21 @@ SELECTp.attempt + 1, p.max_attempts, p.id,p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',p.is_leader_task,- p.squad_id+ p.squad_id,+ p.originator_user_id,+ $2,+ $3FROM agent_task_queue pWHERE p.id = $1-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`+type CreateRetryTaskParams struct {+ ID pgtype.UUID `json:"id"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+}+// Clones a parent task into a fresh queued attempt. Carries forward the// agent's resume context (session_id/work_dir) so the child can continue// the conversation when the backend supports it. Resume-unsafe failures are@@ -1298,8 +1439,14 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c// parent and the self-trigger guard in shouldEnqueueSquadLeaderOnComment// continues to recognise it as a leader task. Inheriting squad_id also keeps// the squad-leader briefing injection working across retries.-func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {- row := q.db.QueryRow(ctx, createRetryTask, id)+//+// originator_user_id is inherited so the Composio overlay decision sees the+// same top-of-chain human across the retry: the user behind the original+// run has not changed. The Composio overlay follows the agent's invocation+// permission and uses the agent owner's connection (MUL-3963); originator is+// carried for A2A/audit, not as an originator == agent.owner_id gate.+func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, createRetryTask, arg.ID, arg.RuntimeMcpOverlay, arg.RuntimeConnectedApps)var i AgentTaskQueueerr := row.Scan(&i.ID,@@ -1332,8 +1479,11 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -1357,7 +1507,7 @@ FROM victims vWHERE t.id = v.idAND t.status = 'queued'AND t.created_at < now() - make_interval(secs => $1::double precision)-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.escalation_for_task_id, t.fire_at+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps`type ExpireStaleQueuedTasksParams struct {@@ -1428,8 +1578,11 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -1448,7 +1601,7 @@ WHERE id = $1AND runtime_id = $2AND status IN ('dispatched', 'waiting_local_directory')AND started_at IS NULL-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type ExtendAgentTaskPrepareLeaseParams struct {@@ -1495,8 +1648,11 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -1511,7 +1667,7 @@ SET status = 'failed',work_dir = COALESCE($5, work_dir),prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type FailAgentTaskParams struct {@@ -1571,8 +1727,11 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -1588,7 +1747,7 @@ WHERE (AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now()))OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type FailStaleTasksParams struct {@@ -1647,8 +1806,11 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -1661,7 +1823,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)}const getAgent = `-- name: GetAgent :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agentWHERE id = $1`@@ -1691,12 +1853,14 @@ func (q *Queries) GetAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}const getAgentForClaimUpdate = `-- name: GetAgentForClaimUpdate :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agentWHERE id = $1FOR UPDATE`@@ -1727,12 +1891,14 @@ func (q *Queries) GetAgentForClaimUpdate(ctx context.Context, id pgtype.UUID) (A&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}const getAgentInWorkspace = `-- name: GetAgentInWorkspace :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agentWHERE id = $1 AND workspace_id = $2`@@ -1767,12 +1933,14 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}const getAgentTask = `-- name: GetAgentTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM agent_task_queueWHERE id = $1`@@ -1810,14 +1978,17 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.escalation_for_task_id, atq.fire_at FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE atq.id = $1 AND a.workspace_id = $2`@@ -1868,8 +2039,11 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -2210,7 +2384,7 @@ func (q *Queries) LinkTaskToIssue(ctx context.Context, arg LinkTaskToIssueParams}const listActiveAgentsByRuntime = `-- name: ListActiveAgentsByRuntime :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agentWHERE runtime_id = $1 AND archived_at IS NULLORDER BY name ASC`@@ -2253,6 +2427,8 @@ func (q *Queries) ListActiveAgentsByRuntime(ctx context.Context, runtimeID pgtyp&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,); err != nil {return nil, err}@@ -2265,7 +2441,7 @@ func (q *Queries) ListActiveAgentsByRuntime(ctx context.Context, runtimeID pgtyp}const listActiveAgentsByRuntimeForUpdate = `-- name: ListActiveAgentsByRuntimeForUpdate :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agentWHERE runtime_id = $1 AND archived_at IS NULLORDER BY name ASCFOR UPDATE@@ -2311,6 +2487,8 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,); err != nil {return nil, err}@@ -2323,7 +2501,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim}const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM agent_task_queueWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESC`@@ -2373,8 +2551,11 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -2387,7 +2568,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI}const listAgentTasks = `-- name: ListAgentTasks :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM agent_task_queueWHERE agent_id = $1ORDER BY created_at DESC`@@ -2432,8 +2613,11 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -2446,7 +2630,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag}const listAgents = `-- name: ListAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agentWHERE workspace_id = $1 AND archived_at IS NULLORDER BY created_at ASC`@@ -2483,6 +2667,8 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,); err != nil {return nil, err}@@ -2495,7 +2681,7 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag}const listAllAgents = `-- name: ListAllAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode FROM agentWHERE workspace_id = $1ORDER BY created_at ASC`@@ -2532,6 +2718,8 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,); err != nil {return nil, err}@@ -2544,7 +2732,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([}const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC`@@ -2589,8 +2777,11 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -2603,7 +2794,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp}const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM agent_task_queueWHERE runtime_id = $1 AND status = 'queued'ORDER BY priority DESC, created_at ASC`@@ -2656,8 +2847,11 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -2670,7 +2864,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim}const listTasksByIssue = `-- name: ListTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC`@@ -2715,8 +2909,11 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -2729,15 +2926,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]}const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.escalation_for_task_id, atq.fire_at FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')UNION ALL-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.escalation_for_task_id, t.fire_at FROM (- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.escalation_for_task_id, atq.fire_at+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps FROM (+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_appsFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1@@ -2804,8 +3001,11 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -2823,7 +3023,7 @@ SET status = 'waiting_local_directory',wait_reason = $2,prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)WHERE id = $1 AND status = 'dispatched'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type MarkAgentTaskWaitingLocalDirectoryParams struct {@@ -2875,8 +3075,11 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -2887,7 +3090,7 @@ SET status = 'queued'WHERE runtime_id = $1AND status = 'deferred'AND fire_at <= now()-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {@@ -2930,8 +3133,11 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -2958,7 +3164,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type ReclaimStaleDispatchedTaskForRuntimeParams struct {@@ -3006,8 +3212,11 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -3021,7 +3230,7 @@ SET status = 'failed',wait_reason = NULL,prepare_lease_expires_at = NULLWHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`// Called by the daemon at startup. Atomically fails any dispatched/running/@@ -3070,8 +3279,11 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -3091,7 +3303,7 @@ SET status = CASE WHEN EXISTS () THEN 'working' ELSE 'idle' END,updated_at = now()WHERE a.id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -3120,6 +3332,8 @@ func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUI&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -3127,7 +3341,7 @@ func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUIconst restoreAgent = `-- name: RestoreAgent :oneUPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -3156,6 +3370,8 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -3167,7 +3383,7 @@ SET status = 'running',wait_reason = NULL,prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`// Transitions a task to running. Accepts either 'dispatched' (the normal@@ -3210,8 +3426,11 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}@@ -3225,38 +3444,48 @@ UPDATE agent SETruntime_mode = COALESCE($6, runtime_mode),runtime_id = COALESCE($7, runtime_id),visibility = COALESCE($8, visibility),- status = COALESCE($9, status),- max_concurrent_tasks = COALESCE($10, max_concurrent_tasks),- instructions = COALESCE($11, instructions),- custom_env = COALESCE($12, custom_env),- custom_args = COALESCE($13, custom_args),- mcp_config = COALESCE($14, mcp_config),- model = COALESCE($15, model),- thinking_level = COALESCE($16, thinking_level),+ permission_mode = COALESCE($9, permission_mode),+ status = COALESCE($10, status),+ max_concurrent_tasks = COALESCE($11, max_concurrent_tasks),+ instructions = COALESCE($12, instructions),+ custom_env = COALESCE($13, custom_env),+ custom_args = COALESCE($14, custom_args),+ mcp_config = COALESCE($15, mcp_config),+ model = COALESCE($16, model),+ thinking_level = COALESCE($17, thinking_level),+ composio_toolkit_allowlist = COALESCE($18::text[], composio_toolkit_allowlist),updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`type UpdateAgentParams struct {- ID pgtype.UUID `json:"id"`- Name pgtype.Text `json:"name"`- Description pgtype.Text `json:"description"`- AvatarUrl pgtype.Text `json:"avatar_url"`- RuntimeConfig []byte `json:"runtime_config"`- RuntimeMode pgtype.Text `json:"runtime_mode"`- RuntimeID pgtype.UUID `json:"runtime_id"`- Visibility pgtype.Text `json:"visibility"`- Status pgtype.Text `json:"status"`- MaxConcurrentTasks pgtype.Int4 `json:"max_concurrent_tasks"`- Instructions pgtype.Text `json:"instructions"`- CustomEnv []byte `json:"custom_env"`- CustomArgs []byte `json:"custom_args"`- McpConfig []byte `json:"mcp_config"`- Model pgtype.Text `json:"model"`- ThinkingLevel pgtype.Text `json:"thinking_level"`-}-+ ID pgtype.UUID `json:"id"`+ Name pgtype.Text `json:"name"`+ Description pgtype.Text `json:"description"`+ AvatarUrl pgtype.Text `json:"avatar_url"`+ RuntimeConfig []byte `json:"runtime_config"`+ RuntimeMode pgtype.Text `json:"runtime_mode"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ Visibility pgtype.Text `json:"visibility"`+ PermissionMode pgtype.Text `json:"permission_mode"`+ Status pgtype.Text `json:"status"`+ MaxConcurrentTasks pgtype.Int4 `json:"max_concurrent_tasks"`+ Instructions pgtype.Text `json:"instructions"`+ CustomEnv []byte `json:"custom_env"`+ CustomArgs []byte `json:"custom_args"`+ McpConfig []byte `json:"mcp_config"`+ Model pgtype.Text `json:"model"`+ ThinkingLevel pgtype.Text `json:"thinking_level"`+ ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist"`+}++// composio_toolkit_allowlist is set wholesale: the API layer is responsible+// for normalising the request payload to either (a) the new slug list — sent+// here verbatim — or (b) an empty array to explicitly disable Composio.+// Distinguish "field omitted" (preserve) from "explicit clear" via+// ClearAgentComposioToolkitAllowlist below, mirroring the+// thinking_level / mcp_config two-query pattern: COALESCE can't restore NULL.func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent, error) {row := q.db.QueryRow(ctx, updateAgent,arg.ID,@@ -3267,6 +3496,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentarg.RuntimeMode,arg.RuntimeID,arg.Visibility,+ arg.PermissionMode,arg.Status,arg.MaxConcurrentTasks,arg.Instructions,@@ -3275,6 +3505,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentarg.McpConfig,arg.Model,arg.ThinkingLevel,+ arg.ComposioToolkitAllowlist,)var i Agenterr := row.Scan(@@ -3300,6 +3531,8 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -3308,7 +3541,7 @@ const updateAgentCustomEnv = `-- name: UpdateAgentCustomEnv :oneUPDATE agentSET custom_env = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`type UpdateAgentCustomEnvParams struct {@@ -3347,6 +3580,8 @@ func (q *Queries) UpdateAgentCustomEnv(ctx context.Context, arg UpdateAgentCusto&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}@@ -3354,7 +3589,7 @@ func (q *Queries) UpdateAgentCustomEnv(ctx context.Context, arg UpdateAgentCustoconst updateAgentStatus = `-- name: UpdateAgentStatus :oneUPDATE agent SET status = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode`type UpdateAgentStatusParams struct {@@ -3388,6 +3623,8 @@ func (q *Queries) UpdateAgentStatus(ctx context.Context, arg UpdateAgentStatusPa&i.McpConfig,&i.Model,&i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,)return i, err}diff --git a/server/pkg/db/generated/agent_invocation_target.sql.go b/server/pkg/db/generated/agent_invocation_target.sql.gonew file mode 100644index 0000000000..24ff307775--- /dev/null+++ b/server/pkg/db/generated/agent_invocation_target.sql.go@@ -0,0 +1,165 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: agent_invocation_target.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const createAgentInvocationTarget = `-- name: CreateAgentInvocationTarget :exec+INSERT INTO agent_invocation_target (agent_id, target_type, target_id, created_by)+VALUES ($1, $2, $3, $4)+ON CONFLICT (agent_id, target_type, target_id) DO UPDATE SET+ created_by = EXCLUDED.created_by,+ created_at = now()+`++type CreateAgentInvocationTargetParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ TargetType string `json:"target_type"`+ TargetID pgtype.UUID `json:"target_id"`+ CreatedBy pgtype.UUID `json:"created_by"`+}++// Idempotent upsert: re-adding an existing (agent, target_type, target)+// refreshes created_by/created_at rather than erroring. Callers replace the+// whole set via DeleteAgentInvocationTargets + a series of these, so the+// ON CONFLICT is belt-and-suspenders against races.+func (q *Queries) CreateAgentInvocationTarget(ctx context.Context, arg CreateAgentInvocationTargetParams) error {+ _, err := q.db.Exec(ctx, createAgentInvocationTarget,+ arg.AgentID,+ arg.TargetType,+ arg.TargetID,+ arg.CreatedBy,+ )+ return err+}++const deleteAgentInvocationTargets = `-- name: DeleteAgentInvocationTargets :exec+DELETE FROM agent_invocation_target+WHERE agent_id = $1+`++// Clears every target for an agent. Used before re-writing the allow-list so+// the update is a wholesale replace, matching the composio_toolkit_allowlist+// write model.+func (q *Queries) DeleteAgentInvocationTargets(ctx context.Context, agentID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteAgentInvocationTargets, agentID)+ return err+}++const deleteAgentInvocationTargetsByArchivedRuntimeAgents = `-- name: DeleteAgentInvocationTargetsByArchivedRuntimeAgents :exec+DELETE FROM agent_invocation_target+WHERE agent_id IN (+ SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL+)+`++// Application-layer replacement for the (deliberately absent) agent_id ON+// DELETE CASCADE: removes invocation targets for the archived agents a runtime+// delete is about to hard-delete. MUST run in the same tx as, and BEFORE,+// DeleteArchivedAgentsByRuntime so no orphan target rows survive the agent+// rows they belonged to. Mirrors the agent hard-delete predicate exactly.+func (q *Queries) DeleteAgentInvocationTargetsByArchivedRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteAgentInvocationTargetsByArchivedRuntimeAgents, runtimeID)+ return err+}++const deleteAgentInvocationTargetsByMember = `-- name: DeleteAgentInvocationTargetsByMember :exec+DELETE FROM agent_invocation_target ait+USING agent a+WHERE ait.agent_id = a.id+ AND a.workspace_id = $1+ AND ait.target_type = 'member'+ AND ait.target_id = $2+`++type DeleteAgentInvocationTargetsByMemberParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ TargetID pgtype.UUID `json:"target_id"`+}++// Removes member-target grants pointing at a leaving user, SCOPED to a single+// workspace. A user may belong to multiple workspaces; removing them from one+// must NOT touch their invocation grants on agents in another workspace. Joins+// through agent (agent_invocation_target has no workspace_id column and no FK)+// to bound the delete to @workspace_id.+func (q *Queries) DeleteAgentInvocationTargetsByMember(ctx context.Context, arg DeleteAgentInvocationTargetsByMemberParams) error {+ _, err := q.db.Exec(ctx, deleteAgentInvocationTargetsByMember, arg.WorkspaceID, arg.TargetID)+ return err+}++const listAgentInvocationTargets = `-- name: ListAgentInvocationTargets :many++SELECT id, agent_id, target_type, target_id, created_by, created_at FROM agent_invocation_target+WHERE agent_id = $1+ORDER BY target_type ASC, created_at ASC+`++// Agent invocation permission targets (MUL-3963). Rows are the allow-list for+// agents whose permission_mode = 'public_to'. See migration 130.+func (q *Queries) ListAgentInvocationTargets(ctx context.Context, agentID pgtype.UUID) ([]AgentInvocationTarget, error) {+ rows, err := q.db.Query(ctx, listAgentInvocationTargets, agentID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentInvocationTarget{}+ for rows.Next() {+ var i AgentInvocationTarget+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.TargetType,+ &i.TargetID,+ &i.CreatedBy,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listAgentInvocationTargetsByAgentIDs = `-- name: ListAgentInvocationTargetsByAgentIDs :many+SELECT id, agent_id, target_type, target_id, created_by, created_at FROM agent_invocation_target+WHERE agent_id = ANY($1::uuid[])+ORDER BY agent_id, target_type ASC, created_at ASC+`++// Batch load for the agent list endpoint so we don't N+1 per agent.+func (q *Queries) ListAgentInvocationTargetsByAgentIDs(ctx context.Context, agentIds []pgtype.UUID) ([]AgentInvocationTarget, error) {+ rows, err := q.db.Query(ctx, listAgentInvocationTargetsByAgentIDs, agentIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentInvocationTarget{}+ for rows.Next() {+ var i AgentInvocationTarget+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.TargetType,+ &i.TargetID,+ &i.CreatedBy,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 078c80ed9b..b0b86b984c 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -211,7 +211,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)VALUES ($1, $2, NULL, 'queued', $3, $4, $5)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CreateAutopilotTaskParams struct {@@ -265,8 +265,11 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex be2e2a1d8a..aaac155924 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -90,22 +90,29 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPaconst createChatTask = `-- name: CreateChatTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id,- initiator_user_id, force_fresh_session+ initiator_user_id, originator_user_id, force_fresh_session, runtime_mcp_overlay,+ runtime_connected_apps)VALUES ($1, $2, NULL, 'queued', $3, $4, $5,- COALESCE($6::boolean, FALSE)+ $6,+ COALESCE($7::boolean, FALSE),+ $8,+ $9)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CreateChatTaskParams struct {- AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`- Priority int32 `json:"priority"`- ChatSessionID pgtype.UUID `json:"chat_session_id"`- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`- ForceFreshSession pgtype.Bool `json:"force_fresh_session"`+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ Priority int32 `json:"priority"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`}func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams) (AgentTaskQueue, error) {@@ -115,7 +122,10 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)arg.Priority,arg.ChatSessionID,arg.InitiatorUserID,+ arg.OriginatorUserID,arg.ForceFreshSession,+ arg.RuntimeMcpOverlay,+ arg.RuntimeConnectedApps,)var i AgentTaskQueueerr := row.Scan(@@ -149,8 +159,11 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,)return i, err}diff --git a/server/pkg/db/generated/composio.sql.go b/server/pkg/db/generated/composio.sql.gonew file mode 100644index 0000000000..4d266afc55--- /dev/null+++ b/server/pkg/db/generated/composio.sql.go@@ -0,0 +1,155 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: composio.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const getUserComposioConnection = `-- name: GetUserComposioConnection :one+SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at FROM user_composio_connection+WHERE id = $1 AND user_id = $2+`++type GetUserComposioConnectionParams struct {+ ID pgtype.UUID `json:"id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Owner-scoped lookup: a connection can only be read by the user who owns it,+// so one user cannot disconnect another's account by guessing the UUID.+func (q *Queries) GetUserComposioConnection(ctx context.Context, arg GetUserComposioConnectionParams) (UserComposioConnection, error) {+ row := q.db.QueryRow(ctx, getUserComposioConnection, arg.ID, arg.UserID)+ var i UserComposioConnection+ err := row.Scan(+ &i.ID,+ &i.UserID,+ &i.ToolkitSlug,+ &i.AuthConfigID,+ &i.ConnectedAccountID,+ &i.ComposioUserID,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const listActiveUserComposioConnections = `-- name: ListActiveUserComposioConnections :many+SELECT id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at FROM user_composio_connection+WHERE user_id = $1 AND status = 'active'+ORDER BY connected_at DESC+`++func (q *Queries) ListActiveUserComposioConnections(ctx context.Context, userID pgtype.UUID) ([]UserComposioConnection, error) {+ rows, err := q.db.Query(ctx, listActiveUserComposioConnections, userID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []UserComposioConnection{}+ for rows.Next() {+ var i UserComposioConnection+ if err := rows.Scan(+ &i.ID,+ &i.UserID,+ &i.ToolkitSlug,+ &i.AuthConfigID,+ &i.ConnectedAccountID,+ &i.ComposioUserID,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const markUserComposioConnectionRevoked = `-- name: MarkUserComposioConnectionRevoked :exec+UPDATE user_composio_connection+SET status = 'revoked', updated_at = now()+WHERE id = $1 AND user_id = $2+`++type MarkUserComposioConnectionRevokedParams struct {+ ID pgtype.UUID `json:"id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Idempotent: re-running on an already-revoked row is a no-op write. Scoped to+// the owner for defense-in-depth.+func (q *Queries) MarkUserComposioConnectionRevoked(ctx context.Context, arg MarkUserComposioConnectionRevokedParams) error {+ _, err := q.db.Exec(ctx, markUserComposioConnectionRevoked, arg.ID, arg.UserID)+ return err+}++const upsertUserComposioConnection = `-- name: UpsertUserComposioConnection :one++INSERT INTO user_composio_connection (+ user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status+) VALUES (+ $1, $2, $3, $4, $5, 'active'+)+ON CONFLICT (user_id, connected_account_id) DO UPDATE SET+ toolkit_slug = EXCLUDED.toolkit_slug,+ auth_config_id = EXCLUDED.auth_config_id,+ composio_user_id = EXCLUDED.composio_user_id,+ status = 'active',+ updated_at = now()+RETURNING id, user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status, connected_at, last_used_at, created_at, updated_at+`++type UpsertUserComposioConnectionParams struct {+ UserID pgtype.UUID `json:"user_id"`+ ToolkitSlug string `json:"toolkit_slug"`+ AuthConfigID string `json:"auth_config_id"`+ ConnectedAccountID string `json:"connected_account_id"`+ ComposioUserID string `json:"composio_user_id"`+}++// =====================+// User Composio Connection+// =====================+// Idempotent on (user_id, connected_account_id): a duplicate callback for the+// same connected account re-activates the row instead of inserting a second+// one. connected_at is preserved on conflict (first-connect time); updated_at+// moves so the reactivation is observable.+func (q *Queries) UpsertUserComposioConnection(ctx context.Context, arg UpsertUserComposioConnectionParams) (UserComposioConnection, error) {+ row := q.db.QueryRow(ctx, upsertUserComposioConnection,+ arg.UserID,+ arg.ToolkitSlug,+ arg.AuthConfigID,+ arg.ConnectedAccountID,+ arg.ComposioUserID,+ )+ var i UserComposioConnection+ err := row.Scan(+ &i.ID,+ &i.UserID,+ &i.ToolkitSlug,+ &i.AuthConfigID,+ &i.ConnectedAccountID,+ &i.ComposioUserID,+ &i.Status,+ &i.ConnectedAt,+ &i.LastUsedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex ecd37d0cbb..33f45d7bc2 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -44,6 +44,20 @@ type Agent struct {McpConfig []byte `json:"mcp_config"`Model pgtype.Text `json:"model"`ThinkingLevel pgtype.Text `json:"thinking_level"`+ // Composio toolkit slugs this agent is allowed to mount as MCP. NULL or empty array = no MCP overlay. Mounted for any run that passes the agent invocation-permission gate (MUL-3963); the overlay uses the agent OWNER's active Composio connection, so sharing the agent (public_to) shares these apps with whoever may invoke it. No longer gated on originator == owner. Stored as TEXT[] so the dispatch path can intersect against the owner's active connections with a single SQL ANY() filter.+ ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist"`+ // Agent invocation permission mode (MUL-3963). private = owner only; public_to = allow-list in agent_invocation_target. Replaces visibility as the authorization source for triggering runs; visibility is now a derived legacy field. Default private = deny-by-default.+ PermissionMode string `json:"permission_mode"`+}++// Allow-list of who may invoke a public_to agent (MUL-3963). One row per (agent, target_type, target); targets stack and canInvokeAgent OR-matches. workspace rows store the agent workspace_id in target_id; member rows store the user id; team rows are reserved and inert in V1. Rows only matter when agent.permission_mode = public_to. No DB foreign keys: agent_id / created_by / member target_id relationships are maintained in the application layer (see migration comment).+type AgentInvocationTarget struct {+ ID pgtype.UUID `json:"id"`+ AgentID pgtype.UUID `json:"agent_id"`+ TargetType string `json:"target_type"`+ TargetID pgtype.UUID `json:"target_id"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`}type AgentRuntime struct {@@ -102,8 +116,14 @@ type AgentTaskQueue struct {HandoffNote pgtype.Text `json:"handoff_note"`PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`SquadID pgtype.UUID `json:"squad_id"`- EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`- FireAt pgtype.Timestamptz `json:"fire_at"`+ // Per-task MCP servers computed at dispatch time, merged on top of agent.mcp_config. Currently used by Composio integration to inject the initiator user's session URL. Cleared after task completes via trg_clear_runtime_mcp_overlay.+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`+ FireAt pgtype.Timestamptz `json:"fire_at"`+ // Top-of-chain human originator for this run. For human-triggered tasks (comment by a member, chat, quick-create) equals that member. For agent-fanout tasks inherited from the parent task's originator_user_id via comment.source_task_id. NULL when no human is in the chain (autopilot, system-driven). Used by canInvokeAgent to judge A2A by the originator; the Composio overlay now follows invocation permission and uses the agent owner's connection, so this is audit/attribution + A2A gating, NOT a Composio owner==originator gate (MUL-3963).+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ // Non-secret per-task connected app metadata corresponding to runtime_mcp_overlay, used by the daemon brief to tell agents which app capabilities are mounted. Cleared with runtime_mcp_overlay after task completion.+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`}type Attachment struct {@@ -858,6 +878,20 @@ type User struct {Timezone pgtype.Text `json:"timezone"`}+type UserComposioConnection struct {+ ID pgtype.UUID `json:"id"`+ UserID pgtype.UUID `json:"user_id"`+ ToolkitSlug string `json:"toolkit_slug"`+ AuthConfigID string `json:"auth_config_id"`+ ConnectedAccountID string `json:"connected_account_id"`+ ComposioUserID string `json:"composio_user_id"`+ Status string `json:"status"`+ ConnectedAt pgtype.Timestamptz `json:"connected_at"`+ LastUsedAt pgtype.Timestamptz `json:"last_used_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type VerificationCode struct {ID pgtype.UUID `json:"id"`Email string `json:"email"`diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex c04d5aadfe..9902af0149 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -16,7 +16,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`type CancelAgentTasksByRuntimeOrAgentParams struct {@@ -78,8 +78,11 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}@@ -199,7 +202,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')AND runtime_id IN (SELECT id FROM agent_runtime WHERE status = 'offline')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, escalation_for_task_id, fire_at+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps`// Marks dispatched/running/waiting_local_directory tasks as failed when@@ -245,8 +248,11 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ&i.HandoffNote,&i.PrepareLeaseExpiresAt,&i.SquadID,+ &i.RuntimeMcpOverlay,&i.EscalationForTaskID,&i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 238e21b5d5..0b4717444e 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -20,11 +20,24 @@ WHERE id = $1 AND workspace_id = $2;INSERT INTO agent (workspace_id, name, description, avatar_url, runtime_mode,runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id,- instructions, custom_env, custom_args, mcp_config, model, thinking_level-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)+ instructions, custom_env, custom_args, mcp_config, model, thinking_level,+ composio_toolkit_allowlist, permission_mode+) VALUES (+ $1, $2, $3, $4, $5,+ $6, $7, $8, $9, $10,+ $11, $12, $13, $14, $15, $16,+ sqlc.narg('composio_toolkit_allowlist')::text[],+ COALESCE(sqlc.narg('permission_mode'), 'private')+)RETURNING *;-- name: UpdateAgent :one+-- composio_toolkit_allowlist is set wholesale: the API layer is responsible+-- for normalising the request payload to either (a) the new slug list — sent+-- here verbatim — or (b) an empty array to explicitly disable Composio.+-- Distinguish "field omitted" (preserve) from "explicit clear" via+-- ClearAgentComposioToolkitAllowlist below, mirroring the+-- thinking_level / mcp_config two-query pattern: COALESCE can't restore NULL.UPDATE agent SETname = COALESCE(sqlc.narg('name'), name),description = COALESCE(sqlc.narg('description'), description),@@ -33,6 +46,7 @@ UPDATE agent SETruntime_mode = COALESCE(sqlc.narg('runtime_mode'), runtime_mode),runtime_id = COALESCE(sqlc.narg('runtime_id'), runtime_id),visibility = COALESCE(sqlc.narg('visibility'), visibility),+ permission_mode = COALESCE(sqlc.narg('permission_mode'), permission_mode),status = COALESCE(sqlc.narg('status'), status),max_concurrent_tasks = COALESCE(sqlc.narg('max_concurrent_tasks'), max_concurrent_tasks),instructions = COALESCE(sqlc.narg('instructions'), instructions),@@ -41,10 +55,22 @@ UPDATE agent SETmcp_config = COALESCE(sqlc.narg('mcp_config'), mcp_config),model = COALESCE(sqlc.narg('model'), model),thinking_level = COALESCE(sqlc.narg('thinking_level'), thinking_level),+ composio_toolkit_allowlist = COALESCE(sqlc.narg('composio_toolkit_allowlist')::text[], composio_toolkit_allowlist),updated_at = now()WHERE id = $1RETURNING *;+-- name: ClearAgentComposioToolkitAllowlist :one+-- Explicit NULL-clear for composio_toolkit_allowlist. The COALESCE-based+-- UpdateAgent cannot set the column back to NULL — sending an empty array+-- through there would persist `{}` (still a non-NULL, equivalent to "no+-- toolkits" but distinct from "field never configured"). The API uses this+-- dedicated query when the agent owner removes every toolkit; subsequent+-- dispatch decisions treat NULL identically to `{}` (both -> no overlay).+UPDATE agent SET composio_toolkit_allowlist = NULL, updated_at = now()+WHERE id = $1+RETURNING *;+-- name: ClearAgentThinkingLevel :one-- Explicit NULL-clear for thinking_level. COALESCE-based UpdateAgent cannot-- set the column back to NULL, so the API layer routes "user picked Default"@@ -144,7 +170,7 @@ ORDER BY created_at DESC;INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context+ squad_id, context, originator_user_id, runtime_mcp_overlay, runtime_connected_apps)VALUES ($1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),@@ -157,7 +183,10 @@ VALUES (WHEN COALESCE(sqlc.narg('head_sha')::text, '') <> ''THEN jsonb_build_object('head_sha', sqlc.narg('head_sha')::text)ELSE NULL- END+ END,+ sqlc.narg(originator_user_id),+ sqlc.narg(runtime_mcp_overlay),+ sqlc.narg(runtime_connected_apps))RETURNING *;@@ -165,8 +194,16 @@ RETURNING *;-- Quick-create tasks have no issue / chat / autopilot link; the entire job-- description (prompt, requester, workspace) lives in context JSONB. The-- daemon detects this variant via context.type == "quick_create".-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context)-VALUES ($1, $2, NULL, 'queued', $3, $4)+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,+ runtime_mcp_overlay, runtime_connected_apps+)+VALUES (+ $1, $2, NULL, 'queued', $3, $4,+ sqlc.narg(originator_user_id),+ sqlc.narg(runtime_mcp_overlay),+ sqlc.narg(runtime_connected_apps)+)RETURNING *;-- name: CreateDeferredAgentTask :one@@ -210,12 +247,18 @@ WHERE id = $1 AND issue_id IS NULL;-- parent and the self-trigger guard in shouldEnqueueSquadLeaderOnComment-- continues to recognise it as a leader task. Inheriting squad_id also keeps-- the squad-leader briefing injection working across retries.+--+-- originator_user_id is inherited so the Composio overlay decision sees the+-- same top-of-chain human across the retry: the user behind the original+-- run has not changed. The Composio overlay follows the agent's invocation+-- permission and uses the agent owner's connection (MUL-3963); originator is+-- carried for A2A/audit, not as an originator == agent.owner_id gate.INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,status, priority, trigger_comment_id, trigger_summary, context,session_id, work_dir,attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,- squad_id+ squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps)SELECTp.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,@@ -225,7 +268,10 @@ SELECTp.attempt + 1, p.max_attempts, p.id,p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',p.is_leader_task,- p.squad_id+ p.squad_id,+ p.originator_user_id,+ sqlc.narg(runtime_mcp_overlay),+ sqlc.narg(runtime_connected_apps)FROM agent_task_queue pWHERE p.id = $1RETURNING *;diff --git a/server/pkg/db/queries/agent_invocation_target.sql b/server/pkg/db/queries/agent_invocation_target.sqlnew file mode 100644index 0000000000..0b4114e7a6--- /dev/null+++ b/server/pkg/db/queries/agent_invocation_target.sql@@ -0,0 +1,55 @@+-- Agent invocation permission targets (MUL-3963). Rows are the allow-list for+-- agents whose permission_mode = 'public_to'. See migration 130.++-- name: ListAgentInvocationTargets :many+SELECT * FROM agent_invocation_target+WHERE agent_id = $1+ORDER BY target_type ASC, created_at ASC;++-- name: ListAgentInvocationTargetsByAgentIDs :many+-- Batch load for the agent list endpoint so we don't N+1 per agent.+SELECT * FROM agent_invocation_target+WHERE agent_id = ANY(@agent_ids::uuid[])+ORDER BY agent_id, target_type ASC, created_at ASC;++-- name: CreateAgentInvocationTarget :exec+-- Idempotent upsert: re-adding an existing (agent, target_type, target)+-- refreshes created_by/created_at rather than erroring. Callers replace the+-- whole set via DeleteAgentInvocationTargets + a series of these, so the+-- ON CONFLICT is belt-and-suspenders against races.+INSERT INTO agent_invocation_target (agent_id, target_type, target_id, created_by)+VALUES ($1, $2, $3, sqlc.narg('created_by'))+ON CONFLICT (agent_id, target_type, target_id) DO UPDATE SET+ created_by = EXCLUDED.created_by,+ created_at = now();++-- name: DeleteAgentInvocationTargets :exec+-- Clears every target for an agent. Used before re-writing the allow-list so+-- the update is a wholesale replace, matching the composio_toolkit_allowlist+-- write model.+DELETE FROM agent_invocation_target+WHERE agent_id = $1;++-- name: DeleteAgentInvocationTargetsByMember :exec+-- Removes member-target grants pointing at a leaving user, SCOPED to a single+-- workspace. A user may belong to multiple workspaces; removing them from one+-- must NOT touch their invocation grants on agents in another workspace. Joins+-- through agent (agent_invocation_target has no workspace_id column and no FK)+-- to bound the delete to @workspace_id.+DELETE FROM agent_invocation_target ait+USING agent a+WHERE ait.agent_id = a.id+ AND a.workspace_id = @workspace_id+ AND ait.target_type = 'member'+ AND ait.target_id = @target_id;++-- name: DeleteAgentInvocationTargetsByArchivedRuntimeAgents :exec+-- Application-layer replacement for the (deliberately absent) agent_id ON+-- DELETE CASCADE: removes invocation targets for the archived agents a runtime+-- delete is about to hard-delete. MUST run in the same tx as, and BEFORE,+-- DeleteArchivedAgentsByRuntime so no orphan target rows survive the agent+-- rows they belonged to. Mirrors the agent hard-delete predicate exactly.+DELETE FROM agent_invocation_target+WHERE agent_id IN (+ SELECT id FROM agent WHERE runtime_id = $1 AND archived_at IS NOT NULL+);diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 12a56e6134..87f34d5b71 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -110,11 +110,15 @@ WHERE id = $1;-- name: CreateChatTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id,- initiator_user_id, force_fresh_session+ initiator_user_id, originator_user_id, force_fresh_session, runtime_mcp_overlay,+ runtime_connected_apps)VALUES ($1, $2, NULL, 'queued', $3, $4, $5,- COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE)+ sqlc.narg(originator_user_id),+ COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),+ sqlc.narg(runtime_mcp_overlay),+ sqlc.narg(runtime_connected_apps))RETURNING *;diff --git a/server/pkg/db/queries/composio.sql b/server/pkg/db/queries/composio.sqlnew file mode 100644index 0000000000..e4674b4b4b--- /dev/null+++ b/server/pkg/db/queries/composio.sql@@ -0,0 +1,39 @@+-- =====================+-- User Composio Connection+-- =====================++-- name: UpsertUserComposioConnection :one+-- Idempotent on (user_id, connected_account_id): a duplicate callback for the+-- same connected account re-activates the row instead of inserting a second+-- one. connected_at is preserved on conflict (first-connect time); updated_at+-- moves so the reactivation is observable.+INSERT INTO user_composio_connection (+ user_id, toolkit_slug, auth_config_id, connected_account_id, composio_user_id, status+) VALUES (+ $1, $2, $3, $4, $5, 'active'+)+ON CONFLICT (user_id, connected_account_id) DO UPDATE SET+ toolkit_slug = EXCLUDED.toolkit_slug,+ auth_config_id = EXCLUDED.auth_config_id,+ composio_user_id = EXCLUDED.composio_user_id,+ status = 'active',+ updated_at = now()+RETURNING *;++-- name: ListActiveUserComposioConnections :many+SELECT * FROM user_composio_connection+WHERE user_id = $1 AND status = 'active'+ORDER BY connected_at DESC;++-- name: GetUserComposioConnection :one+-- Owner-scoped lookup: a connection can only be read by the user who owns it,+-- so one user cannot disconnect another's account by guessing the UUID.+SELECT * FROM user_composio_connection+WHERE id = $1 AND user_id = $2;++-- name: MarkUserComposioConnectionRevoked :exec+-- Idempotent: re-running on an already-revoked row is a no-op write. Scoped to+-- the owner for defense-in-depth.+UPDATE user_composio_connection+SET status = 'revoked', updated_at = now()+WHERE id = $1 AND user_id = $2;diff --git a/server/pkg/redact/redact_test.go b/server/pkg/redact/redact_test.goindex 3caab19f8e..eb6f0b8829 100644--- a/server/pkg/redact/redact_test.go+++ b/server/pkg/redact/redact_test.go@@ -74,6 +74,22 @@ func TestRedactBearerToken(t *testing.T) {}}+// TestRedactBearerMCPToken is a regression guard for the Composio MCP session+// headers (MUL-3720): the SDK attaches the project key as `Bearer mcp_...` on+// some MCP transports, so the generic Bearer pattern must mask it before it can+// reach a log line or WS broadcast.+func TestRedactBearerMCPToken(t *testing.T) {+ t.Parallel()+ input := "connecting with Authorization: Bearer mcp_AbCdEf0123456789-_token"+ got := Text(input)+ if strings.Contains(got, "mcp_AbCdEf0123456789") {+ t.Fatalf("Bearer mcp_ token not redacted: %s", got)+ }+ if !strings.Contains(got, "Bearer [REDACTED]") {+ t.Fatalf("expected Bearer [REDACTED] placeholder, got: %s", got)+ }+}+func TestRedactGenericCredentials(t *testing.T) {t.Parallel()cases := []struct {